@draug/engine 1.0.21 → 1.0.23

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.
@@ -0,0 +1,1256 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __decorateClass = (decorators, target, key, kind) => {
4
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
5
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
6
+ if (decorator = decorators[i])
7
+ result = (kind ? decorator(target, key, result) : decorator(result)) || result;
8
+ if (kind && result) __defProp(target, key, result);
9
+ return result;
10
+ };
11
+
12
+ // src/ecs/components/utils.ts
13
+ var registry = /* @__PURE__ */ new Map();
14
+ var id = 0;
15
+ var ComponentMetadataSymbol = /* @__PURE__ */ Symbol("component");
16
+ function Component(options) {
17
+ return (target) => {
18
+ const metadata = {
19
+ name: options.name,
20
+ id: ++id
21
+ };
22
+ registry.set(target, metadata.id);
23
+ target[ComponentMetadataSymbol] = metadata;
24
+ };
25
+ }
26
+ function getComponentId(ctor) {
27
+ const id2 = registry.get(ctor);
28
+ if (id2 === void 0) {
29
+ throw new Error(`Component not registered: ${ctor.name}`);
30
+ }
31
+ return id2;
32
+ }
33
+ var ErrNotComponent = class extends Error {
34
+ constructor(ctor) {
35
+ super(`Class ${ctor.name} is not a Component. Use @Component decorator to define components.`);
36
+ }
37
+ };
38
+ function getComponentMetadata(component) {
39
+ if (isComponent(component)) {
40
+ return component[ComponentMetadataSymbol];
41
+ }
42
+ throw new ErrNotComponent(component);
43
+ }
44
+ function isComponent(ctor) {
45
+ return ComponentMetadataSymbol in ctor;
46
+ }
47
+
48
+ // src/core/graph/dag.ts
49
+ var VisitedState = /* @__PURE__ */ ((VisitedState2) => {
50
+ VisitedState2[VisitedState2["Unvisited"] = 0] = "Unvisited";
51
+ VisitedState2[VisitedState2["Visiting"] = 1] = "Visiting";
52
+ VisitedState2[VisitedState2["Visited"] = 2] = "Visited";
53
+ return VisitedState2;
54
+ })(VisitedState || {});
55
+ var DAGNode = class {
56
+ data;
57
+ vertices = [];
58
+ constructor(data, vertices) {
59
+ this.data = data;
60
+ if (vertices)
61
+ this.vertices = vertices;
62
+ }
63
+ };
64
+ var ErrDAGCycleDetected = class extends Error {
65
+ constructor() {
66
+ super(`Cycle detected!`);
67
+ }
68
+ };
69
+ function topologicalSort(nodes) {
70
+ const visited = /* @__PURE__ */ new Map();
71
+ const result = [];
72
+ const dfs = (node) => {
73
+ const state = visited.get(node) ?? 0 /* Unvisited */;
74
+ if (state === 2 /* Visited */) return;
75
+ if (state === 1 /* Visiting */) {
76
+ throw new ErrDAGCycleDetected();
77
+ }
78
+ visited.set(node, 1 /* Visiting */);
79
+ for (const child of node.vertices) {
80
+ dfs(child);
81
+ }
82
+ visited.set(node, 2 /* Visited */);
83
+ result.push(node);
84
+ };
85
+ for (const node of nodes) {
86
+ dfs(node);
87
+ }
88
+ return result.reverse();
89
+ }
90
+
91
+ // src/ecs/system.ts
92
+ var SystemError = class extends Error {
93
+ constructor(target) {
94
+ super(`[System Error] (System "${target.name}".`);
95
+ }
96
+ };
97
+ var ErrNotASystem = class extends Error {
98
+ constructor(target) {
99
+ super(`Provided class "${target.name}" is not a System! Extend your class from SystemBase.`);
100
+ }
101
+ };
102
+ var ErrMissingSystemMetadata = class extends SystemError {
103
+ constructor(target) {
104
+ super(target);
105
+ this.message = `${this.message}: Missing system metadata! Define system class with @System decorator.`;
106
+ }
107
+ };
108
+ var SystemPhase = /* @__PURE__ */ ((SystemPhase2) => {
109
+ SystemPhase2[SystemPhase2["PRE"] = 0] = "PRE";
110
+ SystemPhase2[SystemPhase2["MAIN"] = 1] = "MAIN";
111
+ SystemPhase2[SystemPhase2["POST"] = 2] = "POST";
112
+ return SystemPhase2;
113
+ })(SystemPhase || {});
114
+ var SystemMetadataSymbol = /* @__PURE__ */ Symbol("system");
115
+ function System(props) {
116
+ return (target) => {
117
+ const systemTarget = target;
118
+ if ("__proto__" in systemTarget && systemTarget.__proto__ !== SystemBase) {
119
+ throw new ErrNotASystem(target);
120
+ }
121
+ const query = { ...props.query };
122
+ const requiredComponents = new Set(props.requiredComponents);
123
+ const computeAfter = new Set(props.computeAfter);
124
+ const phase = props.phase ?? 1 /* MAIN */;
125
+ const name = props.name ?? target.name;
126
+ const metadata = { query, requiredComponents, computeAfter, phase, name };
127
+ systemTarget[SystemMetadataSymbol] = metadata;
128
+ };
129
+ }
130
+ function getSystemMetadata(system) {
131
+ if (hasMetadata(system)) {
132
+ return system[SystemMetadataSymbol];
133
+ }
134
+ throw new ErrMissingSystemMetadata(system);
135
+ }
136
+ function hasMetadata(ctor) {
137
+ return SystemMetadataSymbol in ctor;
138
+ }
139
+ function isSystem(ctor) {
140
+ return hasMetadata(ctor);
141
+ }
142
+ var SystemBase = class {
143
+ };
144
+ var SystemsManager = class {
145
+ constructor(world, logger) {
146
+ this.world = world;
147
+ this.logger = logger;
148
+ }
149
+ world;
150
+ logger;
151
+ systems_ = /* @__PURE__ */ new Map();
152
+ executionOrder_ = [];
153
+ requiredComponents_ = /* @__PURE__ */ new Set();
154
+ dirty_ = true;
155
+ getRequiredComponents() {
156
+ return this.requiredComponents_;
157
+ }
158
+ register(sys) {
159
+ const ctor = sys.constructor;
160
+ if (this.systems_.has(ctor)) throw new Error("Duplicate system");
161
+ const { query, requiredComponents } = getSystemMetadata(ctor);
162
+ this.systems_.set(ctor, sys);
163
+ const q = query;
164
+ for (const c of q.include ?? [])
165
+ this.requiredComponents_.add(c);
166
+ for (const c of q.exclude ?? [])
167
+ this.requiredComponents_.add(c);
168
+ for (const c of q.anyOf ?? [])
169
+ this.requiredComponents_.add(c);
170
+ for (const c of requiredComponents)
171
+ this.requiredComponents_.add(c);
172
+ const meta = getSystemMetadata(ctor);
173
+ this.logger.debug(() => `[Systems]: system "${meta.name}" was registered`);
174
+ }
175
+ build() {
176
+ this.buildSystemsArray();
177
+ for (const sys of this.systems_.values()) {
178
+ sys.onInit?.({ world: this.world, logger: this.logger });
179
+ }
180
+ this.logger.debug(() => `Built ${this.systems_.size} systems`);
181
+ this.dirty_ = false;
182
+ }
183
+ rebuild() {
184
+ this.build();
185
+ }
186
+ get(ctor) {
187
+ const s = this.systems_.get(ctor);
188
+ if (!s)
189
+ throw new Error("System not registered");
190
+ return s;
191
+ }
192
+ update(time) {
193
+ if (this.dirty_)
194
+ this.rebuild();
195
+ this.world.events.swapAll();
196
+ for (const s of this.executionOrder_) {
197
+ const { query } = getSystemMetadata(s.constructor);
198
+ const entities = this.world.query(query);
199
+ s.compute({
200
+ world: this.world,
201
+ entities,
202
+ time,
203
+ logger: this.logger
204
+ });
205
+ }
206
+ }
207
+ buildSystemsArray() {
208
+ const pre = [];
209
+ const main = [];
210
+ const post = [];
211
+ const map = /* @__PURE__ */ new Map();
212
+ for (const [ctor, system] of this.systems_.entries()) {
213
+ const meta = getSystemMetadata(ctor);
214
+ switch (meta.phase) {
215
+ case 0 /* PRE */:
216
+ pre.push(system);
217
+ break;
218
+ case 1 /* MAIN */:
219
+ post.push(system);
220
+ break;
221
+ default:
222
+ main.push(system);
223
+ map.set(ctor, new DAGNode(system));
224
+ break;
225
+ }
226
+ }
227
+ for (const ctor of map.keys()) {
228
+ const currentNode = map.get(ctor);
229
+ const { computeAfter } = getSystemMetadata(ctor);
230
+ for (const depCtor of computeAfter ?? []) {
231
+ const depNode = map.get(depCtor);
232
+ if (!depNode) {
233
+ throw new Error(`Dependency ${depCtor.name} not registered`);
234
+ }
235
+ depNode.vertices.push(currentNode);
236
+ }
237
+ }
238
+ this.executionOrder_ = [
239
+ ...pre,
240
+ ...topologicalSort(map.values()).map((x) => x.data),
241
+ ...post
242
+ ];
243
+ }
244
+ };
245
+
246
+ // src/ecs/constant.ts
247
+ var ECS_DEFAULTS = {
248
+ MAX_ENTITY_COUNT: Math.pow(2, 12)
249
+ };
250
+
251
+ // src/ecs/events-buffer.ts
252
+ var EventBuffer = class {
253
+ readBuf = [];
254
+ writeBuf = [];
255
+ write(event) {
256
+ this.writeBuf.push(event);
257
+ }
258
+ /**
259
+ * Advances the buffer to the next frame.
260
+ *
261
+ * Performs a double-buffer flip:
262
+ * - Promotes all events written during the previous frame (`writeBuf`)
263
+ * to be readable in the current frame (`readBuf`).
264
+ * - Reuses the previous `readBuf` as the new `writeBuf` and clears it
265
+ * to collect events for the next frame.
266
+ *
267
+ * After calling this method:
268
+ * - `get()` will return a stable snapshot of events produced in the previous frame.
269
+ * - `add()` will write into an empty buffer for the current frame.
270
+ *
271
+ * Guarantees:
272
+ * - No events written during the current frame are visible until the next `swap()`.
273
+ * - Readers observe a consistent, immutable snapshot within a frame.
274
+ *
275
+ * Expected to be called exactly once per frame, before system execution.
276
+ */
277
+ swap() {
278
+ const tmp = this.readBuf;
279
+ this.readBuf = this.writeBuf;
280
+ this.writeBuf = tmp;
281
+ this.writeBuf.length = 0;
282
+ }
283
+ read() {
284
+ return this.readBuf;
285
+ }
286
+ size() {
287
+ return this.readBuf.length;
288
+ }
289
+ };
290
+ function createEventKey(description) {
291
+ return Symbol(description);
292
+ }
293
+ var EventBus = class {
294
+ storage = /* @__PURE__ */ new Map();
295
+ swapAll() {
296
+ this.storage.forEach((s) => s.swap());
297
+ }
298
+ getBuffer(key) {
299
+ let buf = this.storage.get(key);
300
+ if (!buf) {
301
+ buf = new EventBuffer();
302
+ this.storage.set(key, buf);
303
+ }
304
+ return buf;
305
+ }
306
+ };
307
+
308
+ // src/ecs/resources/resources.ts
309
+ var ResourceMetadataSymbol = /* @__PURE__ */ Symbol("resource");
310
+ function Resource(params) {
311
+ return (target) => {
312
+ const metadata = {
313
+ name: params.name
314
+ };
315
+ target[ResourceMetadataSymbol] = metadata;
316
+ };
317
+ }
318
+ var ErrNotResource = class extends Error {
319
+ constructor(ctor) {
320
+ super(`Class ${ctor.name} is not a Resource. Use @Resource decorator to define resources.`);
321
+ }
322
+ };
323
+ function getResourceMetadata(resource) {
324
+ if (isResource(resource)) {
325
+ return resource[ResourceMetadataSymbol];
326
+ }
327
+ throw new ErrNotResource(resource);
328
+ }
329
+ function isResource(ctor) {
330
+ return ResourceMetadataSymbol in ctor;
331
+ }
332
+ var ResourcesManager = class {
333
+ constructor(logger) {
334
+ this.logger = logger;
335
+ }
336
+ logger;
337
+ items_ = /* @__PURE__ */ new Map();
338
+ insert(type, value) {
339
+ this.items_.set(type, value);
340
+ const metadata = getResourceMetadata(type);
341
+ this.logger.debug(() => `[Resources]: Inserted new Resource "${metadata.name}"`);
342
+ return value;
343
+ }
344
+ get(type) {
345
+ const value = this.items_.get(type);
346
+ const meta = getResourceMetadata(type);
347
+ if (!value)
348
+ throw new Error(`Resource of class ${meta.name} does not exist!`);
349
+ return value;
350
+ }
351
+ getOrInsert(type, factory) {
352
+ let value = this.items_.get(type) ?? null;
353
+ if (value === null) {
354
+ value = factory();
355
+ this.insert(type, value);
356
+ }
357
+ return value;
358
+ }
359
+ remove(type) {
360
+ const meta = getResourceMetadata(type);
361
+ this.logger.debug(() => `[Resources]: Removed resource "${meta.name}"`);
362
+ this.items_.delete(type);
363
+ }
364
+ };
365
+
366
+ // src/ecs/command.ts
367
+ function entry(component, init = () => {
368
+ }) {
369
+ return [component, init];
370
+ }
371
+ var Commands = class {
372
+ constructor(world, logger) {
373
+ this.world = world;
374
+ this.logger = logger;
375
+ }
376
+ world;
377
+ logger;
378
+ commandsQueue_ = [];
379
+ add(cmd) {
380
+ this.commandsQueue_.push(cmd);
381
+ }
382
+ flush(world) {
383
+ for (const cmd of this.commandsQueue_)
384
+ cmd(world);
385
+ this.commandsQueue_.length = 0;
386
+ }
387
+ createEntity(...entries) {
388
+ const id2 = this.world.entities.create();
389
+ const cmd = (world) => {
390
+ for (const [cls, initFn] of entries) {
391
+ world.addComponent(id2, cls, initFn);
392
+ }
393
+ };
394
+ this.add(cmd);
395
+ this.logger.debug(() => {
396
+ const components = entries.map((x) => getComponentMetadata(x[0]).name).join(", ");
397
+ return `[Commands.createEntity]: Created new entity with ID ${id2}. Linked components: [${components}]`;
398
+ });
399
+ return id2;
400
+ }
401
+ };
402
+
403
+ // src/ecs/query.ts
404
+ import { Bitmap } from "bitmap-index";
405
+ var QueryManager = class {
406
+ constructor(world) {
407
+ this.world = world;
408
+ }
409
+ world;
410
+ cache = /* @__PURE__ */ new Map();
411
+ get(params) {
412
+ const key = this.getKey(params);
413
+ let entry2 = this.cache.get(key);
414
+ if (!entry2) {
415
+ entry2 = {
416
+ params,
417
+ bitmap: this.compute(params),
418
+ dirty: false,
419
+ deps: this.collectDeps(params)
420
+ };
421
+ this.cache.set(key, entry2);
422
+ }
423
+ if (entry2.dirty) {
424
+ entry2.bitmap = this.compute(entry2.params);
425
+ entry2.dirty = false;
426
+ }
427
+ let targetBitmap = entry2.bitmap;
428
+ if (params.excludeEntitiesIds?.length) {
429
+ targetBitmap = entry2.bitmap.clone();
430
+ const excludeBm = new Bitmap();
431
+ for (const id2 of params.excludeEntitiesIds) {
432
+ excludeBm.set(id2);
433
+ }
434
+ targetBitmap.andNot(excludeBm);
435
+ }
436
+ if (params.filter) {
437
+ const result = [];
438
+ targetBitmap.range((id2) => {
439
+ if (params.filter(id2)) result.push(id2);
440
+ });
441
+ return result;
442
+ }
443
+ return this.extractIds(targetBitmap);
444
+ }
445
+ invalidate(component) {
446
+ for (const entry2 of this.cache.values()) {
447
+ if (entry2.deps.has(component)) {
448
+ entry2.dirty = true;
449
+ }
450
+ }
451
+ }
452
+ getKey(q) {
453
+ return [
454
+ this.ids(q.include),
455
+ this.ids(q.exclude),
456
+ this.ids(q.anyOf)
457
+ ].join("|");
458
+ }
459
+ ids(arr) {
460
+ if (!arr || arr.length === 0) return "";
461
+ return arr.map((c) => this.world.components.getComponentId(c)).sort((a, b) => a - b).join(",");
462
+ }
463
+ collectDeps(q) {
464
+ const set = /* @__PURE__ */ new Set();
465
+ q.include?.forEach((c) => set.add(c));
466
+ q.exclude?.forEach((c) => set.add(c));
467
+ q.anyOf?.forEach((c) => set.add(c));
468
+ return set;
469
+ }
470
+ compute(params) {
471
+ let result = this.combineBitmaps(params.include, "and");
472
+ const any = this.combineBitmaps(params.anyOf, "or");
473
+ if (any) {
474
+ result = result ? result.and(any) : any;
475
+ }
476
+ if (!result) {
477
+ return new Bitmap();
478
+ }
479
+ this.applyExclusions(result, params.exclude);
480
+ return result;
481
+ }
482
+ combineBitmaps(components, op) {
483
+ if (!components?.length) return null;
484
+ let result = null;
485
+ let hasAtLeastOneValid = false;
486
+ for (const c of components) {
487
+ const bm = this.world.components.getStorage(c)?.bitmap();
488
+ if (!bm) {
489
+ if (op === "and") {
490
+ return new Bitmap();
491
+ }
492
+ continue;
493
+ }
494
+ hasAtLeastOneValid = true;
495
+ if (!result) {
496
+ result = bm.clone();
497
+ } else {
498
+ op === "and" ? result.and(bm) : result.or(bm);
499
+ }
500
+ }
501
+ if (op === "or" && !hasAtLeastOneValid) {
502
+ return new Bitmap();
503
+ }
504
+ return result;
505
+ }
506
+ applyExclusions(target, excludeComponents) {
507
+ if (excludeComponents?.length) {
508
+ for (const c of excludeComponents) {
509
+ const bm = this.world.components.getStorage(c)?.bitmap();
510
+ if (bm) target.andNot(bm);
511
+ }
512
+ }
513
+ }
514
+ extractIds(bitmap) {
515
+ const result = [];
516
+ bitmap.range((id2) => {
517
+ result.push(id2);
518
+ });
519
+ return result;
520
+ }
521
+ };
522
+
523
+ // src/ecs/plugin/plugin.ts
524
+ var PluginMetadataSymbol = /* @__PURE__ */ Symbol("plugin");
525
+ function Plugin(metadata) {
526
+ return (target) => {
527
+ if ("__proto__" in target && target.__proto__ !== PluginBase)
528
+ throw new ErrNotAPlugin(target);
529
+ target[PluginMetadataSymbol] = metadata;
530
+ };
531
+ }
532
+ function getPluginMetadata(plugin) {
533
+ if (hasMetadata2(plugin)) {
534
+ return plugin[PluginMetadataSymbol];
535
+ }
536
+ throw new ErrMissingPluginMetadata(plugin);
537
+ }
538
+ function hasMetadata2(ctor) {
539
+ return PluginMetadataSymbol in ctor;
540
+ }
541
+ function isPlugin(ctor) {
542
+ return hasMetadata2(ctor);
543
+ }
544
+ var PluginBase = class {
545
+ onPluginLoad;
546
+ onPluginUnload;
547
+ onAfterWorldInit;
548
+ };
549
+ var PluginError = class extends Error {
550
+ constructor(pluginId) {
551
+ super(`Plugin error! Plugin [${pluginId}]`);
552
+ }
553
+ };
554
+ var ErrNotAPlugin = class extends Error {
555
+ constructor(target) {
556
+ super(`Provided class ${target.name} is not a Plugin! Every plugin must extends of PluginBase class.`);
557
+ }
558
+ };
559
+ var ErrMissingPluginMetadata = class extends Error {
560
+ constructor(plugin) {
561
+ super(`Provided class ${plugin.name}: Missing plugin metadata! Define plugin class with @Plugin decorator.`);
562
+ }
563
+ };
564
+ var ErrUnknownPlugin = class extends PluginError {
565
+ constructor(pluginId) {
566
+ super(pluginId);
567
+ this.message = `${super.message}: Plugin not found in manager.`;
568
+ }
569
+ };
570
+ var ErrPluginNotInit = class extends PluginError {
571
+ constructor(pluginId) {
572
+ super(pluginId);
573
+ this.message = `${super.message}: Plugin not initiated yet. You must use PluginsManager.build() before getting instance.`;
574
+ }
575
+ };
576
+ var ErrMissingPluginDependency = class extends PluginError {
577
+ constructor(pluginId, missingDepId) {
578
+ super(pluginId);
579
+ this.message = `${super.message}: Missing required dependency [${missingDepId}]. Install it first.`;
580
+ }
581
+ };
582
+ var ErrDAGCycleDetectedPlugin = class extends Error {
583
+ constructor() {
584
+ super(`Cycle detected in plugin dependencies!`);
585
+ }
586
+ };
587
+ var PluginsManager = class {
588
+ constructor(logger) {
589
+ this.logger = logger;
590
+ }
591
+ logger;
592
+ plugins_ = /* @__PURE__ */ new Map();
593
+ isInitiated_ = false;
594
+ install(plugin, ...constructorProps) {
595
+ if (!isPlugin(plugin))
596
+ throw new ErrMissingPluginMetadata(plugin);
597
+ const metadata = getPluginMetadata(plugin);
598
+ if (this.plugins_.has(plugin))
599
+ return;
600
+ const entry2 = {
601
+ ctor: plugin,
602
+ ctorParams: constructorProps,
603
+ metadata
604
+ };
605
+ this.plugins_.set(plugin, entry2);
606
+ this.logger.debug(() => `[Plugins]: Installed plugin ${metadata.name} (${metadata.version})`);
607
+ }
608
+ build() {
609
+ if (this.plugins_.size === 0) {
610
+ return;
611
+ }
612
+ const nodes = /* @__PURE__ */ new Map();
613
+ for (const id2 of this.plugins_.keys()) {
614
+ nodes.set(id2, new DAGNode(id2));
615
+ }
616
+ for (const [plugin, entry2] of this.plugins_) {
617
+ const node = nodes.get(plugin);
618
+ const depPlugins = entry2.metadata.dependencies?.plugins ?? [];
619
+ for (const dep of depPlugins) {
620
+ const depNode = nodes.get(dep.plugin);
621
+ if (!depNode) {
622
+ throw new ErrMissingPluginDependency(plugin, dep.plugin);
623
+ }
624
+ depNode.vertices.push(node);
625
+ }
626
+ }
627
+ let sortedNodes;
628
+ try {
629
+ sortedNodes = topologicalSort(nodes.values());
630
+ } catch (e) {
631
+ if (e instanceof ErrDAGCycleDetected) {
632
+ throw new ErrDAGCycleDetectedPlugin();
633
+ }
634
+ throw e;
635
+ }
636
+ for (const node of sortedNodes) {
637
+ const entry2 = this.plugins_.get(node.data);
638
+ const { ctor, ctorParams } = entry2;
639
+ const instance = new ctor(...ctorParams);
640
+ entry2.instance = instance;
641
+ instance.onPluginLoad?.();
642
+ }
643
+ this.isInitiated_ = true;
644
+ this.logger.debug(() => `[Plugins]: Plugins built successfully!`);
645
+ }
646
+ /**
647
+ * @internal
648
+ */
649
+ __internal__onAfterWorldInit(world) {
650
+ for (const p of this.plugins_.values()) {
651
+ p.instance?.onAfterWorldInit?.(world);
652
+ }
653
+ }
654
+ getPluginMetadata(plugin) {
655
+ const entry2 = this.plugins_.get(plugin);
656
+ if (!entry2) throw new ErrUnknownPlugin(plugin);
657
+ return entry2.metadata;
658
+ }
659
+ getPluginInstance(plugin) {
660
+ const entry2 = this.plugins_.get(plugin);
661
+ if (!entry2) throw new ErrUnknownPlugin(plugin);
662
+ if (!entry2.instance) throw new ErrPluginNotInit(plugin);
663
+ if (!this.isInitiated_) {
664
+ throw new ErrPluginNotInit(plugin);
665
+ }
666
+ return entry2.instance;
667
+ }
668
+ };
669
+
670
+ // src/ecs/world.ts
671
+ var World2 = class {
672
+ entities;
673
+ components;
674
+ systems;
675
+ events;
676
+ resources;
677
+ commands;
678
+ queries;
679
+ plugins;
680
+ logger;
681
+ entityRefs_ = /* @__PURE__ */ new Map();
682
+ updatesCount_ = 0;
683
+ get updatesCount() {
684
+ return this.updatesCount_;
685
+ }
686
+ constructor(params) {
687
+ this.entities = new EntitiesManager(params.logger);
688
+ this.components = new ComponentsManager(params.logger, params.maxEntityCount ?? ECS_DEFAULTS.MAX_ENTITY_COUNT);
689
+ this.systems = new SystemsManager(this, params.logger);
690
+ this.events = new EventBus();
691
+ this.resources = new ResourcesManager(params.logger);
692
+ this.commands = new Commands(this, params.logger);
693
+ this.queries = new QueryManager(this);
694
+ this.plugins = new PluginsManager(params.logger);
695
+ this.logger = params.logger;
696
+ }
697
+ getEntityRef(id2) {
698
+ let ref = this.entityRefs_.get(id2);
699
+ if (!ref) {
700
+ ref = new EntityRef(this, id2);
701
+ this.entityRefs_.set(id2, ref);
702
+ }
703
+ return ref;
704
+ }
705
+ query(params) {
706
+ return this.queries.get(params);
707
+ }
708
+ removeComponent(entity, component) {
709
+ const id2 = typeof entity === "number" ? entity : entity.id;
710
+ const storage = this.components.getStorage(component);
711
+ storage.remove(id2);
712
+ this.queries.invalidate(component);
713
+ }
714
+ addComponent(entity, component, initFn) {
715
+ const storage = this.components.getStorage(component);
716
+ let id2;
717
+ if (typeof entity === "number") {
718
+ id2 = entity;
719
+ } else {
720
+ id2 = entity.id;
721
+ }
722
+ const c = storage.add(id2, (o) => {
723
+ if (initFn) {
724
+ initFn(o);
725
+ }
726
+ return o;
727
+ });
728
+ this.queries.invalidate(component);
729
+ return c;
730
+ }
731
+ update(clock) {
732
+ this.systems.update(clock.getTime());
733
+ this.commands.flush(this);
734
+ this.updatesCount_++;
735
+ }
736
+ build() {
737
+ this.plugins.build();
738
+ this.logger.debug(() => "World was built successfully");
739
+ }
740
+ };
741
+
742
+ // src/ecs/entity.ts
743
+ var UnregisteredComponentStorageError = class extends Error {
744
+ constructor(component) {
745
+ const meta = getComponentMetadata(component);
746
+ super(`Cannot get storage for component ${meta.name}. Seems like it's not registered in world.`);
747
+ }
748
+ };
749
+ var EntityMaskNotFoundError = class extends Error {
750
+ constructor(id2) {
751
+ super(`Cannot find bitmask for entity [${id2}]. Seems like it's not registered in the EntityManager.`);
752
+ }
753
+ };
754
+ var EntitiesManager = class {
755
+ constructor(logger) {
756
+ this.logger = logger;
757
+ }
758
+ logger;
759
+ id_ = 0;
760
+ nextId() {
761
+ return ++this.id_;
762
+ }
763
+ create() {
764
+ const id2 = this.nextId();
765
+ this.logger.debug(() => `[Entities]: Created new entity with ID ${id2}`);
766
+ return id2;
767
+ }
768
+ };
769
+ var EntityRef = class {
770
+ constructor(world, id2) {
771
+ this.world = world;
772
+ this.id = id2;
773
+ }
774
+ world;
775
+ id;
776
+ with(...components) {
777
+ return components.map((c) => {
778
+ const s = this.world.components.getStorage(c);
779
+ return s.tryGet(this.id);
780
+ });
781
+ }
782
+ };
783
+
784
+ // src/core/memory/pool.ts
785
+ var ObjectPool = class {
786
+ pool_;
787
+ factory_;
788
+ cursor_;
789
+ constructor(factory, initialSize = 0) {
790
+ this.pool_ = new Array(initialSize);
791
+ this.factory_ = factory;
792
+ this.cursor_ = initialSize - 1;
793
+ }
794
+ acquire() {
795
+ if (this.cursor_ >= 0) {
796
+ return this.pool_[this.cursor_--];
797
+ }
798
+ return this.factory_();
799
+ }
800
+ release(obj) {
801
+ this.pool_[++this.cursor_] = obj;
802
+ }
803
+ grow() {
804
+ const oldSize = this.pool_.length;
805
+ const newSize = oldSize * 2;
806
+ for (let i = oldSize; i < newSize; i++) this.pool_[i] = this.factory_();
807
+ this.cursor_ = newSize - 1;
808
+ this.pool_.length = newSize;
809
+ }
810
+ };
811
+
812
+ // src/ecs/components/component-storage.ts
813
+ import { Bitmap as Bitmap2 } from "bitmap-index";
814
+ var ComponentStorage = class {
815
+ bits_;
816
+ data_ = [];
817
+ entityIds_ = [];
818
+ indexMap_ = /* @__PURE__ */ new Map();
819
+ pool_;
820
+ id_ = 0;
821
+ size_ = 0;
822
+ cls;
823
+ constructor(cap = ECS_DEFAULTS.MAX_ENTITY_COUNT, factory, cls) {
824
+ this.bits_ = new Bitmap2(cap);
825
+ this.pool_ = new ObjectPool(factory, 0);
826
+ this.cls = cls;
827
+ }
828
+ bitmap() {
829
+ return this.bits_;
830
+ }
831
+ get id() {
832
+ return this.id_;
833
+ }
834
+ _internalSetId(id2) {
835
+ return this.id_ = id2;
836
+ }
837
+ add(id2, initFn) {
838
+ if (this.indexMap_.has(id2)) {
839
+ throw new Error(`[ComponentStorage "${this.cls.name}"]: Entity ${id2} already has this component`);
840
+ }
841
+ const obj = this.pool_.acquire();
842
+ initFn?.(obj);
843
+ const index = this.data_.length;
844
+ this.data_.push(obj);
845
+ this.entityIds_.push(id2);
846
+ this.indexMap_.set(id2, index);
847
+ this.bits_.set(id2);
848
+ this.size_++;
849
+ return obj;
850
+ }
851
+ remove(id2) {
852
+ const index = this.indexMap_.get(id2);
853
+ if (index === void 0) return;
854
+ this.bits_.remove(id2);
855
+ const lastIndex = this.data_.length - 1;
856
+ const lastEntityId = this.entityIds_[lastIndex];
857
+ const removedObj = this.data_[index];
858
+ if (index !== lastIndex) {
859
+ this.data_[index] = this.data_[lastIndex];
860
+ this.entityIds_[index] = lastEntityId;
861
+ this.indexMap_.set(lastEntityId, index);
862
+ }
863
+ this.data_.pop();
864
+ this.entityIds_.pop();
865
+ this.indexMap_.delete(id2);
866
+ this.pool_.release(removedObj);
867
+ this.size_--;
868
+ }
869
+ get(id2) {
870
+ const index = this.indexMap_.get(id2);
871
+ return index !== void 0 ? this.data_[index] : null;
872
+ }
873
+ tryGet(id2) {
874
+ const index = this.indexMap_.get(id2);
875
+ if (index === void 0)
876
+ throw new Error(`[ComponentStorage "${this.cls.name}"]: Requesting non-existing item with ID ${id2}.`);
877
+ return this.data_[index];
878
+ }
879
+ writeComponentsToBuf(ids, out) {
880
+ let len = 0;
881
+ for (const id2 of ids) {
882
+ const index = this.indexMap_.get(id2);
883
+ if (index !== void 0) out[len++] = this.data_[index];
884
+ }
885
+ return len;
886
+ }
887
+ has(id2) {
888
+ return this.bits_.contains(id2);
889
+ }
890
+ size() {
891
+ return this.size_;
892
+ }
893
+ forEach(cb) {
894
+ for (const id2 of this.entityIds_) {
895
+ cb(id2);
896
+ }
897
+ }
898
+ };
899
+
900
+ // src/ecs/components/manager.ts
901
+ var ComponentAlreadyRegisteredError = class extends Error {
902
+ constructor(component) {
903
+ super(`Component ${component.name} already registered!`);
904
+ }
905
+ };
906
+ var ComponentsManager = class {
907
+ constructor(logger, maxEntityCount = ECS_DEFAULTS.MAX_ENTITY_COUNT) {
908
+ this.logger = logger;
909
+ this.maxEntityCount = maxEntityCount;
910
+ }
911
+ logger;
912
+ maxEntityCount;
913
+ storages_ = /* @__PURE__ */ new Map();
914
+ currId_ = 0;
915
+ nextId() {
916
+ return ++this.currId_;
917
+ }
918
+ register(component, opts) {
919
+ if (this.storages_.has(component))
920
+ return this.storages_.get(component);
921
+ const store = this.createComponentStore(component, opts);
922
+ this.storages_.set(component, store);
923
+ const meta = getComponentMetadata(component);
924
+ this.logger.debug(() => `[Components]: Registered component "${meta.name}"`);
925
+ return store;
926
+ }
927
+ createComponentStore(component, opts) {
928
+ const factory = opts?.factory ?? ((...args) => new component(...args));
929
+ const store = new ComponentStorage(this.maxEntityCount, factory, component);
930
+ store._internalSetId(this.nextId());
931
+ return store;
932
+ }
933
+ getStorage(component) {
934
+ const store = this.storages_.get(component);
935
+ if (store === void 0)
936
+ throw new UnregisteredComponentStorageError(component);
937
+ return store;
938
+ }
939
+ getComponentId(ctor) {
940
+ return getComponentId(ctor);
941
+ }
942
+ };
943
+
944
+ // src/std/math/vector.ts
945
+ var Vector2 = class _Vector2 {
946
+ constructor(x = 0, y = 0) {
947
+ this.x = x;
948
+ this.y = y;
949
+ }
950
+ x;
951
+ y;
952
+ toVec3(z = 0) {
953
+ return new Vector3(this.x, this.y, z);
954
+ }
955
+ toVec4(z = 0, w = 0) {
956
+ return new Vector4(this.x, this.y, z, w);
957
+ }
958
+ clone() {
959
+ return new _Vector2(this.x, this.y);
960
+ }
961
+ set(x, y) {
962
+ this.x = x;
963
+ this.y = y;
964
+ return this;
965
+ }
966
+ equals(v) {
967
+ return this.x === v.x && this.y === v.y;
968
+ }
969
+ add(other) {
970
+ this.x += other.x;
971
+ this.y += other.y;
972
+ return this;
973
+ }
974
+ sub(other) {
975
+ this.x -= other.x;
976
+ this.y -= other.y;
977
+ return this;
978
+ }
979
+ mulScalar(s) {
980
+ this.x *= s;
981
+ this.y *= s;
982
+ return this;
983
+ }
984
+ divScalar(s) {
985
+ if (s === 0) {
986
+ this.x = 0;
987
+ this.y = 0;
988
+ return this;
989
+ }
990
+ this.x /= s;
991
+ this.y /= s;
992
+ return this;
993
+ }
994
+ negate() {
995
+ this.x *= -1;
996
+ this.y *= -1;
997
+ return this;
998
+ }
999
+ length() {
1000
+ return Math.sqrt(this.x ** 2 + this.y ** 2);
1001
+ }
1002
+ normalize() {
1003
+ const m = this.length();
1004
+ if (m !== 0) {
1005
+ this.x = this.x / m;
1006
+ this.y = this.y / m;
1007
+ }
1008
+ return this;
1009
+ }
1010
+ normalized() {
1011
+ return this.clone().normalize();
1012
+ }
1013
+ };
1014
+ var Vector3 = class _Vector3 {
1015
+ constructor(x = 0, y = 0, z = 0) {
1016
+ this.x = x;
1017
+ this.y = y;
1018
+ this.z = z;
1019
+ }
1020
+ x;
1021
+ y;
1022
+ z;
1023
+ toVec2() {
1024
+ return new Vector2(this.x, this.y);
1025
+ }
1026
+ toVec4(w = 0) {
1027
+ return new Vector4(this.x, this.y, this.z, w);
1028
+ }
1029
+ clone() {
1030
+ return new _Vector3(this.x, this.y, this.z);
1031
+ }
1032
+ set(x, y, z) {
1033
+ this.x = x;
1034
+ this.y = y;
1035
+ this.z = z;
1036
+ return this;
1037
+ }
1038
+ equals(v) {
1039
+ return this.x === v.x && this.y === v.y && this.z === v.z;
1040
+ }
1041
+ add(other) {
1042
+ this.x += other.x;
1043
+ this.y += other.y;
1044
+ this.z += other.z;
1045
+ return this;
1046
+ }
1047
+ sub(other) {
1048
+ this.x -= other.x;
1049
+ this.y -= other.y;
1050
+ this.z -= other.z;
1051
+ return this;
1052
+ }
1053
+ mulScalar(s) {
1054
+ this.x *= s;
1055
+ this.y *= s;
1056
+ this.z *= s;
1057
+ return this;
1058
+ }
1059
+ divScalar(s) {
1060
+ if (s === 0) {
1061
+ this.x = 0;
1062
+ this.y = 0;
1063
+ this.z = 0;
1064
+ return this;
1065
+ }
1066
+ this.x /= s;
1067
+ this.y /= s;
1068
+ this.z /= s;
1069
+ return this;
1070
+ }
1071
+ negate() {
1072
+ this.x *= -1;
1073
+ this.y *= -1;
1074
+ this.z *= -1;
1075
+ return this;
1076
+ }
1077
+ length() {
1078
+ return Math.sqrt(this.x ** 2 + this.y ** 2 + this.z ** 2);
1079
+ }
1080
+ normalize() {
1081
+ const m = this.length();
1082
+ if (m !== 0) {
1083
+ this.x = this.x / m;
1084
+ this.y = this.y / m;
1085
+ this.z = this.z / m;
1086
+ }
1087
+ return this;
1088
+ }
1089
+ normalized() {
1090
+ return this.clone().normalize();
1091
+ }
1092
+ };
1093
+ var Vector4 = class _Vector4 {
1094
+ constructor(x = 0, y = 0, z = 0, w = 0) {
1095
+ this.x = x;
1096
+ this.y = y;
1097
+ this.z = z;
1098
+ this.w = w;
1099
+ }
1100
+ x;
1101
+ y;
1102
+ z;
1103
+ w;
1104
+ toVec2() {
1105
+ return new Vector2(this.x, this.y);
1106
+ }
1107
+ toVec3() {
1108
+ return new Vector3(this.x, this.y, this.z);
1109
+ }
1110
+ clone() {
1111
+ return new _Vector4(this.x, this.y, this.z, this.w);
1112
+ }
1113
+ set(x, y, z, w) {
1114
+ this.x = x;
1115
+ this.y = y;
1116
+ this.z = z;
1117
+ this.w = w;
1118
+ return this;
1119
+ }
1120
+ equals(v) {
1121
+ return this.x === v.x && this.y === v.y && this.z === v.z && this.w === v.w;
1122
+ }
1123
+ add(other) {
1124
+ this.x += other.x;
1125
+ this.y += other.y;
1126
+ this.z += other.z;
1127
+ this.w += other.w;
1128
+ return this;
1129
+ }
1130
+ sub(other) {
1131
+ this.x -= other.x;
1132
+ this.y -= other.y;
1133
+ this.z -= other.z;
1134
+ this.w -= other.w;
1135
+ return this;
1136
+ }
1137
+ mulScalar(s) {
1138
+ this.x *= s;
1139
+ this.y *= s;
1140
+ this.z *= s;
1141
+ this.w *= s;
1142
+ return this;
1143
+ }
1144
+ divScalar(s) {
1145
+ if (s === 0) {
1146
+ this.x = 0;
1147
+ this.y = 0;
1148
+ this.z = 0;
1149
+ this.w = 0;
1150
+ return this;
1151
+ }
1152
+ this.x /= s;
1153
+ this.y /= s;
1154
+ this.z /= s;
1155
+ this.w /= s;
1156
+ return this;
1157
+ }
1158
+ negate() {
1159
+ this.x *= -1;
1160
+ this.y *= -1;
1161
+ this.z *= -1;
1162
+ this.w *= -1;
1163
+ return this;
1164
+ }
1165
+ length() {
1166
+ return Math.sqrt(this.x ** 2 + this.y ** 2 + this.z ** 2 + this.w ** 2);
1167
+ }
1168
+ normalize() {
1169
+ const m = this.length();
1170
+ if (m !== 0) {
1171
+ this.x = this.x / m;
1172
+ this.y = this.y / m;
1173
+ this.z = this.z / m;
1174
+ this.w = this.w / m;
1175
+ }
1176
+ return this;
1177
+ }
1178
+ normalized() {
1179
+ return this.clone().normalize();
1180
+ }
1181
+ };
1182
+
1183
+ // src/std/components/transform.ts
1184
+ var Transform = class {
1185
+ constructor(position = new Vector3(), rotation = new Vector3(), scale = new Vector3(1, 1, 1)) {
1186
+ this.position = position;
1187
+ this.rotation = rotation;
1188
+ this.scale = scale;
1189
+ }
1190
+ position;
1191
+ rotation;
1192
+ scale;
1193
+ };
1194
+ Transform = __decorateClass([
1195
+ Component({ name: "Transform_stdlib" })
1196
+ ], Transform);
1197
+
1198
+ // src/std/components/velocity.ts
1199
+ var Velocity = class {
1200
+ constructor(linear = new Vector3()) {
1201
+ this.linear = linear;
1202
+ }
1203
+ linear;
1204
+ };
1205
+ Velocity = __decorateClass([
1206
+ Component({ name: "Velocity_stdlib" })
1207
+ ], Velocity);
1208
+
1209
+ export {
1210
+ __decorateClass,
1211
+ VisitedState,
1212
+ DAGNode,
1213
+ ErrDAGCycleDetected,
1214
+ topologicalSort,
1215
+ SystemError,
1216
+ ErrNotASystem,
1217
+ ErrMissingSystemMetadata,
1218
+ SystemPhase,
1219
+ System,
1220
+ getSystemMetadata,
1221
+ isSystem,
1222
+ SystemBase,
1223
+ SystemsManager,
1224
+ Component,
1225
+ UnregisteredComponentStorageError,
1226
+ EntityMaskNotFoundError,
1227
+ EntitiesManager,
1228
+ EntityRef,
1229
+ ECS_DEFAULTS,
1230
+ EventBuffer,
1231
+ createEventKey,
1232
+ EventBus,
1233
+ ObjectPool,
1234
+ ComponentStorage,
1235
+ ComponentAlreadyRegisteredError,
1236
+ ComponentsManager,
1237
+ Resource,
1238
+ getResourceMetadata,
1239
+ ResourcesManager,
1240
+ entry,
1241
+ Commands,
1242
+ Plugin,
1243
+ getPluginMetadata,
1244
+ isPlugin,
1245
+ PluginBase,
1246
+ PluginError,
1247
+ ErrNotAPlugin,
1248
+ ErrMissingPluginMetadata,
1249
+ ErrUnknownPlugin,
1250
+ ErrPluginNotInit,
1251
+ PluginsManager,
1252
+ World2 as World,
1253
+ Transform,
1254
+ Velocity
1255
+ };
1256
+ //# sourceMappingURL=chunk-SWTBVK53.js.map