mani-game-engine 1.0.0-pre.9 → 1.0.0-pre.90

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/gameEngine.ts CHANGED
@@ -1,413 +1,608 @@
1
1
  import {Action, Class, EngineSignals, GameEnginePlugin, OnFixedUpdateParams, OnUpdateParams, Service, System} from './types';
2
2
  import {Signal, SignalBinding} from 'mani-signal';
3
3
  import {Entity} from './entity';
4
- import {ID, putIfAbsent} from 'mani-injector';
5
4
  import {EcsInjector, signalHandlers, staticSignalHandlers} from './ecsInjector';
6
5
  import {Clock, GameClock} from './clock';
7
6
  import {SystemContext} from './systemContext';
7
+ import {ID, putIfAbsent} from './injector';
8
8
 
9
9
  type AddEntry = [Entity, () => void];
10
10
  type RemoveEntry = [Entity, () => void];
11
11
 
12
12
  const defaultOptions = {
13
- fixedDeltaTime: 1 / 60,
14
- plugins: [] as GameEnginePlugin[],
13
+ fixedDeltaTime: 1 / 60,
14
+ plugins: [] as GameEnginePlugin[],
15
15
  };
16
16
 
17
17
  export type GameEngineOptions = Partial<typeof defaultOptions>;
18
18
  declare global {
19
- interface GameEngineActions {
20
- 'testAction': string
21
- }
19
+ interface GameEngineActions {
20
+ 'testAction': string;
21
+ }
22
22
  }
23
23
 
24
24
  type GameEngineActionParams<K extends keyof GameEngineActions> = GameEngineActions[K];
25
25
  type GameAction<K extends keyof GameEngineActions> = (engine: GameEngine, params: GameEngineActionParams<K>) => Promise<any> | any;
26
26
 
27
+ let id = 0;
27
28
  export class GameEngine {
28
-
29
- readonly onPrepare: Signal;
30
- readonly onStart: Signal;
31
- readonly onRender: Signal<OnUpdateParams>;
32
- readonly onUpdate: Signal<OnUpdateParams>;
33
- readonly onFixedUpdate: Signal<OnFixedUpdateParams>;
34
- readonly onPostPhysics: Signal<OnFixedUpdateParams>;
35
- readonly onLateFixedUpdate: Signal<OnFixedUpdateParams>;
36
- readonly onLateUpdate: Signal<OnUpdateParams>;
37
-
38
- private readonly onEarlyUpdateSet = new Set<System>();
39
- private readonly onUpdateSet = new Set<System>();
40
- private readonly onFixedUpdateSet = new Set<System>();
41
- private readonly onPreFixedUpdateSet = new Set<System>();
42
- private readonly onPhysicsUpdateSet = new Set<System>();
43
- private readonly onPostPhysicsUpdateSet = new Set<System>();
44
- private readonly onLateFixedUpdateSet = new Set<System>();
45
- private readonly onLateUpdateSet = new Set<System>();
46
- private readonly onRenderUpdateSet = new Set<System>();
47
-
48
- private readonly entitySystemMap = new Map<Entity, SystemContext[]>();
49
-
50
- private readonly serviceClasses = new Set<Class<Service>>();
51
- private readonly services: Service[] = [];
52
-
53
- private framePromise!: Promise<any>;
54
- private resolveFrame: () => void = () => undefined;
55
-
56
- private addQueue: AddEntry[] = [];
57
- private removeQueue: RemoveEntry[] = [];
58
-
59
- private _started = false;
60
-
61
- get started(): boolean { return this._started; }
62
-
63
- private _frameCount = 0;
64
- get frameCount(): number { return this._frameCount; }
65
-
66
- private _fixedFrameCount = 0;
67
- get fixedFrameCount(): number { return this._fixedFrameCount; }
68
-
69
- get numEntities(): number { return this.entitySystemMap.size;}
29
+ readonly id = id++;
30
+ readonly onPrepare: Signal;
31
+ readonly onStart: Signal;
32
+ readonly onEnd: Signal;
33
+ readonly onRender: Signal<OnUpdateParams>;
34
+ readonly onUpdate: Signal<OnUpdateParams>;
35
+ readonly onFixedUpdate: Signal<OnFixedUpdateParams>;
36
+ readonly onPrePhysicsUpdate: Signal<OnFixedUpdateParams>;
37
+ readonly onPhysicsUpdate: Signal<OnFixedUpdateParams>;
38
+ readonly onPostPhysicsUpdate: Signal<OnFixedUpdateParams>;
39
+ readonly onLateFixedUpdate: Signal<OnFixedUpdateParams>;
40
+ readonly onLateUpdate: Signal<OnUpdateParams>;
41
+ readonly onAddEntity: Signal<Entity>;
42
+ readonly onRemoveEntity: Signal<Entity>;
43
+
44
+ private readonly onEarlyUpdateSet = new Set<System>();
45
+ private readonly onUpdateSet = new Set<System>();
46
+ private readonly onFixedUpdateSet = new Set<System>();
47
+ private readonly onPreFixedUpdateSet = new Set<System>();
48
+ private readonly onPhysicsUpdateSet = new Set<System>();
49
+ private readonly onPrePhysicsUpdateSet = new Set<System>();
50
+ private readonly onPostPhysicsUpdateSet = new Set<System>();
51
+ private readonly onLateFixedUpdateSet = new Set<System>();
52
+ private readonly onLateUpdateSet = new Set<System>();
53
+ private readonly onRenderUpdateSet = new Set<System>();
54
+ private readonly onAddEntitySet = new Set<System>();
55
+ private readonly onRemoveEntitySet = new Set<System>();
56
+
57
+ // TODO: for performance, we could store the systems directly in the entity
58
+ private readonly entitySystemMap = new Map<Entity, Set<SystemContext>>();
59
+
60
+ private readonly registeredServices = new Set<Class<Service>>();
61
+ private readonly services: Service[] = [];
62
+ private readonly systemChildInjectors = new Map<object, EcsInjector>();
63
+
64
+ private framePromise!: Promise<any>;
65
+ private resolveFrame: () => void = () => undefined;
66
+
67
+ private addQueue: AddEntry[] = [];
68
+ private removeQueue: RemoveEntry[] = [];
69
+
70
+ private _started = false;
71
+
72
+ get started(): boolean { return this._started; }
73
+
74
+ private _frameCount = 0;
75
+ get frameCount(): number { return this._frameCount; }
76
+
77
+ private _fixedFrameCount = 0;
78
+ get fixedFrameCount(): number { return this._fixedFrameCount; }
79
+
80
+ get numEntities(): number { return this.entitySystemMap.size;}
70
81
 
71
82
  // TODO inject clock into game engine
72
83
  // TODO inject space into game engine
73
84
 
74
- constructor(
75
- readonly injector: EcsInjector<Class<System>>,
76
- readonly clock: Clock,
77
- ) {
78
- this.injector.map(GameEngine).toValue(this);
79
-
80
- this.onPrepare = this.injector.getSignal(EngineSignals.OnPrepare);
81
- this.onStart = this.injector.getSignal(EngineSignals.OnStart);
82
- this.onRender = this.injector.getSignal(EngineSignals.OnRender);
83
- this.onFixedUpdate = this.injector.getSignal(EngineSignals.OnFixedUpdate);
84
- this.onUpdate = this.injector.getSignal(EngineSignals.OnUpdate);
85
- this.onLateUpdate = this.injector.getSignal(EngineSignals.OnLateUpdate);
86
- this.onPostPhysics = this.injector.getSignal(EngineSignals.OnPostPhysics);
87
- this.onLateFixedUpdate = this.injector.getSignal(EngineSignals.onLateFixedUpdate);
88
-
89
- this.setupClock();
90
- this.prepareFrame();
85
+ constructor(
86
+ readonly injector: EcsInjector<Class<System>>,
87
+ readonly clock: Clock,
88
+ ) {
89
+ this.injector.map(GameEngine).toValue(this);
90
+
91
+ this.onPrepare = this.injector.getSignal(EngineSignals.OnPrepare);
92
+ this.onStart = this.injector.getSignal(EngineSignals.OnStart);
93
+ this.onEnd = this.injector.getSignal(EngineSignals.OnEnd);
94
+ this.onRender = this.injector.getSignal(EngineSignals.OnRender);
95
+ this.onFixedUpdate = this.injector.getSignal(EngineSignals.OnFixedUpdate);
96
+ this.onUpdate = this.injector.getSignal(EngineSignals.OnUpdate);
97
+ this.onLateUpdate = this.injector.getSignal(EngineSignals.OnLateUpdate);
98
+ this.onPrePhysicsUpdate = this.injector.getSignal(EngineSignals.OnPrePhysicsUpdate);
99
+ this.onPhysicsUpdate = this.injector.getSignal(EngineSignals.OnPhysicsUpdate);
100
+ this.onPostPhysicsUpdate = this.injector.getSignal(EngineSignals.OnPostPhysicsUpdate);
101
+ this.onLateFixedUpdate = this.injector.getSignal(EngineSignals.OnLateFixedUpdate);
102
+
103
+ this.onAddEntity = this.injector.getSignal(EngineSignals.OnAddEntity);
104
+ this.onRemoveEntity = this.injector.getSignal(EngineSignals.OnRemoveEntity);
105
+
106
+ this.setupClock();
107
+ this.prepareFrame();
108
+ }
109
+
110
+ static createDefault(options?: GameEngineOptions) {
111
+ const opts = {...defaultOptions, ...options};
112
+ const clock = new GameClock({
113
+ fixedDeltaTime: opts.fixedDeltaTime,
114
+ autoStart: false,
115
+ });
116
+ const injector = new EcsInjector<Class<System>>();
117
+ const engine = new GameEngine(injector, clock);
118
+ engine.installPlugins(opts.plugins);
119
+ return engine;
120
+ }
121
+
122
+ static createDefaultWithInjector(injector: EcsInjector<Class<System>>, options?: GameEngineOptions) {
123
+ const opts = {...defaultOptions, ...options};
124
+ const clock = new GameClock({
125
+ fixedDeltaTime: opts.fixedDeltaTime,
126
+ autoStart: false,
127
+ });
128
+ const engine = new GameEngine(injector, clock);
129
+ engine.installPlugins(opts.plugins);
130
+ return engine;
131
+ }
132
+
133
+ // TODO: test
134
+ addServiceClass<T extends Class<Service>>(serviceClass: T, mapping?: (injector: EcsInjector) => void): InstanceType<T> {
135
+ let childInjector: EcsInjector | undefined;
136
+ if (mapping) {
137
+ childInjector = this.injector.createChild();
138
+ mapping(childInjector);
91
139
  }
92
-
93
- static createDefault(options?: GameEngineOptions) {
94
- const opts = {...defaultOptions, ...options};
95
- const clock = new GameClock({
96
- fixedDeltaTime: opts.fixedDeltaTime,
97
- autoStart: false,
98
- });
99
- const injector = new EcsInjector<Class<System>>();
100
- const engine = new GameEngine(injector, clock);
101
- engine.installPlugins(opts.plugins);
102
- return engine;
140
+ this.mapStaticAnnotatedSignals(serviceClass);
141
+ const service = childInjector?.createInstance(serviceClass) || this.injector.createInstance(serviceClass);
142
+ this.addService(service);
143
+ if (childInjector) {
144
+ this.systemChildInjectors.set(service, childInjector);
103
145
  }
104
-
105
- static createDefaultWithInjector(injector: EcsInjector<Class<System>>, options?: GameEngineOptions) {
106
- const opts = {...defaultOptions, ...options};
107
- const clock = new GameClock({
108
- fixedDeltaTime: opts.fixedDeltaTime,
109
- autoStart: false,
110
- });
111
- const engine = new GameEngine(injector, clock);
112
- engine.installPlugins(opts.plugins);
113
- return engine;
146
+ return service;
147
+ }
148
+
149
+ private addService(service: Service): void {
150
+ this.mapAnnotatedSignals(service);
151
+ service.onStart && service.onStart();
152
+ service.onEarlyUpdate && this.onEarlyUpdateSet.add(service);
153
+ service.onPreFixedUpdate && this.onPreFixedUpdateSet.add(service);
154
+ service.onFixedUpdate && this.onFixedUpdateSet.add(service);
155
+ service.onUpdate && this.onUpdateSet.add(service);
156
+ service.onLateUpdate && this.onLateUpdateSet.add(service);
157
+ service.onPrePhysicsUpdate && this.onPrePhysicsUpdateSet.add(service);
158
+ service.onPhysicsUpdate && this.onPhysicsUpdateSet.add(service);
159
+ service.onPostPhysicsUpdate && this.onPostPhysicsUpdateSet.add(service);
160
+ service.onLateFixedUpdate && this.onLateFixedUpdateSet.add(service);
161
+ service.onRender && this.onRenderUpdateSet.add(service);
162
+ service.onAddEntity && this.onAddEntitySet.add(service);
163
+ service.onRemoveEntity && this.onRemoveEntitySet.add(service);
164
+ this.services.push(service);
165
+ }
166
+
167
+ removeService(service: Service): void {
168
+ const index = this.services.indexOf(service);
169
+ if (index === -1) return;
170
+ this.services.splice(index, 1);
171
+ this.unmapAnnotatedSignals(service);
172
+ service.onEarlyUpdate && this.onEarlyUpdateSet.delete(service);
173
+ service.onPreFixedUpdate && this.onPreFixedUpdateSet.delete(service);
174
+ service.onFixedUpdate && this.onFixedUpdateSet.delete(service);
175
+ service.onUpdate && this.onUpdateSet.delete(service);
176
+ service.onLateUpdate && this.onLateUpdateSet.delete(service);
177
+ service.onPrePhysicsUpdate && this.onPrePhysicsUpdateSet.delete(service);
178
+ service.onPhysicsUpdate && this.onPhysicsUpdateSet.delete(service);
179
+ service.onPostPhysicsUpdate && this.onPostPhysicsUpdateSet.delete(service);
180
+ service.onLateFixedUpdate && this.onLateFixedUpdateSet.delete(service);
181
+ service.onRender && this.onRenderUpdateSet.delete(service);
182
+ service.onAddEntity && this.onAddEntitySet.delete(service);
183
+ service.onRemoveEntity && this.onRemoveEntitySet.delete(service);
184
+ service.onEnd && service.onEnd();
185
+ const childInjector = this.systemChildInjectors.get(service);
186
+ if (childInjector) {
187
+ childInjector.dispose();
188
+ this.systemChildInjectors.delete(service);
114
189
  }
115
-
116
- addService(service: Service): void {
117
- this.mapAnnotatedSignals(service);
118
- service.onStart && service.onStart();
119
- service.onPreFixedUpdate && this.onPreFixedUpdateSet.add(service);
120
- service.onFixedUpdate && this.onFixedUpdateSet.add(service);
121
- service.onUpdate && this.onUpdateSet.add(service);
122
- service.onLateUpdate && this.onLateUpdateSet.add(service);
123
- service.onPhysicsUpdate && this.onPhysicsUpdateSet.add(service);
124
- service.onPostPhysicsUpdate && this.onPostPhysicsUpdateSet.add(service);
125
- service.onLateFixedUpdate && this.onLateFixedUpdateSet.add(service);
126
- service.onRender && this.onRenderUpdateSet.add(service);
127
- this.services.push(service);
128
- }
129
-
130
- private installPlugins(plugins: GameEnginePlugin[]) {
131
- plugins.forEach(plugin => {
132
- plugin.onPrepare && plugin.onPrepare(this);
133
- });
134
- plugins.forEach(plugin => {
135
- plugin.onStart && plugin.onStart(this);
136
- });
190
+ }
191
+
192
+ installPlugins(plugins: GameEnginePlugin[]) {
193
+ plugins.forEach(plugin => {
194
+ plugin.onPrepare && plugin.onPrepare(this);
195
+ });
196
+ plugins.forEach(plugin => {
197
+ plugin.onStart && plugin.onStart(this);
198
+ });
199
+ }
200
+
201
+ registerSystem(systemClass: Class<System>): void {
202
+ this.mapStaticAnnotatedSignals(systemClass);
203
+ if (this._started) throw new Error('Register Systems before engine is started');
204
+ this.injector.registerSystem(systemClass);
205
+ }
206
+
207
+ registerService(serviceClass: Class<Service>): void {
208
+ this.mapStaticAnnotatedSignals(serviceClass);
209
+ if (this._started) throw new Error('Register Services before engine is started');
210
+ this.injector.map(serviceClass).toSingleton();
211
+ this.registeredServices.add(serviceClass);
212
+ }
213
+
214
+ getService<T extends Class<Service>>(serviceClass: T): InstanceType<T> {
215
+ return this.injector.get(serviceClass);
216
+ }
217
+
218
+ start() {
219
+ this._started = true;
220
+ //TODO: throw when registering services or systems when engine is running
221
+ for (const serviceClass of this.registeredServices) {
222
+ const service = this.injector.get(serviceClass);
223
+ this.addService(service);
137
224
  }
138
-
139
- registerSystem(systemClass: Class<System>): void {
140
- this.mapStaticAnnotatedSignals(systemClass);
141
- if (this._started) throw new Error('Register Systems before engine is started');
142
- this.injector.registerSystem(systemClass);
225
+ this.clock.start();
226
+ this.onStart.dispatch();
227
+ }
228
+
229
+ private setupClock() {
230
+ this.clock.onPrepare.add(this.prepareFrame, {context: this});
231
+
232
+ this.clock.onEarlyUpdate.add(({time, deltaTime}) => {
233
+ for (const system of this.onEarlyUpdateSet) {
234
+ system.onEarlyUpdate!(time, deltaTime);
235
+ }
236
+ });
237
+
238
+ this.clock.onFixedUpdate.add((params) => {
239
+ const {time, deltaTime} = params;
240
+ for (const system of this.onPreFixedUpdateSet) {
241
+ system.onPreFixedUpdate!(time, deltaTime);
242
+ }
243
+ this.onFixedUpdate.dispatch(params);
244
+ for (const system of this.onFixedUpdateSet) {
245
+ system.onFixedUpdate!(time, deltaTime);
246
+ }
247
+ this.onPrePhysicsUpdate.dispatch(params);
248
+ for (const system of this.onPrePhysicsUpdateSet) {
249
+ system.onPrePhysicsUpdate!(time, deltaTime);
250
+ }
251
+ this.onPhysicsUpdate.dispatch(params);
252
+ for (const system of this.onPhysicsUpdateSet) {
253
+ system.onPhysicsUpdate!(time, deltaTime);
254
+ }
255
+ this.onPostPhysicsUpdate.dispatch(params);
256
+ for (const system of this.onPostPhysicsUpdateSet) {
257
+ system.onPostPhysicsUpdate!(time, deltaTime);
258
+ }
259
+ this.onLateFixedUpdate.dispatch(params);
260
+ for (const system of this.onLateFixedUpdateSet) {
261
+ system.onLateFixedUpdate!(time, deltaTime);
262
+ }
263
+ this._fixedFrameCount++;
264
+ });
265
+
266
+ // TODO: update from outside
267
+ this.clock.onUpdate.add(onUpdateParams => {
268
+ const {time, deltaTime, alpha} = onUpdateParams;
269
+ this.onUpdate.dispatch(onUpdateParams);
270
+ for (const system of this.onUpdateSet) {
271
+ system.onUpdate!(time, deltaTime, alpha);
272
+ }
273
+ //TODO: merge with framerate to single signal?
274
+ this.onLateUpdate.dispatch(onUpdateParams);
275
+ for (const system of this.onLateUpdateSet) {
276
+ system.onLateUpdate!(time, deltaTime, alpha);
277
+ }
278
+ this.onRender.dispatch(onUpdateParams);
279
+ for (const system of this.onRenderUpdateSet) {
280
+ system.onRender!(time, deltaTime, alpha);
281
+ }
282
+ this._frameCount++;
283
+ });
284
+ }
285
+
286
+ add(entity: Entity) {
287
+ return new Promise<void>(resolve => this.addQueue.push([entity, resolve]));
288
+ }
289
+
290
+ addAll(entity: Entity[]) {
291
+ return Promise.all(entity.map(entity => new Promise<void>(resolve => this.addQueue.push([entity, resolve]))));
292
+ }
293
+
294
+ waitFrame() {
295
+ return this.framePromise;
296
+ }
297
+
298
+ async remove(entity: Entity) {
299
+ if ((<any>entity).markRemoval) return;
300
+ (<any>entity).markRemoval = true;
301
+ return new Promise<void>(resolve => this.removeQueue.push([entity, resolve]));
302
+ }
303
+
304
+ async removeAll(entities: Entity[]) {
305
+ return Promise.all(entities.map(entity => this.remove(entity)));
306
+ }
307
+
308
+ stop() {
309
+ // this.injector.dispose();
310
+ this.clock.stop();
311
+ }
312
+
313
+ runAction<T extends Action>(action: T): ReturnType<T> {
314
+ return action(this);
315
+ }
316
+
317
+ getSignal<T>(signalId: ID): Signal<T> {
318
+ return this.injector.getSignal<T>(signalId);
319
+ }
320
+
321
+ private signalMappings = new Map<Class, [string, Signal][]>();
322
+ private staticSignalMappings = new Map<Class, [string, Signal][]>();
323
+ private signalMapBindings = new Map<Object, SignalBinding[]>();
324
+
325
+ // TODO: staticSignalMapBindings needed if we want to unregister Services or Systems
326
+ private staticSignalMapBindings = new Map<Class, SignalBinding[]>();
327
+
328
+ private mapStaticAnnotatedSignals(target: Class) {
329
+ let staticSignalMap = this.getStaticSignalMap(target);
330
+ if (staticSignalMap.length === 0) return;
331
+
332
+ const bindings = [];
333
+ for (const [key, signal] of staticSignalMap) {
334
+ bindings.push(signal.add((<any>target)[key], {context: target}));
143
335
  }
144
-
145
- registerService(serviceClass: Class<Service>): void {
146
- this.mapStaticAnnotatedSignals(serviceClass);
147
- if (this._started) throw new Error('Register Services before engine is started');
148
- this.injector.map(serviceClass).toSingleton();
149
- this.serviceClasses.add(serviceClass);
336
+ // Store bindings to allow unregistering Services or Systems
337
+ this.staticSignalMapBindings.set(target, bindings);
338
+ }
339
+
340
+ private unmapStaticAnnotatedSignals(target: Class) {
341
+ const bindings = this.staticSignalMapBindings.get(target);
342
+ if (!bindings) return;
343
+ for (const binding of bindings) {
344
+ binding.detach();
150
345
  }
346
+ this.staticSignalMapBindings.delete(target);
347
+ }
151
348
 
152
- getService<T extends Class<Service>>(serviceClass: T): InstanceType<T> {
153
- return this.injector.get(serviceClass);
154
- }
155
-
156
- start() {
157
- this._started = true;
158
- //TODO: throw when registering services or systems when engine is running
159
- for (const serviceClass of this.serviceClasses) {
160
- const service = this.injector.get(serviceClass);
161
- this.addService(service);
162
- }
163
- this.clock.start();
164
- this.onStart.dispatch();
165
- }
166
-
167
- private setupClock() {
168
- this.clock.onPrepare.add(this.prepareFrame, this);
169
-
170
- this.clock.onEarlyUpdate.add(({time, deltaTime}) => {
171
- for (const system of this.onEarlyUpdateSet) {
172
- system.onEarlyUpdate!(time, deltaTime);
173
- }
174
- });
175
-
176
- this.clock.onFixedUpdate.add((params) => {
177
- const {time, deltaTime} = params;
178
- for (const system of this.onPreFixedUpdateSet) {
179
- system.onPreFixedUpdate!();
180
- }
181
- for (const system of this.onFixedUpdateSet) {
182
- system.onFixedUpdate!(time, deltaTime);
183
- }
184
- this.onFixedUpdate.dispatch(params);
185
- for (const system of this.onPhysicsUpdateSet) {
186
- system.onPhysicsUpdate!(time, deltaTime);
187
- }
188
- this.onPostPhysics.dispatch(params);
189
- for (const system of this.onPostPhysicsUpdateSet) {
190
- system.onPostPhysicsUpdate!(time, deltaTime);
191
- }
192
- this.onLateFixedUpdate.dispatch(params);
193
- for (const system of this.onLateFixedUpdateSet) {
194
- system.onLateFixedUpdate!(time, deltaTime);
195
- }
196
- this._fixedFrameCount++;
197
- });
198
-
199
- // TODO: update from outside
200
- this.clock.onUpdate.add(onUpdateParams => {
201
- const {time, deltaTime, alpha} = onUpdateParams;
202
- for (const system of this.onUpdateSet) {
203
- system.onUpdate!(time, deltaTime, alpha);
204
- }
205
- //TODO: merge with framerate to single signal?
206
-
207
- this.onUpdate.dispatch(onUpdateParams);
208
- for (const system of this.onLateUpdateSet) {
209
- system.onLateUpdate!(time, deltaTime, alpha);
210
- }
211
- this.onLateUpdate.dispatch(onUpdateParams);
212
-
213
- for (const system of this.onRenderUpdateSet) {
214
- system.onRender!(time, deltaTime, alpha);
215
- }
216
- this.onRender.dispatch(onUpdateParams);
217
- this._frameCount++;
218
- });
219
- }
349
+ private mapAnnotatedSignals(target: Object) {
350
+ const signalMap = this.getSignalMap(target.constructor);
351
+ if (signalMap.length === 0) return;
220
352
 
221
- add(entity: Entity) {
222
- return new Promise<void>(resolve => this.addQueue.push([entity, resolve]));
353
+ const bindings = [];
354
+ for (const [key, signal] of signalMap) {
355
+ bindings.push(signal.add((<any>target)[key], {context: target}));
223
356
  }
224
-
225
- waitFrame() {
226
- return this.framePromise;
357
+ this.signalMapBindings.set(target, bindings);
358
+ }
359
+
360
+ private unmapAnnotatedSignals(target: Object) {
361
+ const signalBindings = this.signalMapBindings.get(target);
362
+ if (!signalBindings) return;
363
+ for (const binding of signalBindings) {
364
+ binding.detach();
227
365
  }
228
-
229
- async remove(entity: Entity) {
230
- if ((<any>entity).markRemoval) return;
231
- (<any>entity).markRemoval = true;
232
- return new Promise<void>(resolve => this.removeQueue.push([entity, resolve]));
366
+ }
367
+
368
+ private getSignalMap(target: Function) {
369
+ // TODO: we could speed thinks up by introducing "invisible" flags on the systems/services to avoid a map check
370
+ return putIfAbsent(this.signalMappings, target, (): [string, Signal][] => {
371
+ const handlers = signalHandlers.get(target);
372
+ if (!handlers) return [];
373
+ const result: [string, Signal][] = [];
374
+ for (const [key, signalId] of handlers) {
375
+ result.push([key, this.getSignal(signalId)]);
376
+ }
377
+ return result;
378
+ });
379
+ }
380
+
381
+ private getStaticSignalMap(target: Class) {
382
+ // TODO: we could speed thinks up by introducing "invisible" flags on the systems/services to avoid a map check
383
+ return putIfAbsent(this.staticSignalMappings, target, (): [string, Signal][] => {
384
+ const handlers = staticSignalHandlers.get(target);
385
+ if (!handlers) return [];
386
+ const result: [string, Signal][] = [];
387
+ for (const [key, signalId] of handlers) {
388
+ result.push([key, this.getSignal(signalId)]);
389
+ }
390
+ return result;
391
+ });
392
+ }
393
+
394
+ dispose() {
395
+ this.clock.stop();
396
+ this.clock.dispose();
397
+ for (const systems of this.entitySystemMap.values()) {
398
+ for (const context of systems) {
399
+ context.system.onEnd && context.system.onEnd();
400
+ this.unmapAnnotatedSignals(context.system);
401
+ }
233
402
  }
234
-
235
- stop() {
236
- // this.injector.dispose();
237
- this.clock.stop();
403
+ for (const service of this.services) {
404
+ service.onEnd && service.onEnd();
405
+ this.unmapAnnotatedSignals(service);
238
406
  }
407
+ this.onEnd.dispatch();
408
+
409
+ this.onAddEntity.detachAll();
410
+ this.onRemoveEntity.detachAll();
411
+ this.onPrepare.detachAll();
412
+ this.onStart.detachAll();
413
+ this.onEnd.detachAll();
414
+ this.onRender.detachAll();
415
+ this.onUpdate.detachAll();
416
+ this.onLateUpdate.detachAll();
417
+ this.onFixedUpdate.detachAll();
418
+ this.onPrePhysicsUpdate.detachAll();
419
+ this.onPhysicsUpdate.detachAll();
420
+ this.onPostPhysicsUpdate.detachAll();
421
+ this.onLateFixedUpdate.detachAll();
422
+ this.onEarlyUpdateSet.clear();
423
+ this.onPhysicsUpdateSet.clear();
424
+ this.onPrePhysicsUpdateSet.clear();
425
+ this.onPostPhysicsUpdateSet.clear();
426
+ this.onLateFixedUpdateSet.clear();
427
+ this.onLateUpdateSet.clear();
428
+ this.onUpdateSet.clear();
429
+ this.onFixedUpdateSet.clear();
430
+ this.onRenderUpdateSet.clear();
431
+ this.onAddEntitySet.clear();
432
+ this.onRemoveEntitySet.clear();
433
+ }
434
+
435
+ private prepareFrame() {
436
+ this.deferSignal = new Signal();
437
+ for (const [entity, resolve] of this.removeQueue) {
438
+ const entities = entity.getAllEntities();
439
+ for (const entity of entities) {
440
+ (<any>entity).markRemoval = false;
441
+ if (!(<any>entity).gameEngine) {
442
+ console.log('Entity not active', entity);
443
+ // throw new Error('Entity not active');
444
+ }
445
+ (<any>entity).gameEngine = undefined;
446
+
447
+ const systemContexts = this.entitySystemMap.get(entity);
448
+ this.entitySystemMap.delete(entity);
449
+ if (systemContexts) {
450
+ for (const context of systemContexts) {
451
+ this.disposeContext(context);
452
+ }
453
+ }
454
+ entity.onRemove.dispatch();
455
+ entity.onRemove.detachAll();
456
+ entity._signalMap.forEach(signal => signal.detachAll());
239
457
 
240
- runAction<T extends Action>(action: T): ReturnType<T> {
241
- return action(this);
242
- }
458
+ for (const system of this.onRemoveEntitySet) {
459
+ system.onRemoveEntity!(entity);
460
+ }
461
+ this.onRemoveEntity.dispatch(entity);
462
+ }
243
463
 
244
- getSignal<T>(signalId: ID): Signal<T> {
245
- return this.injector.getSignal<T>(signalId);
464
+ resolve();
246
465
  }
247
-
248
- private signalMappings = new Map<Class, [string, Signal][]>();
249
- private staticSignalMappings = new Map<Class, [string, Signal][]>();
250
- private signalMapBindings = new Map<Object, SignalBinding[]>();
251
-
252
- // TODO: staticSignalMapBindings needed if we want to unregister Services or Systems
253
-
254
- private mapStaticAnnotatedSignals(target: Class) {
255
- let staticSignalMap = this.getStaticSignalMap(target);
256
- if (staticSignalMap.length === 0) return;
257
-
258
- const bindings = [];
259
- for (const [key, signal] of staticSignalMap) {
260
- bindings.push(signal.add((<any>target)[key], target));
466
+ this.removeQueue = [];
467
+
468
+ for (const [entity, resolve] of this.addQueue) {
469
+ const preparePromises = [];
470
+ const nextSystemContexts: SystemContext[] = [];
471
+ const entities = entity.getAllEntities();
472
+ for (const entity of entities) {
473
+ if ((<any>entity).gameEngine) throw new Error('Entity already added to a gameEngine');
474
+ (<any>entity).gameEngine = this;
475
+ (<any>entity)._detached = false;
476
+ const systemContexts = this.injector.createSystemsForEntity(entity);
477
+ for (const context of systemContexts) {
478
+ // TODO: implement synced mode where async onPrepares aren't allowed
479
+ context.system.onPrepare && preparePromises.push(context.system.onPrepare());
480
+ nextSystemContexts.push(context);
261
481
  }
262
- // TODO: ignore bindings for now (store them if we implement unregister Service or Systems
263
- }
264
-
265
- private mapAnnotatedSignals(target: Object) {
266
- const signalMap = this.getSignalMap(target.constructor);
267
- if (signalMap.length === 0) return;
268
-
269
- const bindings = [];
270
- for (const [key, signal] of signalMap) {
271
- bindings.push(signal.add((<any>target)[key], target));
482
+ this.entitySystemMap.set(entity, systemContexts);
483
+ // we have to check if the entity is already in the map, because a system might have added dynamic components that also added to this
484
+ this.addSystemContextSetToMap(entity, systemContexts);
485
+
486
+
487
+ const entityWasAdded = () => {
488
+ this.onAddEntity.dispatch(entity);
489
+ for (const system of this.onAddEntitySet) {
490
+ system.onAddEntity!(entity);
491
+ }
492
+ entity.onAdd.dispatch();
493
+ resolve();
494
+ };
495
+
496
+ // Promise.all doesnt resolve immediately when there are no promises bu
497
+ if (preparePromises.length === 0) {
498
+ this.startSystems(nextSystemContexts, entityWasAdded);
499
+ } else {
500
+ Promise.all(preparePromises).then(() => this.startSystems(nextSystemContexts, entityWasAdded));
272
501
  }
273
- this.signalMapBindings.set(target, bindings);
502
+ }
274
503
  }
275
-
276
- private unmapAnnotatedSignals(target: Object) {
277
- const signalBindings = this.signalMapBindings.get(target);
278
- if (!signalBindings) return;
279
- for (const binding of signalBindings) {
280
- binding.detach();
281
- }
504
+ this.addQueue = [];
505
+ // create promise for next frame
506
+
507
+ // the next frame promise should work inside the first frame promise resolve function
508
+ const previousResolveFrame = this.resolveFrame;
509
+ this.framePromise = new Promise<void>(resolve => {
510
+ this.resolveFrame = resolve;
511
+ });
512
+ previousResolveFrame();
513
+ this.onPrepare.dispatch();
514
+
515
+ this.deferSignal.dispatch();
516
+ this.deferSignal = undefined;
517
+ }
518
+
519
+ /**
520
+ * if deferSignal is set, the callback will be called when the signal is dispatched
521
+ * is used for example to add a dynamic component to a system within the constructor of another system
522
+ */
523
+ deferSignal: Signal | undefined;
524
+ maybeDefer<T>(callback: () => T) {
525
+ if (this.deferSignal) {
526
+ this.deferSignal.addOnce(callback);
527
+ } else {
528
+ callback();
282
529
  }
530
+ }
283
531
 
284
- private getSignalMap(target: Function) {
285
- // TODO: we could speed thinks up by introducing "invisible" flags on the systems/services to avoid a map check
286
- return putIfAbsent(this.signalMappings, target, (): [string, Signal][] => {
287
- const handlers = signalHandlers.get(target);
288
- if (!handlers) return [];
289
- const result: [string, Signal][] = [];
290
- for (const [key, signalId] of handlers) {
291
- result.push([key, this.getSignal(signalId)]);
292
- }
293
- return result;
294
- });
295
- }
296
532
 
297
- private getStaticSignalMap(target: Class) {
298
- // TODO: we could speed thinks up by introducing "invisible" flags on the systems/services to avoid a map check
299
- return putIfAbsent(this.staticSignalMappings, target, (): [string, Signal][] => {
300
- const handlers = staticSignalHandlers.get(target);
301
- if (!handlers) return [];
302
- const result: [string, Signal][] = [];
303
- for (const [key, signalId] of handlers) {
304
- result.push([key, this.getSignal(signalId)]);
305
- }
306
- return result;
307
- });
533
+ private addSystemContextSetToMap (entity: Entity, contexts: Set<SystemContext>) {
534
+ const systemContexts = this.entitySystemMap.get(entity);
535
+ if (!systemContexts) {
536
+ this.entitySystemMap.set(entity, contexts);
537
+ } else {
538
+ for (const context of contexts) {
539
+ systemContexts.add(context);
540
+ }
308
541
  }
309
-
310
- dispose() {
311
- this.clock.stop();
312
- for (const systems of this.entitySystemMap.values()) {
313
- for (const system of systems) {
314
- system.system.onEnd && system.system.onEnd();
315
- }
316
- }
317
- for (const service of this.services) {
318
- service.onEnd && service.onEnd();
319
- }
542
+ }
543
+
544
+ private startSystems(contexts: Iterable<SystemContext>, then?: () => void) {
545
+ for (const context of contexts) {
546
+ const system = context.system;
547
+ this.mapAnnotatedSignals(system);
548
+ system.onStart && system.onStart();
549
+ system.onEarlyUpdate && this.onEarlyUpdateSet.add(system);
550
+ system.onPreFixedUpdate && this.onPreFixedUpdateSet.add(system);
551
+ system.onFixedUpdate && this.onFixedUpdateSet.add(system);
552
+ system.onUpdate && this.onUpdateSet.add(system);
553
+ system.onLateUpdate && this.onLateUpdateSet.add(system);
554
+ system.onPhysicsUpdate && this.onPhysicsUpdateSet.add(system);
555
+ system.onPrePhysicsUpdate && this.onPrePhysicsUpdateSet.add(system);
556
+ system.onPostPhysicsUpdate && this.onPostPhysicsUpdateSet.add(system);
557
+ system.onLateFixedUpdate && this.onLateFixedUpdateSet.add(system);
558
+ system.onRender && this.onRenderUpdateSet.add(system);
559
+ system.onAddEntity && this.onAddEntitySet.add(system);
560
+ system.onRemoveEntity && this.onRemoveEntitySet.add(system);
320
561
  }
321
-
322
- private prepareFrame() {
323
-
324
- for (const [entity, resolve] of this.removeQueue) {
325
- const entities = entity.getAllEntities();
326
- for (const entity of entities) {
327
- (<any>entity).markRemoval = false;
328
- if (!(<any>entity).gameEngine) {
329
- console.log(entity);
330
- // throw new Error('Entity not active');
331
- }
332
- (<any>entity).gameEngine = undefined;
333
-
334
- const systemContexts = this.entitySystemMap.get(entity);
335
- this.entitySystemMap.delete(entity);
336
- if (systemContexts) {
337
- for (const context of systemContexts) {
338
- context.dispose();
339
- const system = context.system;
340
- this.unmapAnnotatedSignals(system);
341
- system.onEnd && system.onEnd();
342
- system.onPreFixedUpdate && this.onPreFixedUpdateSet.delete(system);
343
- system.onFixedUpdate && this.onFixedUpdateSet.delete(system);
344
- system.onEarlyUpdate && this.onEarlyUpdateSet.delete(system);
345
- system.onUpdate && this.onUpdateSet.delete(system);
346
- system.onLateUpdate && this.onLateUpdateSet.delete(system);
347
- system.onPhysicsUpdate && this.onPhysicsUpdateSet.delete(system);
348
- system.onPostPhysicsUpdate && this.onPostPhysicsUpdateSet.delete(system);
349
- system.onLateFixedUpdate && this.onLateFixedUpdateSet.delete(system);
350
- system.onRender && this.onRenderUpdateSet.delete(system);
351
- }
352
- }
353
- entity.onRemove.dispatch();
354
- entity.onRemove.detachAll();
355
- }
356
-
357
- resolve();
358
- }
359
- this.removeQueue = [];
360
-
361
- for (const [entity, resolve] of this.addQueue) {
362
- const preparePromises = [];
363
- const nexSystemContexts: SystemContext[] = [];
364
- const entities = entity.getAllEntities();
365
- for (const entity of entities) {
366
- if ((<any>entity).gameEngine) throw new Error('Entity already added to a gameEngine');
367
- (<any>entity).gameEngine = this;
368
- const systemContexts = this.injector.createSystems(entity);
369
- for (const context of systemContexts) {
370
- // TODO: implement synced mode where async onPrepares aren't allowed
371
- context.system.onPrepare && preparePromises.push(context.system.onPrepare());
372
- nexSystemContexts.push(context);
373
- }
374
- this.entitySystemMap.set(entity, systemContexts);
375
- }
376
-
377
- const startSystems = () => {
378
- // TODO: check if a "global" method is faster than this inner method
379
- for (const context of nexSystemContexts) {
380
- const system = context.system;
381
- this.mapAnnotatedSignals(system);
382
- system.onStart && system.onStart();
383
- system.onPreFixedUpdate && this.onPreFixedUpdateSet.add(system);
384
- system.onFixedUpdate && this.onFixedUpdateSet.add(system);
385
- system.onEarlyUpdate && this.onEarlyUpdateSet.add(system);
386
- system.onUpdate && this.onUpdateSet.add(system);
387
- system.onLateUpdate && this.onLateUpdateSet.add(system);
388
- system.onPhysicsUpdate && this.onPhysicsUpdateSet.add(system);
389
- system.onPostPhysicsUpdate && this.onPostPhysicsUpdateSet.add(system);
390
- system.onLateFixedUpdate && this.onLateFixedUpdateSet.add(system);
391
- system.onRender && this.onRenderUpdateSet.add(system);
392
- }
393
- resolve();
394
- };
395
-
396
- // Promise.all doesnt resolve immediately when there are no promises bu
397
- if (preparePromises.length === 0) {
398
- startSystems();
399
- } else {
400
- Promise.all(preparePromises).then(startSystems);
401
- }
402
- }
403
- this.addQueue = [];
404
- // create promise for next frame
405
- this.resolveFrame();
406
- this.framePromise = new Promise<void>(resolve => {
407
- this.resolveFrame = resolve;
562
+ then?.();
563
+ };
564
+
565
+ getAllEntities(): Entity[] {
566
+ return Array.from(this.entitySystemMap.keys());
567
+ }
568
+
569
+ removeAllEntities() {
570
+ return this.removeAll(this.getAllEntities());
571
+ }
572
+
573
+ private disposeContext(context: SystemContext<System>) {
574
+ const system = context.system;
575
+
576
+ // if onEnd returns a promise, we need to wait for it to finish before we can dispose the system
577
+ const onEndPromise = system.onEnd && system.onEnd();
578
+ if (onEndPromise instanceof Promise) {
579
+ onEndPromise
580
+ .then(() => {
581
+ context.dispose();
582
+ })
583
+ .catch((error) => {
584
+ console.error('Error during system.onEnd():', error);
585
+ // Dispose the context even if onEnd() fails
586
+ context.dispose();
408
587
  });
409
- this.onPrepare.dispatch();
588
+ } else {
589
+ context.dispose();
410
590
  }
591
+
592
+ this.unmapAnnotatedSignals(system);
593
+ system.onEarlyUpdate && this.onEarlyUpdateSet.delete(system);
594
+ system.onPreFixedUpdate && this.onPreFixedUpdateSet.delete(system);
595
+ system.onFixedUpdate && this.onFixedUpdateSet.delete(system);
596
+ system.onUpdate && this.onUpdateSet.delete(system);
597
+ system.onLateUpdate && this.onLateUpdateSet.delete(system);
598
+ system.onPhysicsUpdate && this.onPhysicsUpdateSet.delete(system);
599
+ system.onPrePhysicsUpdate && this.onPrePhysicsUpdateSet.delete(system);
600
+ system.onPostPhysicsUpdate && this.onPostPhysicsUpdateSet.delete(system);
601
+ system.onLateFixedUpdate && this.onLateFixedUpdateSet.delete(system);
602
+ system.onRender && this.onRenderUpdateSet.delete(system);
603
+ system.onAddEntity && this.onAddEntitySet.delete(system);
604
+ system.onRemoveEntity && this.onRemoveEntitySet.delete(system);
605
+ }
411
606
  }
412
607
  //
413
608
  // type RunSpread<T> = T extends undefined
@@ -419,4 +614,3 @@ export class GameEngine {
419
614
  // export function createGameAction<K extends keyof GameEngineActions>(id: K, action: GameAction<K>): GameActionMapping {
420
615
  // return {id, action};
421
616
  // }
422
- //