/
entity.kt
567 lines (495 loc) · 19.1 KB
/
entity.kt
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
package com.github.quillraven.fleks
import com.github.quillraven.fleks.collection.*
import kotlinx.serialization.Serializable
import kotlin.jvm.JvmInline
/**
* An entity of a [world][World]. It represents a unique id.
*/
@JvmInline
@Serializable
value class Entity(val id: Int)
/**
* Type alias for an optional hook function for an [EntityService].
* Such a function runs within a [World] and takes the [Entity] as an argument.
*/
typealias EntityHook = World.(Entity) -> Unit
/**
* A class for basic [Entity] extension functions within a [Family],
* [IntervalSystem], [World] or [compareEntity].
*/
abstract class EntityComponentContext(
@PublishedApi
internal val componentService: ComponentService
) {
/**
* Returns a [component][Component] of the given [type] for the [entity][Entity].
*
* @throws [FleksNoSuchEntityComponentException] if the [entity][Entity] does not have such a component.
*/
inline operator fun <reified T : Component<*>> Entity.get(type: ComponentType<T>): T =
componentService.holder(type)[this]
/**
* Returns a [component][Component] of the given [type] for the [entity][Entity]
* or null if the [entity][Entity] does not have such a [component][Component].
*/
inline fun <reified T : Component<*>> Entity.getOrNull(type: ComponentType<T>): T? =
componentService.holder(type).getOrNull(this)
/**
* Returns true if and only if the [entity][Entity] has a [component][Component] of the given [type].
*/
inline operator fun <reified T : Component<*>> Entity.contains(type: ComponentType<T>): Boolean =
this in componentService.holder(type)
/**
* Returns true if and only if the [entity][Entity] has a [component][Component] of the given [type].
*/
inline infix fun <reified T : Component<*>> Entity.has(type: ComponentType<T>): Boolean =
this in componentService.holder(type)
/**
* Returns true if and only if the [entity][Entity] doesn't have a [component][Component] of the given [type].
*/
inline infix fun <reified T : Component<*>> Entity.hasNo(type: ComponentType<T>): Boolean =
this !in componentService.holder(type)
/**
* Updates the [entity][Entity] using the given [configuration] to add and remove [components][Component].
*
* **Attention** Make sure that you only modify the entity of the current scope.
* Otherwise, you will get wrong behavior for families. E.g. don't do this:
*
* ```
* entity.configure {
* // modifying the current entity is allowed ✅
* it += Position()
* // don't modify other entities ❌
* someOtherEntity += Position()
* }
* ```
*/
inline fun Entity.configure(configuration: EntityUpdateContext.(Entity) -> Unit) =
componentService.world.entityService.configure(this, configuration)
/**
* Removes the [entity][Entity] from the world. The [entity][Entity] will be recycled and reused for
* future calls to [World.entity].
*/
fun Entity.remove() = componentService.world.minusAssign(this)
}
/**
* A class that extends the extension functionality of an [EntityComponentContext] by also providing
* the possibility to create [components][Component].
*/
open class EntityCreateContext(
compService: ComponentService,
@PublishedApi
internal val compMasks: Bag<BitArray>,
) : EntityComponentContext(compService) {
/**
* Adds the [component] to the [entity][Entity].
*
* The [onAdd][Component.onAdd] lifecycle method
* gets called after the [component] is assigned to the [entity][Entity].
*
* If the [entity][Entity] already had such a [component] then the [onRemove][Component.onRemove]
* lifecycle method gets called on the previously assigned component before the [onAdd][Component.onAdd]
* lifecycle method is called on the new component.
*/
inline operator fun <reified T : Component<T>> Entity.plusAssign(component: T) {
val compType: ComponentType<T> = component.type()
compMasks[this.id].set(compType.id)
val holder: ComponentsHolder<T> = componentService.holder(compType)
holder[this] = component
}
/**
* Adds the [components] to the [entity][Entity]. This function should only be used
* in exceptional cases.
* It is preferred to use the [plusAssign] function whenever possible to have type-safety.
*
* The [onAdd][Component.onAdd] lifecycle method
* gets called after each component is assigned to the [entity][Entity].
*
* If the [entity][Entity] already has such a component then the [onRemove][Component.onRemove]
* lifecycle method gets called on the previously assigned component before the [onAdd][Component.onAdd]
* lifecycle method is called on the new component.
*/
operator fun Entity.plusAssign(components: List<Component<*>>) {
components.forEach { cmp ->
val compType = cmp.type()
compMasks[this.id].set(compType.id)
val holder = componentService.wildcardHolder(compType)
holder.setWildcard(this, cmp)
}
}
}
/**
* A class that extends the extension functionality of an [EntityCreateContext] by also providing
* the possibility to update [components][Component].
*/
class EntityUpdateContext(
compService: ComponentService,
compMasks: Bag<BitArray>,
) : EntityCreateContext(compService, compMasks) {
/**
* Removes a [component][Component] of the given [type] from the [entity][Entity].
*
* Calls the [onRemove][Component.onRemove] lifecycle method on the component being removed.
*
* @throws [IndexOutOfBoundsException] if the id of the [entity][Entity] exceeds the internal components' capacity.
* This can only happen when the [entity][Entity] never had such a component.
*/
inline operator fun <reified T : Component<*>> Entity.minusAssign(type: ComponentType<T>) {
compMasks[this.id].clear(type.id)
componentService.holder(type) -= this
}
/**
* Returns a [component][Component] of the given [type] for the [entity][Entity].
*
* If the [entity][Entity] does not have such a [component][Component] then [add] is called
* to assign it to the [entity][Entity] and return it.
*/
inline fun <reified T : Component<T>> Entity.getOrAdd(
type: ComponentType<T>,
add: () -> T,
): T {
val holder: ComponentsHolder<T> = componentService.holder(type)
val existingCmp = holder.getOrNull(this)
if (existingCmp != null) {
return existingCmp
}
compMasks[this.id].set(type.id)
val newCmp = add()
holder[this] = newCmp
return newCmp
}
}
/**
* Interface to describe the functionality needed by an [EntityService]
* to create and remove [entities][Entity]. The provider can be specified
* via the [WorldConfiguration]. Per default a [DefaultEntityProvider] will be used.
*/
interface EntityProvider {
/**
* Reference to the [World] of the [EntityProvider].
* It is needed for the [forEach] implementation.
*/
val world: World
/**
* Returns the total amount of active [entities][Entity].
*/
fun numEntities(): Int
/**
* Creates a new [entity][Entity].
*/
fun create(): Entity
/**
* Creates a new [Entity] with a specific [id].
* Internally, this is only needed by [World.loadSnapshotOf] and
* if that is not used, then this function can be omitted.
*/
fun create(id: Int): Entity
/**
* Removes an [entity][Entity].
*/
operator fun minusAssign(entity: Entity)
/**
* Returns true if and only if the given [entity] is active and part of the provider.
*/
operator fun contains(entity: Entity): Boolean
/**
* Resets the provider by removing all [entities][Entity].
*/
fun reset()
/**
* Performs the given [action] for all active [entities][Entity].
*/
fun forEach(action: World.(Entity) -> Unit)
}
/**
* Default implementation of an [EntityProvider] which uses an [entity][Entity]
* recycling mechanism to reuse [entities][Entity] that get removed.
* The first [entity][Entity] starts with ID zero.
*/
class DefaultEntityProvider(
override val world: World,
initialEntityCapacity: Int
) : EntityProvider {
/**
* The id that will be given to a newly created [entity][Entity] if there are no [recycledEntities].
*/
private var nextId = 0
/**
* Separate BitArray to remember if an [entity][Entity] was already removed.
* This is faster than looking up the [recycledEntities].
*/
private val removedEntities = BitArray(initialEntityCapacity)
/**
* The already removed [entities][Entity] which can be reused whenever a new entity is needed.
*/
private val recycledEntities = ArrayDeque<Entity>()
/**
* Returns the total amount of active [entities][Entity].
*/
override fun numEntities(): Int = nextId - recycledEntities.size
/**
* Creates a new [entity][Entity]. If there are [recycledEntities] then they will be preferred
* over creating new entities.
*/
override fun create(): Entity {
return if (recycledEntities.isEmpty()) {
Entity(nextId++)
} else {
val recycled = recycledEntities.removeLast()
removedEntities.clear(recycled.id)
// because of the load snapshot functionality of the world, it is
// possible that an entity with an ID higher than nextId gets recycled
// and immediately created afterward. In such a case we need to correct the
// nextId to avoid creating duplicated entities.
if (recycled.id >= nextId) {
nextId = recycled.id + 1
}
recycled
}
}
/**
* Creates a new [Entity] with a specific [id].
*/
override fun create(id: Int): Entity {
if (id >= nextId) {
// entity with given id was never created before -> create all missing entities ...
repeat(id - nextId + 1) {
this -= Entity(nextId + it)
}
// ... and then create the entity to guarantee that it has the correct ID.
// The entity is at the end of the recycled list.
// adjust ID for future entities to be created
nextId = id + 1
return create()
} else {
// entity with given id was already created before and is part of the recycled entities
// -> move it to the end to be used by the next create call
recycledEntities.remove(Entity(id))
recycledEntities.addLast(Entity(id))
return create()
}
}
/**
* Removes an [entity][Entity].
*/
override operator fun minusAssign(entity: Entity) {
recycledEntities.add(entity)
removedEntities.set(entity.id)
}
/**
* Returns true if and only if the given [entity] is active and part of the provider.
*/
override fun contains(entity: Entity): Boolean = entity.id in 0 until nextId && !removedEntities[entity.id]
/**
* Resets the provider by removing and recycling all [entities][Entity].
* Also, resets the [nextId] to zero.
*/
override fun reset() {
nextId = 0
recycledEntities.clear()
removedEntities.clearAll()
}
/**
* Performs the given [action] for all active [entities][Entity].
*/
override fun forEach(action: World.(Entity) -> Unit) {
for (id in 0 until nextId) {
val entity = Entity(id)
if (removedEntities[entity.id]) {
continue
}
world.action(entity)
}
}
}
/**
* A service class that is responsible for creation and removal of [entities][Entity].
* It also stores the component configuration of each entity as a [BitArray] to have quick access to
* what kind of components an entity has or doesn't have.
*/
class EntityService(
@PublishedApi
internal val world: World,
initialEntityCapacity: Int,
@PublishedApi
internal var entityProvider: EntityProvider = DefaultEntityProvider(world, initialEntityCapacity),
private val compService: ComponentService = world.componentService,
) {
/**
* Returns the amount of active entities.
*/
val numEntities: Int
get() = entityProvider.numEntities()
/**
* Returns the maximum capacity of active entities.
*/
val capacity: Int
get() = compMasks.capacity
/**
* The component configuration per [entity][Entity].
*/
@PublishedApi
internal val compMasks = bag<BitArray>(initialEntityCapacity)
@PublishedApi
internal val createCtx = EntityCreateContext(compService, compMasks)
@PublishedApi
internal val updateCtx = EntityUpdateContext(compService, compMasks)
/**
* Flag that indicates if an iteration of an [IteratingSystem] is currently in progress.
* In such cases entities will not be removed immediately.
* Refer to [IteratingSystem.onTick] for more details.
*/
@PublishedApi
internal var delayRemoval = false
/**
* The entities that get removed at the end of an [IteratingSystem] iteration.
*/
private val delayedEntities = MutableEntityBag()
/**
* An optional [EntityHook] that gets called whenever an [entity][Entity] gets created and
* after its [components][Component] are assigned and [families][Family] are updated.
*/
@PublishedApi
internal var addHook: EntityHook? = null
/**
* An optional [EntityHook] that gets called whenever an [entity][Entity] gets removed and
* before its [components][Component] are removed and [families][Family] are updated.
*/
@PublishedApi
internal var removeHook: EntityHook? = null
/**
* Creates and returns a new [entity][Entity] and applies the given [configuration].
* Notifies all [families][World.allFamilies].
*/
inline fun create(configuration: EntityCreateContext.(Entity) -> Unit): Entity =
postCreate(entityProvider.create(), configuration)
/**
* Creates and returns a new [entity][Entity] with the given [id] and applies the given [configuration].
* Notifies all [families][World.allFamilies].
*/
inline fun create(id: Int, configuration: EntityCreateContext.(Entity) -> Unit): Entity =
postCreate(entityProvider.create(id), configuration)
/**
* Applies the given [configuration] to the [entity] and notifies all [families][World.allFamilies].
* The [addHook] is invoked at the end, if provided.
*/
@PublishedApi
internal inline fun postCreate(
entity: Entity,
configuration: EntityCreateContext.(Entity) -> Unit
): Entity {
// add components
if (entity.id >= compMasks.size) {
compMasks[entity.id] = BitArray(64)
}
val compMask = compMasks[entity.id]
createCtx.configuration(entity)
// update families
world.allFamilies.forEach { it.onEntityAdded(entity, compMask) }
// trigger optional add hook
addHook?.invoke(world, entity)
return entity
}
/**
* Updates an [entity] with the given [configuration].
* Notifies all [families][World.allFamilies].
*/
inline fun configure(entity: Entity, configuration: EntityUpdateContext.(Entity) -> Unit) {
val compMask = compMasks[entity.id]
updateCtx.configuration(entity)
world.allFamilies.forEach { it.onEntityCfgChanged(entity, compMask) }
}
/**
* Updates an [entity] with the given [components].
* Notifies all [families][World.allFamilies].
* This function is only used by [World.loadSnapshot] and [World.loadSnapshotOf],
* and is therefore working with unsafe wildcards ('*').
*/
internal fun configure(entity: Entity, components: List<Component<*>>) {
val compMask = compMasks[entity.id]
// remove any existing components that are not part of the new components to set
compMask.forEachSetBit { cmpId ->
if (components.any { it.type().id == cmpId }) return@forEachSetBit
// we can use holderByIndex because we can be sure that the holder already exists
// because otherwise the entity would not even have the component
compService.holderByIndex(cmpId) -= entity
}
compMask.clearAll()
// set new components
components.forEach { cmp ->
val holder = compService.wildcardHolder(cmp.type())
holder.setWildcard(entity, cmp)
compMask.set(cmp.type().id)
}
// notify families
world.allFamilies.forEach { it.onEntityCfgChanged(entity, compMask) }
}
/**
* Recycles the given [entity] and resets its component mask with an empty [BitArray].
* This function is only used by [World.loadSnapshot].
*/
internal fun recycle(entity: Entity) {
entityProvider -= entity
compMasks[entity.id] = BitArray(64)
}
/**
* Removes the given [entity]. If [delayRemoval] is set then the [entity]
* is not removed immediately and instead will be cleaned up within the [cleanupDelays] function.
*
* Notifies all [families][World.allFamilies] when the [entity] gets removed.
*/
operator fun minusAssign(entity: Entity) {
if (entity !in entityProvider) {
// entity is already removed
return
}
if (delayRemoval) {
delayedEntities += entity
} else {
entityProvider -= entity
val compMask = compMasks[entity.id]
// trigger optional remove hook
removeHook?.invoke(world, entity)
// remove components
compMask.forEachSetBit { compId ->
compService.holderByIndex(compId) -= entity
}
compMask.clearAll()
// update families
world.allFamilies.forEach { it.onEntityRemoved(entity) }
}
}
/**
* Removes all [entities][Entity]. If [clearRecycled] is true then the
* recycled entities are cleared and the ids for newly created entities start at 0 again.
*
* Refer to [remove] for more details.
*/
fun removeAll(clearRecycled: Boolean = false) {
entityProvider.forEach { this -= it }
if (clearRecycled) {
entityProvider.reset()
compMasks.clear()
}
}
/**
* Returns true if and only if the [entity] is not removed and is part of the [EntityService].
*/
operator fun contains(entity: Entity): Boolean = entity in entityProvider
/**
* Performs the given [action] on each active [entity][Entity].
*/
fun forEach(action: World.(Entity) -> Unit) {
entityProvider.forEach(action)
}
/**
* Clears the [delayRemoval] flag and removes [entities][Entity] which are part of the [delayedEntities].
*/
fun cleanupDelays() {
delayRemoval = false
if (delayedEntities.isNotEmpty()) {
delayedEntities.forEach { this -= it }
delayedEntities.clear()
}
}
}