mani-game-engine 1.0.0-pre.8 → 1.0.0-pre.81

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/entity.ts CHANGED
@@ -1,116 +1,241 @@
1
1
  import {GameEngine} from './gameEngine';
2
2
  import {Signal} from 'mani-signal';
3
3
  import {Class} from './types';
4
- import {entityComponents} from './ecsInjector';
4
+ import {ID, putIfAbsent} from './injector';
5
+ import {EcsInjector} from './ecsInjector';
5
6
 
6
7
  let idCounter = 0;
7
8
 
8
9
  export class Entity {
9
10
 
10
- readonly id: number;
11
- readonly children = new Set<Entity>();
12
- private gameEngine?: GameEngine;
11
+ readonly children = new Set<Entity>();
12
+ readonly gameEngine?: GameEngine;
13
+
14
+ get isAdded() {
15
+ return !!this.gameEngine;
16
+ }
17
+
18
+ // TODO: use single rootEntity class instead of undefined?
19
+ private _parent?: Entity;
20
+ readonly parentChanged = new Signal();
21
+ readonly onRemove = new Signal();
22
+ private markRemoval = false;
23
+ private _detached = false;
24
+ readonly _signalMap: Map<ID, Signal> = new Map<ID, Signal>();
25
+
26
+ // this is filled by the injector
27
+ private _components?: Map<Class, InstanceType<any>>;
28
+ get components(): ReadonlyMap<Class, InstanceType<any>> {
29
+ if (!this._components) {
30
+ this._components = new Map<Class, InstanceType<any>>();
31
+ EcsInjector.entityComponents.get(this.constructor as Class)!.forEach((field, componentClass) =>
32
+ this._components!.set(componentClass, (this as any)[field]));
33
+ }
34
+ return this._components;
35
+ }
13
36
 
14
- // TODO: use single rootEntity class instead of undefined?
15
- private _parent?: Entity;
16
- readonly parentChanged = new Signal();
17
- readonly onRemove = new Signal();
18
- private markRemoval = false;
37
+ private _dynamicComponents = new Map<Class, InstanceType<any>>();
19
38
 
20
- constructor() {
21
- this.id = idCounter++;
22
- }
39
+ readonly dynamicComponentAdded = new Signal<InstanceType<any>>();
40
+ readonly dynamicComponentRemoved = new Signal<InstanceType<any>>();
23
41
 
24
- async onBeforeRemove?(): Promise<void>;
42
+ get dynamicComponents(): ReadonlyMap<Class, InstanceType<any>> {
43
+ return this._dynamicComponents;
44
+ }
25
45
 
26
- private setParent(parent: Entity | undefined) {
27
- if (parent === this._parent) {
28
- //TODO: i think this check can be removed
29
- throw Error('same parent');
30
- }
31
- this._parent = parent;
32
- this.parentChanged.dispatch();
46
+ // TODO: move the logic to gameEngine?
47
+ addDynamicComponent<T extends Class>(component: InstanceType<T>): this {
48
+ if (this.hasDynamicComponentClass(component.constructor)) {
49
+ throw new Error('component of this class already added');
33
50
  }
34
-
35
- get parent(): Entity | undefined {
36
- return this._parent;
51
+ if (!this.gameEngine) {
52
+ this._dynamicComponents.set(component.constructor as T, component);
53
+ this.dynamicComponentAdded.dispatch(component);
54
+ return this;
37
55
  }
38
56
 
39
- getComponent<T extends Class>(componentClass: T): InstanceType<T> | undefined {
40
- const componentMap = entityComponents.get(this.constructor as Class);
41
- if (!componentMap) {
42
- throw new Error(`No components in entity of type '${this.constructor.name}'.`);
43
- }
44
- const key = componentMap.get(componentClass as T);
45
- return key && (<any>this)[key];
57
+ this.gameEngine.maybeDefer(() => {
58
+ this._dynamicComponents.set(component.constructor as T, component);
59
+ this.dynamicComponentAdded.dispatch(component);
60
+ // it could be that we are within the system creation loop (component is added within a constructor of a system)
61
+ const systemContexts = this.gameEngine!.injector.createSystemsForDynamicComponents(component.constructor, this);
62
+
63
+ if (!systemContexts) return this;
64
+ const preparePromises = [];
65
+ for (const context of systemContexts) {
66
+ context.system.onPrepare && preparePromises.push(context.system.onPrepare());
67
+ }
68
+ for (const context of systemContexts) {
69
+ this.gameEngine!['entitySystemMap'].get(this)?.add(context);
70
+ // (this.gameEngine as any).addSystemContextSetToMap(this, systemContexts);
71
+ }
72
+
73
+ if (preparePromises.length === 0) {
74
+ this.gameEngine!['startSystems'](systemContexts, () => {});
75
+ } else {
76
+ Promise.all(preparePromises).then(() => this.gameEngine?.['startSystems'](systemContexts));
77
+ }
78
+ });
79
+ return this;
80
+ }
81
+
82
+ hasDynamicComponentClass<T extends Class>(componentClass: T): boolean {
83
+ return this._dynamicComponents.has(componentClass);
84
+ }
85
+
86
+ // TODO: move the logic to gameEngine?
87
+ removeDynamicComponentClass<T extends Class>(componentClass: T) {
88
+ const systemContexts = this.gameEngine?.['entitySystemMap'].get(this);
89
+ systemContexts?.forEach(systemContext => {
90
+ const systemToDependencies = this.gameEngine?.injector['dynamicComponentDependencyMap'];
91
+ const dependencies = systemToDependencies?.get((systemContext.system as any).constructor);
92
+ if (!dependencies) return;
93
+ if (dependencies.some(dependency => dependency.type === componentClass)) {
94
+ this.gameEngine?.['disposeContext']?.(systemContext);
95
+ systemContexts?.delete(systemContext);
96
+ }
97
+ });
98
+ const component = this._dynamicComponents.get(componentClass);
99
+ if (!this._dynamicComponents.delete(componentClass)) {
100
+ throw new Error('component not found: ' + JSON.stringify(componentClass));
46
101
  }
102
+ this.dynamicComponentRemoved.dispatch(component);
103
+ }
47
104
 
48
- async add(entity: Entity) {
49
- if (entity.parent === this) {
50
- throw new Error('Entity is already a child');
51
- }
52
- if (entity === this) {
53
- throw new Error('Could not add Entity as a child of itself.');
54
- }
105
+ removeDynamicComponent<T extends Class>(component: InstanceType<T>) {
106
+ this.removeDynamicComponentClass(component.constructor as T);
107
+ }
55
108
 
56
- if (entity.parent) {
57
- entity.parent.children.delete(entity);
58
- }
59
- this.children.add(entity);
60
- entity.setParent(this);
109
+ getDynamicComponent<T extends Class>(componentClass: T): InstanceType<T> | undefined {
110
+ return this._dynamicComponents.get(componentClass);
111
+ }
61
112
 
62
- if (entity.gameEngine) {
63
- if (this.gameEngine !== entity.gameEngine) {
64
- throw new Error('cant add an active to a passive entity');
65
- }
66
- } else {
67
- if (this.gameEngine) {
113
+ getDynamicComponentOrThrow<T extends Class>(componentClass: T): InstanceType<T> {
114
+ const component = this._dynamicComponents.get(componentClass);
115
+ if (!component) {
116
+ throw new Error(`DynamicComponent '${componentClass.name}' not found in entity of type '${this.constructor.name}'.`);
117
+ }
118
+ return component;
119
+ }
68
120
 
69
- await this.gameEngine.add(entity);
70
- }
71
- }
121
+ get detached(): boolean { return this._detached; }
72
122
 
73
- // TODO: systems should be informed so they can do stuff (renderer system should add object 3d etc...)
123
+ async onBeforeRemove?(): Promise<void>;
74
124
 
75
- if (this.gameEngine && this.gameEngine !== entity.gameEngine) {
125
+ getSignal<T>(id: ID): Signal<T> {
126
+ return putIfAbsent(this._signalMap, id, () => new Signal<any>());
127
+ }
76
128
 
77
- }
129
+ private setParent(parent: Entity | undefined) {
130
+ if (parent === this._parent) {
131
+ //TODO: i think this check can be removed
132
+ throw Error('same parent');
133
+ }
134
+ this._parent = parent;
135
+ this.parentChanged.dispatch();
136
+ }
137
+
138
+ get parent(): Entity | undefined {
139
+ return this._parent;
140
+ }
141
+
142
+ getComponent<T extends Class>(componentClass: T): InstanceType<T> | undefined {
143
+ const componentMap = EcsInjector.entityComponents.get(this.constructor as Class);
144
+ if (!componentMap) {
145
+ throw new Error(`No components in entity of type '${this.constructor.name}'.`);
78
146
  }
147
+ const key = componentMap.get(componentClass as T);
148
+ return key && (<any>this)[key];
149
+ }
150
+
151
+ getComponentOrThrow<T extends Class>(componentClass: T): InstanceType<T> {
152
+ const componentMap = EcsInjector.entityComponents.get(this.constructor as Class);
153
+ if (!componentMap) {
154
+ throw new Error(`No components in entity of type '${this.constructor.name}'.`);
155
+ }
156
+ const key = componentMap.get(componentClass as T);
157
+ if (!key) {
158
+ throw new Error(`Component '${componentClass.name}' not found in entity of type '${this.constructor.name}'.`);
159
+ }
160
+ return (<any>this)[key];
161
+ }
79
162
 
80
- async remove(entity: Entity) {
81
- if (!this.children.delete(entity)) {
82
- throw new Error('Could not remove. Entity is not a child.');
83
- }
84
- entity.setParent(undefined);
85
- if (this.gameEngine) {
86
- return await this.gameEngine.remove(entity);
87
- }
163
+ async add(entity: Entity) {
164
+ if (entity.parent === this) {
165
+ throw new Error('Entity is already a child');
166
+ }
167
+ if (entity === this) {
168
+ throw new Error('Could not add Entity as a child of itself.');
88
169
  }
89
170
 
90
- async detach() {
91
- if (this.parent) {
92
- await this.parent.remove(this);
93
- } else {
94
- if (!this.gameEngine) {
95
- throw new Error('entity isn\'t attached to a parent or the game engine');
96
- }
97
- await this.gameEngine.remove(this);
98
- }
171
+ if (entity.parent) {
172
+ entity.parent.children.delete(entity);
173
+ }
174
+ this.children.add(entity);
175
+ entity.setParent(this);
176
+
177
+ if (entity.gameEngine) {
178
+ if (this.gameEngine !== entity.gameEngine) {
179
+ throw new Error('cant add an active to a passive entity');
180
+ }
181
+ } else {
182
+ if (this.gameEngine) {
183
+
184
+ await this.gameEngine.add(entity);
185
+ }
99
186
  }
100
187
 
101
- has(entity: Entity) {
102
- return this.children.has(entity);
188
+ // TODO: systems should be informed so they can do stuff (renderer system should add object 3d etc...)
189
+
190
+ if (this.gameEngine && this.gameEngine !== entity.gameEngine) {
191
+
192
+ }
193
+ }
194
+
195
+ async remove(entity: Entity) {
196
+ if (!this.children.delete(entity)) {
197
+ throw new Error('Could not remove. Entity is not a child.');
103
198
  }
199
+ entity.setParent(undefined);
200
+ if (this.gameEngine) {
201
+ return await this.gameEngine.remove(entity);
202
+ }
203
+ entity._signalMap.forEach(signal => signal.detachAll());
204
+ }
104
205
 
105
- /**
106
- * this includes the entity itself
107
- * @param target
108
- */
109
- getAllEntities(target: Entity[] = []) {
110
- target.push(this);
111
- for (const child of this.children) {
112
- child.getAllEntities(target);
113
- }
114
- return target;
206
+ async detach() {
207
+ if (this._detached) {
208
+ throw new Error('entity already detached');
209
+ }
210
+ this._detached = true;
211
+ // TODO: mark for detach and prevent another call, because this.gameEngine is set to undefined until next frame
212
+ if (this.parent) {
213
+ await this.parent.remove(this);
214
+ } else {
215
+ if (!this.gameEngine) {
216
+ throw new Error('entity isn\'t attached to a parent or the game engine');
217
+ }
218
+ await this.gameEngine.remove(this);
115
219
  }
220
+ }
221
+
222
+ has(entity: Entity) {
223
+ return this.children.has(entity);
224
+ }
225
+
226
+ /**
227
+ * this includes the entity itself
228
+ * @param target
229
+ */
230
+ getAllEntities(target: Entity[] = []) {
231
+ target.push(this);
232
+ for (const child of this.children) {
233
+ child.getAllEntities(target);
234
+ }
235
+ return target;
236
+ }
237
+
238
+ hasDynamicComponents() {
239
+ return this._dynamicComponents.size > 0;
240
+ }
116
241
  }