summaryrefslogtreecommitdiff
path: root/composeApp/src/commonMain/kotlin/coffee/liz/ecs/Entity.kt
blob: 0ee604c8e22d41b779171025fcd889e93422ba98 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package coffee.liz.ecs

import kotlin.reflect.KClass

/**
 * An entity is a unique identifier with a collection of components.
 */
class Entity(
    val id: Int,
) {
    private val components = mutableMapOf<KClass<out Component>, Component>()

    /**
     * Add [Component].
     */
    fun <T : Component> add(component: T): Entity {
        components[component::class] = component
        return this
    }

    /**
     * Remove [Component].
     */
    fun <T : Component> remove(type: KClass<T>): Entity {
        components.remove(type)
        return this
    }

    /**
     * Get [Component]
     */
    @Suppress("UNCHECKED_CAST")
    fun <T : Component> get(type: KClass<T>): T = components[type] as T

    /**
     * Has [Component]
     */
    fun <T : Component> has(type: KClass<T>): Boolean = components.containsKey(type)

    /**
     * [Component]s of this entity.
     */
    fun componentTypes(): Set<KClass<out Component>> = components.keys.toSet()

    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (other !is Entity) return false
        return id == other.id
    }

    override fun hashCode(): Int = id

    override fun toString(): String = "Entity($id)"
}