### IntervalSystem Example with Dependency Injection Source: https://github.com/quillraven/fleks/wiki/System An IntervalSystem that updates every frame and uses dependency injection to access an EventManager for dispatching game events. ```kotlin class EventManager { // code omitted } class DayNightSystem( // inject the EventManager instance that is registered below to our world private val eventMgr: EventManager = inject() ) : IteratingSystem() { private var currentTime = 0f private var isDay = false override fun onTick() { // deltaTime is not needed in every system that's why it is not a parameter of "onTick". // However, if you need it, you can still access it via the IteratingSystem's deltaTime property currentTime += deltaTime if (currentTime >= 1000 && !isDay) { isDay = true eventMgr.publishDayEvent() } else if (currentTime >= 2000 && isDay) { isDay = false currentTime = 0f eventMgr.publishNightEvent() } } } fun main() { val world = configureWorld { injectables { // add an EventManager instance as a dependency to the world add(EventManager()) } systems { // here we use DI to create the system but you can of course pass the EventManager instance directly. It is up to you ;) add(DayNightSystem()) } } } ``` -------------------------------- ### Disposing System Resources Source: https://github.com/quillraven/fleks/wiki/System Example of a system that disposes of internal resources, such as a Box2D debug renderer. ```Kotlin class DebugSystem( private val box2dWorld: World = inject(), private val camera: Camera = inject(), stage: Stage = inject() ) : IntervalSystem() { private val renderer = Box2DDebugRenderer() override fun onTick() { physicRenderer.render(box2dWorld, camera.combined) } // this is an optional function that can be used to free specific resources override fun onDispose() { renderer.dispose() } } fun main() { val world = configureWorld { /* configuration omitted */ } // following call disposes the DebugSystem world.dispose() } ``` -------------------------------- ### Registering a Custom EntityProvider Source: https://github.com/quillraven/fleks/wiki/EntityProvider Example of how to register a custom EntityProvider by providing an instance within the configureWorld DSL block. Ensure your custom provider has a 'World' property. ```kotlin class CustomEntityProvider( override val world: World ) : EntityProvider { // implementation omitted } fun main() { configureWorld { entityProvider { CustomEntityProvider(this) } } } ``` -------------------------------- ### Configure Entity Components with Add/Remove/GetOrAdd Source: https://github.com/quillraven/fleks/wiki/System Illustrates modifying an entity's components using the configure block. This example shows adding a DeadComponent, removing a LifeComponent, and conditionally adding or modifying a Damage component based on hitpoints. ```Kotlin data class Life(var hitpoints: Float) : Component { override fun type() = Life companion object : ComponentType() } data class Damage(var amount: Float) : Component { override fun type() = Damage companion object : ComponentType() } class Dead : Component { override fun type() = Dead companion object : ComponentType() } class DeathSystem : IteratingSystem( family { all(Life).none(Dead) } ) { override fun onTickEntity(entity: Entity) { if (entity[Life].hitpoints <= 0f) { // call 'configure' before changing an entity's components entity.configure { it += Dead() it -= Life } } else { entity.configure { // the Damage(0f) instance only gets created, if the entity does not have a damage component yet it.getOrAdd(Damage){ Damage(0f) }.amount += 5f } } } } ``` -------------------------------- ### Fleks Position Component Example Source: https://github.com/quillraven/fleks/wiki/Component An example of a data class representing a Position component. It demonstrates extending `Component` and defining a unique `ComponentType` via its companion object. ```kotlin data class Position( var x: Float, var y: Float, ) : Component { override fun type(): ComponentType = Position // this assigns the Position component a unique ID companion object : ComponentType() } ``` -------------------------------- ### Get Snapshot of Entire World Source: https://github.com/quillraven/fleks/wiki/Debugging Call `world.snapshot()` to get a map of all entities and their components. Useful for a comprehensive overview of your world's state. ```kotlin val snapshot = world.snapshot() ``` -------------------------------- ### Define an IteratingSystem with a Family Source: https://github.com/quillraven/fleks/wiki/System Create an IteratingSystem that iterates over entities matching specific component criteria. This example defines a system that processes entities with Position and Physic components, excluding those with Dead, but including those with either Sprite or Animation. ```Kotlin class AnimationSystem : IteratingSystem( family { all(Position, Physic).none(Dead).any(Sprite, Animation) } ) { override fun onTickEntity(entity: Entity) { // update entities in here } } ``` -------------------------------- ### Get Family with Specific Components Source: https://github.com/quillraven/fleks/wiki/Family Retrieves a family of entities that possess a `MoveComponent` but do not have a `DeadComponent`. This is useful for targeting specific entity subsets for processing. ```kotlin fun main() { val world = configureWorld {} val e1 = world.entity { it += Move(speed = 70f) } val e2 = world.entity { it += Move(speed = 50f) it += Dead() } val e3 = world.entity { it += Move(speed = 30f) } // get family for entities with a MoveComponent and without a DeadComponent val family = world.family { all(Move).none(Dead) } // you can sort entities of a family family.sort(compareEntityBy(Move)) // And you can iterate over entities of a family. // In this example it will iterate in following order: // 1) e3 // 2) e1 family.forEach { entity -> // family also supports the typical entity extension functions like get, has, configure, ... entity.configure { // update entity components } } } ``` -------------------------------- ### Sort Entities by Y-Coordinate using compareEntity Source: https://github.com/quillraven/fleks/wiki/System Implement entity sorting within an IteratingSystem using the compareEntity function. This example sorts entities by their Position component's y-coordinate before processing. ```Kotlin // 1) via the 'compareEntity' function class RenderSystem : IteratingSystem( family = family { all(Position, Render) }, comparator = compareEntity { entA, entB -> entA[Position].y.compareTo(entB[Position].y) } ) { override fun onTickEntity(entity: Entity) { // render entities: entities are sorted by their y-coordinate } } ``` -------------------------------- ### Get Snapshot of a Single Entity Source: https://github.com/quillraven/fleks/wiki/Debugging Use `world.snapshotOf(Entity(id))` to retrieve the components of a specific entity. Helpful for isolating issues related to a particular entity. ```kotlin val eSnapshot = world.snapshotOf(Entity(3)) ``` -------------------------------- ### Sort Entities by Y-Coordinate using compareEntityBy Source: https://github.com/quillraven/fleks/wiki/System Utilize the compareEntityBy function for sorting entities when the relevant component implements the Comparable interface. This example sorts entities by the Position component's y-coordinate. ```Kotlin // 2) via the 'compareEntityBy' function which requires the component to implement the Comparable interface data class Position( var x: Float, var y: Float, ) : Component, Comparable { override fun type() = Position override fun compareTo(other: Position): Int { return y.compareTo(other.y) } companion object : ComponentType() } class RenderSystem : IteratingSystem( family = family { all(Position, Render) }, comparator = compareEntityBy(Position) ) { override fun onTickEntity(entity: Entity) { ``` -------------------------------- ### Creating and Using Families Outside Systems Source: https://github.com/quillraven/fleks/wiki/System Demonstrates how to create a family outside of a system and iterate over its entities. ```Kotlin fun main() { val world = configureWorld {} // Retrieve a family. If a family with such a configuration already exists, then it will be returned. // There are no duplicate families. val family = world.family { all(Position) } family.forEach { entity -> // do something with the entity } } ``` -------------------------------- ### Create a Basic Fleks World Source: https://github.com/quillraven/fleks/wiki/World Initializes a Fleks world. Use the lambda argument to configure its components. ```Kotlin val world = configureWorld {} ``` -------------------------------- ### IntervalSystem with Named Dependencies Source: https://github.com/quillraven/fleks/wiki/System An IntervalSystem demonstrating the use of named dependencies to inject multiple instances of the same type (String in this case) with distinct identifiers. ```kotlin class NamedDependenciesSystem( val hsKey: String = inject("HighscoreKey"), // will have the value hs-key val levelKey: String = inject("LevelKey") // will have the value Level001 ) : IntervalSystem() { // ... } fun main() { configureWorld { injectables { // add two String dependencies via a specific name add("HighscoreKey", "hs-key") ``` -------------------------------- ### Create and Add Components to an Entity Source: https://github.com/quillraven/fleks/wiki/Entity Demonstrates how to create a new entity and add Position and Sprite components to it using the world's entity function. ```Kotlin data class Position( var x: Float, var y: Float, ) : Component { override fun type() = Position companion object : ComponentType() } data class Sprite( var texturePath:String ) : Component { override fun type() = Sprite companion object : ComponentType() } fun main() { val world = configureWorld {} val entity: Entity = world.entity { it += Position(5f, 5f) it += Sprite("texture.png") } } ``` -------------------------------- ### Manual Sorting in IteratingSystem Source: https://github.com/quillraven/fleks/wiki/System Demonstrates how to use Manual sorting in an IteratingSystem by setting the doSort flag. ```Kotlin class RenderSystem : IteratingSystem( family = family { all(Position, Render) }, comparator = compareEntityBy(Position), sortingType = Manual ) { override fun onTick() { doSort = true super.onTick() } override fun onTickEntity(entity: Entity) { // render entities: entities are sorted by their y-coordinate } } ``` -------------------------------- ### Iterating Over Entities with World.forEach Source: https://github.com/quillraven/fleks/wiki/System Shows how to iterate over all active entities in a world using the forEach function outside of a system. ```Kotlin fun main() { val world = configureWorld {} val e1 = world.entity() val e2 = world.entity() val e3 = world.entity() world -= e2 // this will iterate over entities e1 and e3 world.forEach { entity -> // do something with the entity } } ``` -------------------------------- ### IteratingSystem Live Template Source: https://github.com/quillraven/fleks/wiki/System A basic template for creating an IteratingSystem that processes entities with a specific component configuration. ```kotlin import com.github.quillraven.fleks.Entity import com.github.quillraven.fleks.IteratingSystem import com.github.quillraven.fleks.World.Companion.family class $SYSTEM_NAME$ : IteratingSystem( family = family { all($COMPONENTS$) } ) { override fun onTickEntity(entity: Entity) { } } ``` -------------------------------- ### Configure and Serialize Snapshot Source: https://github.com/quillraven/fleks/wiki/Serialization Shows how to configure Kotlinx Serialization for Fleks snapshots, including registering components and tags, and enabling structured map keys. This is used to serialize the world's snapshot. ```kotlin @Serializable data object VisibleTag : EntityTag() @Serializable data class Speed(val max:Int) : Component { override fun type() = Speed companion object : ComponentType() } @Serializable data class Graphic(val texture:String) : Component { override fun type() = Graphic companion object : ComponentType() } fun main() { val world = configureWorld { } // Assuming configureWorld is defined elsewhere world.entity { it += Speed(3) it += Graphic("mySprite.png") it += VisibleTag } // configure Json's serializersModule and allow structured map keys val json = Json { serializersModule = SerializersModule { // register components polymorphic(Component::class) { subclass(Speed::class, Speed.serializer()) subclass(Graphic::class, Graphic.serializer()) } // register tags polymorphic(UniqueId::class) { subclass(VisibleTag::class, VisibleTag.serializer()) } } allowStructuredMapKeys = true // to support entity id + version as a key in a map data structure } val snapshot: Map = world.snapshot() val snapshotJson = json.encodeToString(snapshot) // [{"id":0,"version":0},{"components":[{"type":"com.github.quillraven.fleks.Graphic","texture":"mySprite.png"},{"type":"com.github.quillraven.fleks.Speed","max":3}],"tags":[{"type":"com.github.quillraven.fleks.VisibleTag"}]}] // clear world and load encoded snapshot from before world.removeAll(clearRecycled = true) world.loadSnapshot(json.decodeFromString(snapshotJson)) } ``` -------------------------------- ### System-Level Family Hooks (FamilyOnAdd) Source: https://github.com/quillraven/fleks/wiki/Family Demonstrates using `FamilyOnAdd` interface within an `IteratingSystem` to automatically create a family hook. This simplifies defining reactions to entities being added to a system's family. ```kotlin data class Move(var speed: Float) : Component { override fun type() = Move companion object : ComponentType() } class System1 : IteratingSystem(family { all(Move) }), FamilyOnAdd { override fun onAddEntity(entity: Entity) { // ... } } class System2 : IteratingSystem(family { all(Move) }), FamilyOnAdd { override fun onAddEntity(entity: Entity) { // ... } } fun main() { val world = configureWorld { systems { add(System1()) add(System2()) } } // creating an entity will call System1's onAddEntity first, and then System2's onAddEntity world.entity { it += Move(speed = 3f) } } ``` -------------------------------- ### Configure Fleks World with Capacity, Systems, and Hooks Source: https://github.com/quillraven/fleks/wiki/World Creates a Fleks world with a specified entity capacity, registers injectables, families, systems, and entity hooks. ```Kotlin val w = configureWorld(entityCapacity = 1000) { injectables { add(b2dWorld) } families { val moveFamily = family { all(MoveComponent) } onAdd(moveFamily) {entity -> } onRemove(moveFamily) {entity -> } } systems { add(MoveSystem()) add(PhysicSystem()) } onAddEntity { entity -> } onRemoveEntity { entity -> } } ``` -------------------------------- ### Fleks Entity and Component Manipulation Source: https://github.com/quillraven/fleks/wiki/Component Demonstrates creating an entity, adding a component, accessing and modifying component data, checking for component presence, and removing a component from an entity within a Fleks world. ```kotlin data class Position( var x: Float, var y: Float, ) : Component { override fun type(): ComponentType = Position companion object : ComponentType() } fun main() { val world = configureWorld { } // creating an entity with a position component val entity = world.entity { it += Position(3f, 4f) } // Start a Fleks context. This is only necessary if you are not within a system, family or hook. with(world) { // access and modify the position entity[Position].x = 5f // access in case you are not sure if an entity has a component or not entity.getOrNull(Position)?.let { position -> // ... } // Check if an entity has a position. There is also a 'hasNo' version. if (entity has Position) { // ... } // another way to check if a component is present if (Position in entity) { // ... } // modify an entity by removing its position component entity.configure { it -= Position } } } ``` -------------------------------- ### Configure One-Shot Components in World Source: https://github.com/quillraven/fleks/wiki/One-Shot-Component Register components or tags that should be automatically removed at the end of each frame. This is done within the world configuration block. ```kotlin configureWorld { oneShotComponents(MyComp1, MyTag1) } ``` -------------------------------- ### Encode and Decode Entity Source: https://github.com/quillraven/fleks/wiki/Serialization Demonstrates basic encoding and decoding of an entity using Kotlinx Serialization's Json library. ```kotlin val entity = Entity(id = 0, version = 0u) // encode an entity val jsonStr = Json.encodeToString(entity0) // {"id":0,"version":0} // decode an entity val decodedEntity: Entity = Json.decodeFromString(jsonStr) ``` -------------------------------- ### Adding Snapshot Repository (Kotlin) Source: https://github.com/quillraven/fleks/blob/master/ReadMe.md Configure your Maven repository to include snapshots if you are using the snapshot version of Fleks with Kotlin DSL. ```gradle maven { url = uri("https://central.sonatype.com/repository/maven-snapshots/") } ``` -------------------------------- ### Adding Snapshot Repository (Groovy) Source: https://github.com/quillraven/fleks/blob/master/ReadMe.md Configure your Maven repository to include snapshots if you are using the snapshot version of Fleks with Groovy DSL. ```gradle maven { url 'https://central.sonatype.com/repository/maven-snapshots/' } ``` -------------------------------- ### Load Snapshot into World Source: https://github.com/quillraven/fleks/wiki/Debugging Call `world.loadSnapshot(snapshot)` to replace the current world state with a provided snapshot. This will clear existing entities. ```kotlin world.loadSnapshot(snapshot) ``` -------------------------------- ### Component Lifecycle Hooks (onAdd, onRemove) Source: https://github.com/quillraven/fleks/wiki/Entity Illustrates using onAdd and onRemove lifecycle methods within a component to manage external resources like Box2D bodies when the component is added to or removed from an entity. ```Kotlin import com.badlogic.gdx.physics.box2d.World as PhysicWorld class Box2dComponent : Component { lateinit var body: Body override fun type() = Box2dComponent override fun World.onAdd(entity: Entity) { body = inject().createBody( /* body creation code omitted */) body.userData = entity } override fun World.onRemove(entity: Entity) { body.world.destroyBody(body) body.userData = null } companion object : ComponentType() } fun main() { val b2dWorld = PhysicWorld() val world = configureWorld { injectables { add(b2dWorld) } } val entity = world.entity { // this triggers the onAdd hook it += Box2dComponent() } // to update an entity outside a system, family or hook, use Kotlin's "with" // to run code in context of a World. This enables certain entity extension functions. with(world) { // Use 'configure' to update the components of an entity. entity.configure { // this triggers the onRemove hook entity -= Box2dComponent } } ``` -------------------------------- ### Accessing Components in an IteratingSystem Source: https://github.com/quillraven/fleks/wiki/System Demonstrates how to access a specific component, Position, from an entity within the onTickEntity method of an IteratingSystem. Ensure the Position component is defined and accessible. ```Kotlin class Position : Component { override fun type() = Position companion object : ComponentType() } class AnimationSystem : IteratingSystem( family { all(Position, Physic).none(Dead).any(Sprite, Animation) } ) { override fun onTickEntity(entity: Entity) { val entityPosition: Position = entity[Position] } } ``` -------------------------------- ### Family Hooks for Entity Add/Remove Events Source: https://github.com/quillraven/fleks/wiki/Family Configures a world with family hooks to react when entities are added to or removed from a specific family. This allows for event-driven logic based on entity lifecycle within a family. ```kotlin fun main() { val world = configureWorld { families { // hook that reacts on entities that have a MoveComponent and do not have a DeadComponent val family = family { all(Move).none(Dead) } onAdd(family) { entity -> } onRemove(family) { entity -> } } } // this will trigger the 'onAdd' hook val entity1 = world.entity { it += Move() } // this will trigger the 'onRemove' hook world -= entity1 // this will NOT trigger any hook because the entity is never part of the family val entity2 = world.entity { it += Move() it += Dead() // <-- that's the reason } world -= entity2 } ``` -------------------------------- ### Define a Simple Entity Tag Source: https://github.com/quillraven/fleks/wiki/Tag Define a tag as a data object. This is useful for marking entities with specific information. ```kotlin data object Visible : EntityTag() ``` -------------------------------- ### Snapshot Data Class Source: https://github.com/quillraven/fleks/wiki/Serialization Defines the structure of a snapshot, containing a list of components and tags. ```kotlin data class Snapshot( val components: List>, val tags: List>, ) ``` -------------------------------- ### Add Fleks Dependency with Gradle (Groovy) Source: https://github.com/quillraven/fleks/wiki/Setup Integrate Fleks into your project using Gradle with Groovy syntax. Replace '2.14' with the version you need. ```groovy implementation 'io.github.quillraven.fleks:Fleks:2.14' ``` -------------------------------- ### Add Fleks Dependency with Gradle (Kotlin) Source: https://github.com/quillraven/fleks/wiki/Setup Add Fleks to your project using Gradle with Kotlin DSL. Adjust the version number as necessary. ```kotlin implementation("io.github.quillraven.fleks:Fleks:2.14") ``` -------------------------------- ### Load Snapshot for a Specific Entity Source: https://github.com/quillraven/fleks/wiki/Debugging Use `world.loadSnapshotOf(Entity(id), eSnapshot)` to update a specific entity's components with a given snapshot. If the entity doesn't exist, it will be created. ```kotlin val eSnapshot = world.snapshotOf(Entity(3)) world.loadSnapshotOf(Entity(3), eSnapshot) ``` -------------------------------- ### Add Fleks Dependency with Maven Source: https://github.com/quillraven/fleks/wiki/Setup Use this snippet to add the Fleks library to your project when using Apache Maven as your build tool. Ensure you specify the desired version. ```xml io.github.quillraven.fleks Fleks-jvm 2.14 ``` -------------------------------- ### Define Entity Tags using Enum Class Source: https://github.com/quillraven/fleks/wiki/Tag Create multiple tags using an enum class and the `entityTagOf` function. This provides a concise way to manage a set of related tags. ```kotlin enum class MyTags : EntityTags by entityTagOf() { PLAYER, VISIBLE } ``` -------------------------------- ### Fleks Entity Data Class (Post 2.5) Source: https://github.com/quillraven/fleks/wiki/Entity Shows the structure of an Entity object since Fleks version 2.5, which includes an ID and a version number for safe entity referencing. ```Kotlin data class Entity(val id: Int, val version: UInt) { companion object { val NONE = Entity(-1, 0u) } } ``` -------------------------------- ### Fleks Component Boilerplate Source: https://github.com/quillraven/fleks/wiki/Component This is the basic template for creating a Fleks component. It requires implementing the `Component` interface and defining a `type` function. ```kotlin import com.github.quillraven.fleks.Component import com.github.quillraven.fleks.ComponentType class $FLEKS_COMPONENT$ : Component<$FLEKS_COMPONENT$> { override fun type() = $FLEKS_COMPONENT$ companion object : ComponentType<$FLEKS_COMPONENT$>() } ``` -------------------------------- ### Fleks Sprite Component with Differentiated Types Source: https://github.com/quillraven/fleks/wiki/Component Illustrates how to create differentiated component types for the same data class using a custom `type` function and the `componentTypeOf` helper. ```kotlin data class Sprite( val background: Boolean, var path: String = "", ) : Component { override fun type(): ComponentType { return when (background) { true -> SpriteBackground else -> SpriteForeground } } companion object { val SpriteForeground = componentTypeOf() val SpriteBackground = componentTypeOf() } } ``` -------------------------------- ### Fleks EntityProvider Interface Definition Source: https://github.com/quillraven/fleks/wiki/EntityProvider The definition of the EntityProvider interface, outlining the methods and properties required for custom entity ID management. ```kotlin interface EntityProvider { val world: World fun numEntities(): Int fun create(): Entity fun create(id: Int): Entity operator fun minusAssign(entity: Entity) operator fun contains(entity: Entity): Boolean fun reset() fun forEach(action: World.(Entity) -> Unit) } ``` -------------------------------- ### Add Fleks Dependency with KorGE Source: https://github.com/quillraven/fleks/wiki/Setup Configure your KorGE project to use Fleks by adding this dependency. The `registerPlugin` parameter is set to `false`. ```kotlin dependencyMulti("io.github.quillraven.fleks:Fleks:2.14", registerPlugin = false) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.