-
Notifications
You must be signed in to change notification settings - Fork 2
/
World.ts
409 lines (323 loc) · 9.83 KB
/
World.ts
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
import Entity, { EntityId } from "./Entity";
import ComponentCollection from "./ComponentCollection";
import { Tag } from "./Tag";
import { SystemFunc } from "./Systems";
import DevTools from "./DevTools";
import Systems from './Systems';
import { TrackedCompSymbolKeys } from './TrackedComponent';
export type ClassConstructor<T> = { new (...args: any[]): T };
export default class World<CT> {
componentCollections: Map<EntityId, ComponentCollection<CT>> = new Map();
entities: Map<EntityId, Entity<CT>> = new Map();
entitiesByCTypes: Map<string[], Set<EntityId>> = new Map();
entitiesByTags: Map<Tag, Set<EntityId>> = new Map();
systems: Systems<CT>;
dev: DevTools<CT>;
constructor() {
this.dev = new DevTools(this);
this.systems = new Systems(this);
}
/**
* "finds" a single entity based on a predicate
*/
find = (predicate: (entity: Entity<CT>) => boolean): Entity<CT> | null => {
for (const entity of this.entities.values()) {
if (predicate(entity)) {
return entity;
}
}
return null;
};
/**
* "finds" all entities based on a predicate, kinda like filter.
*/
findAll = (predicate: (entity: Entity<CT>) => boolean): Entity<CT>[] => {
const results: Entity<CT>[] = [];
for (const entity of this.entities.values()) {
if (predicate(entity)) {
results.push(entity);
}
}
return results;
};
/**
* "locates" a single entity based on its Components.
*/
locate = (cl: ClassConstructor<CT> | ClassConstructor<CT>[]): Entity<CT> | null => {
for (const entity of this.entities.values()) {
if (entity.components.has(cl)) {
return entity;
}
}
return null;
};
/**
* Locates all entities that contain the components named
*/
locateAll = (cl: ClassConstructor<CT> | ClassConstructor<CT>[]): Entity<CT>[] => {
const results: Entity<CT>[] = [];
for (const entity of this.entities.values()) {
if (entity.components.has(cl)) {
results.push(entity);
}
}
return results;
};
/**
* Grabs the first entity, and its related component, that matches the component type.
* @example
* ```
* const { entity, component } = world.grab(MyComponent);
* ```
*/
grab = <T extends CT>(
cl: ClassConstructor<T>
): { entity: Entity<CT>; component: T } | null => {
const entity = this.locate(cl);
if (entity) {
const cc =
this.componentCollections.get(entity.id) ||
new ComponentCollection<CT>();
const component = cc.get<T>(cl);
return {
entity,
component,
};
}
return null;
};
/**
* Grab single component based on component type and predicate.
*
* @example
* ```typescript
* const { entity, component } = world.grabBy(FirstComponent, (comp) => comp.id == 'awesome')
* ```
*/
grabBy = <T extends CT>(
cl: ClassConstructor<T>,
predicate: (comp: T) => boolean
): { entity: Entity<CT>; component: T } | null => {
const entities = this.locateAll(cl);
// const entities = this.locateAll((cl as unknown) as CT);
for (const entity of entities) {
const cc =
this.componentCollections.get(entity.id) ||
new ComponentCollection<CT>();
const component = cc.get<T>(cl);
if (predicate(component)) {
return {
component,
entity,
};
}
}
return null;
};
/**
* Grab all the components primarily, and the entities if needed
*/
grabAll = <T extends CT>(
cl: ClassConstructor<T>
): { entity: Entity<CT>; component: T }[] => {
const entities = this.locateAll(cl);
return entities.map((entity) => {
return {
entity,
component: entity.components.get<T>(cl),
};
});
};
// TODO: Add grabAllBy method
/**
* Given an entity id and componentType, returns component
*/
get = <T extends CT>(eid: EntityId, cl: ClassConstructor<T>): T => {
const cc =
this.componentCollections.get(eid) || new ComponentCollection<CT>();
return cc.get<T>(cl);
};
/**
* Find and get the first instance of a component, without any associated entities.
* Helpful is you know that only one instance of a component exists across all entities.
* @param cl Component Class Contructor
* @param defaultValue A default component instance if no components are found.
*/
getComponent = <T extends CT>(
cl: ClassConstructor<T>,
defaultValue?: T
): T | null => {
const result = this.grab(cl);
if (!result) {
return defaultValue ? defaultValue : null;
}
return result.component;
};
/**
* Get an entity that has been tagged with the given tag, or return null;
*/
getTagged = (tag: Tag): Entity<CT> | null => {
const tagEntityIds = this.entitiesByTags.get(tag);
if (tagEntityIds) {
const entityId = tagEntityIds.values().next().value;
const entity = this.entities.get(entityId);
if (entity) {
return entity;
}
}
return null;
};
/**
* Gett all entities that have been tagged with the given tag.
* @param tag A string or number.
*/
getAllTagged = (tag: Tag): Entity<CT>[] => {
let entities: Entity<CT>[] = []; // eslint-disable-line
const tagEntityIds = this.entitiesByTags.get(tag);
if (tagEntityIds) {
for (const entityId of tagEntityIds) {
const entity = this.entities.get(entityId);
if (entity) {
entities.push(entity);
}
}
}
return entities;
};
/**
* Add a component on the given entity
*/
add = <T extends CT>(eid: EntityId, component: T): this => {
const cc =
this.componentCollections.get(eid) || new ComponentCollection<CT>();
const entity = this.entities.get(eid);
if (!entity) {
throw new Error(`world.add: Unable to locate entity with id ${eid}`);
}
cc.add(component);
this.componentCollections.set(eid, cc);
for (const [ctArr, entitySet] of this.entitiesByCTypes) {
if ((ctArr as string[]).every(cc.hasByName)) {
entitySet.add(eid);
}
}
// @ts-ignore
if (component[TrackedCompSymbolKeys.isTracked]) {
// @ts-ignore
component[TrackedCompSymbolKeys.setWorld](this);
// @ts-ignore
component[TrackedCompSymbolKeys.entityIDs].add(eid);
// @ts-ignore
component[TrackedCompSymbolKeys.onAdd](this, entity);
}
entity.onComponentAdd({ world: this, component });
return this;
};
/**
* Remove a component from the given entity.
* NOTE: This will change what systems will be called on the entity.
*/
remove = (eid: EntityId, cType: ClassConstructor<CT>): this => {
const cc =
this.componentCollections.get(eid) || new ComponentCollection<CT>();
// need to get component instance...
const component = cc.get(cType);
// @ts-ignore
if (component[TrackedCompSymbolKeys.isTracked]) {
const entity = this.entities.get(eid);
if (!entity) {
throw new Error(`world.remove: Unable to locate entity. eid: ${eid}, cType: ${cType.name}`);
}
// @ts-ignore
component[TrackedCompSymbolKeys.entityIDs].delete(eid);
// @ts-ignore
component[TrackedCompSymbolKeys.onRemove](this, entity);
}
// remove entity from current entitiesByCTypes
for (const [ctArr, entitySet] of this.entitiesByCTypes) {
if ((ctArr as string[]).every(cc.hasByName)) {
entitySet.delete(eid);
}
}
cc.remove(cType);
// Move entityId to new CTypes if needed.
for (const [ctArr, entitySet] of this.entitiesByCTypes) {
if ((ctArr as string[]).every(cc.hasByName)) {
entitySet.add(eid);
}
}
const entity = this.entities.get(eid);
if (entity) {
entity.onComponentRemove({ world: this, component });
}
return this;
};
/**
* Method for adding systems.
*/
addSystem(cTypes: ClassConstructor<CT>[], systemFunc: SystemFunc<CT>, funcName?: string): this {
this.systems.add(cTypes, systemFunc, funcName);
return this;
}
/**
* Setup an entity to exist in the given world. This is mostly an internal method, but exposed just in case.
*/
registerEntity(entity: Entity<CT>): World<CT> {
const cc = new ComponentCollection<CT>();
this.componentCollections.set(entity.id, cc);
this.entities.set(entity.id, entity);
entity.onCreate(this);
return this;
}
/**
* Remove all components that belong to an entity.
*/
clearEntityComponents(entityId: EntityId): this {
this.componentCollections.set(entityId, new ComponentCollection<CT>());
for (const entitySet of this.entitiesByCTypes.values()) {
if (entitySet.has(entityId)) {
entitySet.delete(entityId);
}
}
return this;
}
/**
* Create an entity that is in the world.
* Basically just new Entity(world), but saves an import of Entity.
*/
createEntity(): Entity<CT> {
const entity = new Entity(this);
return entity;
// Register entity here....
}
/**
* Destroys an entity.
* Same as entity.destroy().
*/
destroyEntity(entityId: EntityId): World<CT> {
this.componentCollections.delete(entityId);
const entity = this.entities.get(entityId);
if (!entity) {
throw new Error(`world.destroyEntity: No entity found. entity id: ${entityId}`);
}
this.entities.delete(entityId);
for (const entitySet of this.entitiesByCTypes.values()) {
if (entitySet.has(entityId)) {
entitySet.delete(entityId);
}
}
// remove any tag associations with destroyed entities.
for (const [tag, entitySet] of this.entitiesByTags) {
if (entitySet.has(entityId)) {
entitySet.delete(entityId);
}
if (entitySet.size === 0) {
this.entitiesByTags.delete(tag);
}
}
return this;
}
/*
TODO: world.destroy() and world.destroyImmediately() methods.
*/
}