Quillraven / Fleks

Fast, lightweight, multi-platform entity component system in Kotlin
MIT License
180 stars 20 forks source link

break through new Component/ComponentType approach #68

Closed Quillraven closed 2 years ago

Quillraven commented 2 years ago

This is just a draft PR for potential Fleks 2.0 changes.

At the moment it is a quick breakthrough implementation of a new Component and ComponentType. That way we can remove the reflection stuff for components completely for JVM. For KMP it is no longer necessary to register a factory method for components.

Discussion continues in the "Discussions" area for Fleks ;)

example of new API:

// new Component interface; requires to override the type() function to return a ComponentType
data class Position(var x: Float = 0f, var y: Float = 0f) : Component<Position> {
   companion object : ComponentType<Position>()

   override fun type() = Position
}

// we can keep existing stuff of course like ComponentListener. They will still work as before
class PositionComponentListener : ComponentListener<Position> {
    override fun onComponentAdded(entity: Entity, component: Position) {
        println("added")
    }

    override fun onComponentRemoved(entity: Entity, component: Position) = Unit
}

// No need to inject ComponentMapper anymore; we can directly access components of an entity in a system like
// in this example via "entity[Position]"
@AllOf([Position::class])
class PositionSystem : IteratingSystem() {
    override fun onTickEntity(entity: Entity) {
        println(entity[Position])
    }
}

fun main() {
    val w = world {
        components {
            add<PositionComponentListener>()
        }

        systems {
            add<PositionSystem>()
        }
    }

    w.entity {
        // components are no longer created via reflection. They are directly created and added by the user
        it += Position(2f, 3f)
    }

    w.update(1f)
}
Quillraven commented 2 years ago

I will close this one and open a new one that is based on the KMP branch