/
EntityManager.swift
80 lines (67 loc) · 2.25 KB
/
EntityManager.swift
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
//
// EntityManager.swift
// star-dash
//
// Created by Lau Rui han on 12/3/24.
//
import Foundation
typealias ComponentSet = Set<ComponentId>
typealias ComponentMap = [ComponentId: Component]
typealias EntityMap = [EntityId: Entity]
typealias EntityComponentMap = [EntityId: ComponentSet]
class EntityManager {
var componentMap: ComponentMap
var entityMap: EntityMap
var entityComponentMap: EntityComponentMap
init(componentMap: ComponentMap, entityMap: EntityMap, entityComponentMap: EntityComponentMap) {
self.componentMap = componentMap
self.entityMap = entityMap
self.entityComponentMap = entityComponentMap
}
convenience init() {
self.init(componentMap: .init(), entityMap: .init(), entityComponentMap: .init())
}
func add(component: Component) {
guard self.componentMap[component.id] == nil else {
return
}
self.componentMap[component.id] = component
self.entityComponentMap[component.entityId]?.insert(component.id)
}
func add(entity: Entity) {
guard self.entityMap[entity.id] == nil else {
return
}
self.entityMap[entity.id] = entity
self.entityComponentMap[entity.id] = Set()
}
func remove(entity: Entity) {
entityMap[entity.id] = nil
guard let componentIds = entityComponentMap[entity.id] else {
return
}
for componentId in componentIds {
componentMap[componentId] = nil
}
entityComponentMap[entity.id] = nil
}
func entity(with entityId: EntityId) -> Entity? {
entityMap[entityId]
}
func playerEntityId() -> EntityId? {
// TOODO: Add parameter to specify the player index
for entityId in entityMap.keys where component(ofType: PlayerComponent.self, of: entityId) != nil {
return entityId
}
return nil
}
func component<T: Component>(ofType type: T.Type, of entityId: EntityId) -> T? {
guard let components = entityComponentMap[entityId] else {
return nil
}
guard let componentId = components.first(where: { componentMap[$0] is T }) else {
return nil
}
return componentMap[componentId] as? T
}
}