-
Notifications
You must be signed in to change notification settings - Fork 1
/
EntityManager.swift
102 lines (81 loc) · 2.69 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
//
// 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 {
private var componentMap: ComponentMap
private var entityMap: EntityMap
private 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())
}
var entities: [Entity] {
Array(entityMap.values)
}
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 remove(entityId: EntityId) {
guard let entity = entity(with: entityId) else {
return
}
remove(entity: entity)
}
func entity(with entityId: EntityId) -> Entity? {
entityMap[entityId]
}
func playerEntityId(with playerIndex: Int) -> EntityId? {
for entityId in entityMap.keys {
if let playerComponent = component(ofType: PlayerComponent.self, of: entityId),
playerComponent.playerIndex == playerIndex {
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
}
func components<T: Component>(ofType type: T.Type) -> [T] {
componentMap.values.compactMap({ $0 as? T })
}
}