@combos-fun/engine 0.0.1

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,1682 @@
1
+ 'use strict';
2
+
3
+ var EventEmitter = require('eventemitter3');
4
+ var lodashEs = require('lodash-es');
5
+ var tslib = require('tslib');
6
+ var inspectorDecorator = require('@combos-fun/inspector-decorator');
7
+ var resourceLoader$1 = require('resource-loader');
8
+
9
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
10
+
11
+ var EventEmitter__default = /*#__PURE__*/_interopDefault(EventEmitter);
12
+
13
+ /**
14
+ * Get component name from component instance or Component class
15
+ * @param component - component instance or Component class
16
+ * @returns component' name
17
+ * @example
18
+ * ```typescript
19
+ * import { Transform } from '@combos-fun/engine'
20
+ *
21
+ * assert(getComponentName(Transform) === 'Transform')
22
+ * assert(getComponentName(new Transform()) === 'Transform')
23
+ * ```
24
+ */
25
+ function getComponentName(component) {
26
+ if (component instanceof Component) {
27
+ return component.name;
28
+ }
29
+ else if (component instanceof Function) {
30
+ return component.componentName;
31
+ }
32
+ }
33
+ /**
34
+ * Component contain raw data apply to gameObject and how it interacts with the world
35
+ * @public
36
+ */
37
+ class Component extends EventEmitter__default.default {
38
+ constructor(params) {
39
+ super();
40
+ /**
41
+ * Represents the status of the component, If component has started, the value is true
42
+ * @defaultValue false
43
+ */
44
+ this.started = false;
45
+ const Ctor = this.constructor;
46
+ this.name = Ctor.componentName;
47
+ this.__componentDefaultParams = params;
48
+ }
49
+ }
50
+
51
+ /** Observer event type */
52
+ exports.OBSERVER_TYPE = void 0;
53
+ (function (ObserverType) {
54
+ ObserverType["ADD"] = "ADD";
55
+ ObserverType["REMOVE"] = "REMOVE";
56
+ ObserverType["CHANGE"] = "CHANGE";
57
+ })(exports.OBSERVER_TYPE || (exports.OBSERVER_TYPE = {}));
58
+ const objectCache = {};
59
+ const systemInstance = {};
60
+ const observerInfos = {};
61
+ const componentProps = {};
62
+ /**
63
+ * Get the `ObjectCache` on `component` access by `keys`
64
+ * @example
65
+ * ```typescript
66
+ * getObjectCache(testComponent, ['style', 'transform', 'scale'])
67
+ * ```
68
+ * @param {Component} component
69
+ * @param {string[]} keys - access path to properties, such as ['style', 'transform', 'scale', 'x']
70
+ * @returns {ObservableItem}
71
+ */
72
+ function getObjectCache(component, keys) {
73
+ if (!objectCache[component.gameObject.id]) {
74
+ objectCache[component.gameObject.id] = {};
75
+ }
76
+ const cache = objectCache[component.gameObject.id];
77
+ const key = component.name + '_' + keys.join(',');
78
+ if (cache[key]) {
79
+ return cache[key];
80
+ }
81
+ const keyIndex = keys.length - 1;
82
+ let property = component;
83
+ // FIXME: Bug is here, property[keys[i]] maybe undefined
84
+ for (let i = 0; i < keyIndex; i++) {
85
+ property = property[keys[i]];
86
+ }
87
+ cache[key] = { property, key: keys[keyIndex] };
88
+ return cache[key];
89
+ }
90
+ /**
91
+ * Remove property cache by component
92
+ * @remarks
93
+ * The component should added to a gameObject, otherwise there is no gameObject on component
94
+ * @param {Component} component - a component that has been added to gameObject
95
+ */
96
+ function removeObjectCache(component) {
97
+ if (component.gameObject) {
98
+ delete objectCache[component.gameObject.id];
99
+ }
100
+ }
101
+ /**
102
+ * Add observe event to `componentObserver` on system
103
+ * @param {string} param0.systemName - system name
104
+ * @param {string} param0.componentName - compnent name
105
+ * @param {Component} param0.component - component instance
106
+ * @param {pureObserverProp} param0.prop - pure observer prop
107
+ * @param {ObserverType} param0.type - observer type
108
+ */
109
+ function addObserver({ systemName, componentName, component, prop, type }) {
110
+ systemInstance[systemName]?.componentObserver?.add({
111
+ component,
112
+ prop,
113
+ type,
114
+ componentName,
115
+ });
116
+ }
117
+ function pushToQueue({ prop, component, componentName, }) {
118
+ for (const systemName in observerInfos) {
119
+ const observerInfo = observerInfos[systemName] || {};
120
+ const info = observerInfo[componentName];
121
+ if (!info)
122
+ continue;
123
+ const index = info.findIndex(p => {
124
+ return lodashEs.isEqual(p, prop);
125
+ });
126
+ if (index > -1) {
127
+ addObserver({
128
+ systemName,
129
+ componentName,
130
+ component,
131
+ prop,
132
+ type: exports.OBSERVER_TYPE.CHANGE,
133
+ });
134
+ }
135
+ }
136
+ }
137
+ /**
138
+ * Define property `key` for obj, make `key` observable
139
+ * @param {Object} param0.obj - object contains the 'key'
140
+ * @param {string} param0.key - the key will be observed
141
+ * @param {PureObserverProp} param0.prop
142
+ * @param {Component} param0.component
143
+ * @param {strng} param0.componentName
144
+ */
145
+ function defineProperty({ obj, key, prop, component, componentName, }) {
146
+ if (obj === undefined) {
147
+ return;
148
+ }
149
+ if (!(key in obj)) {
150
+ console.error(`prop ${key} not in component: ${componentName}, Can not observer`);
151
+ return;
152
+ }
153
+ Object.defineProperty(obj, `_${key}`, {
154
+ enumerable: false,
155
+ writable: true,
156
+ value: obj[key],
157
+ });
158
+ if (prop.deep && lodashEs.isObject(obj[key])) {
159
+ for (const childKey of Object.keys(obj[key])) {
160
+ defineProperty({
161
+ obj: obj[key],
162
+ key: childKey, // Bug is here
163
+ prop,
164
+ component,
165
+ componentName,
166
+ });
167
+ }
168
+ }
169
+ Object.defineProperty(obj, key, {
170
+ enumerable: true,
171
+ set(val) {
172
+ if (obj[`_${key}`] === val)
173
+ return;
174
+ obj[`_${key}`] = val;
175
+ pushToQueue({ prop, component, componentName });
176
+ },
177
+ get() {
178
+ return obj[`_${key}`];
179
+ },
180
+ });
181
+ }
182
+ /**
183
+ * Return true if parameter is a component
184
+ * @param comp - any thing
185
+ * @returns {bool}
186
+ */
187
+ function isComponent(comp) {
188
+ return comp && comp.constructor && 'componentName' in comp.constructor;
189
+ }
190
+ /**
191
+ * Collect observerInfo on system
192
+ * @param Systems - array of system or just a system
193
+ */
194
+ function initObserver(Systems) {
195
+ const Ss = [];
196
+ if (Systems instanceof Array) {
197
+ Ss.push(...Systems);
198
+ }
199
+ else {
200
+ Ss.push(Systems);
201
+ }
202
+ for (const S of Ss) {
203
+ for (const componentName in S.observerInfo) {
204
+ componentProps[componentName] = componentProps[componentName] || [];
205
+ const props = componentProps[componentName];
206
+ for (const prop of S.observerInfo[componentName]) {
207
+ const index = props.findIndex(p => {
208
+ return lodashEs.isEqual(p, prop);
209
+ });
210
+ if (index === -1) {
211
+ componentProps[componentName].push(prop);
212
+ }
213
+ }
214
+ }
215
+ }
216
+ }
217
+ /**
218
+ * Make component observerable
219
+ * @remarks
220
+ * Throw an error if component not added to a gameObject
221
+ * @param {Component} component
222
+ * @param {string} componentName - default value is `component.name`, it will be deprecated
223
+ */
224
+ function observer(component, componentName = component.name) {
225
+ if (!componentName || !componentProps[componentName]) {
226
+ return;
227
+ }
228
+ if (!component || !isComponent(component)) {
229
+ throw new Error('component param must be an instance of Component');
230
+ }
231
+ if (!component.gameObject || !component.gameObject.id) {
232
+ throw new Error('component should be add to a gameObject');
233
+ }
234
+ for (const item of componentProps[componentName]) {
235
+ const { property, key } = getObjectCache(component, item.prop);
236
+ defineProperty({
237
+ obj: property,
238
+ key,
239
+ prop: item,
240
+ component,
241
+ componentName,
242
+ });
243
+ }
244
+ }
245
+ /**
246
+ * Push a `Add` event to componentObserver
247
+ * @param component
248
+ * @param componentName - default value is `component.name`, it will be deprecated
249
+ */
250
+ function observerAdded(component, componentName = component.name) {
251
+ for (const systemName in observerInfos) {
252
+ const observerInfo = observerInfos[systemName] || {};
253
+ const info = observerInfo[componentName];
254
+ if (info) {
255
+ systemInstance[systemName]?.componentObserver?.add({
256
+ component,
257
+ type: exports.OBSERVER_TYPE.ADD,
258
+ componentName,
259
+ });
260
+ }
261
+ }
262
+ }
263
+ /**
264
+ * Push a `Remove` event to componentObserver
265
+ * @param component
266
+ * @param componentName - default value is `component.name`, it will be deprecated
267
+ */
268
+ function observerRemoved(component, componentName = component.name) {
269
+ for (const systemName in observerInfos) {
270
+ const observerInfo = observerInfos[systemName] || {};
271
+ const info = observerInfo[componentName];
272
+ if (info) {
273
+ systemInstance[systemName]?.componentObserver?.add({
274
+ component,
275
+ type: exports.OBSERVER_TYPE.REMOVE,
276
+ componentName,
277
+ });
278
+ }
279
+ }
280
+ removeObjectCache(component);
281
+ }
282
+ /**
283
+ * Collect observerInfo from system
284
+ * @param system - system instance
285
+ * @param S - system constructor
286
+ */
287
+ function setSystemObserver(system, S) {
288
+ observerInfos[S.systemName] = S.observerInfo;
289
+ systemInstance[S.systemName] = system;
290
+ }
291
+
292
+ /** Basic component for gameObject, See {@link TransformParams} */
293
+ class Transform extends Component {
294
+ constructor() {
295
+ super(...arguments);
296
+ this.name = 'Transform';
297
+ this._parent = null;
298
+ /** Whether this transform in a scene object */
299
+ this.inScene = false;
300
+ /** Child transform components */
301
+ this.children = [];
302
+ this.position = { x: 0, y: 0 };
303
+ this.size = { width: 0, height: 0 };
304
+ this.origin = { x: 0, y: 0 };
305
+ this.anchor = { x: 0, y: 0 };
306
+ this.scale = { x: 1, y: 1 };
307
+ this.skew = { x: 0, y: 0 };
308
+ this.rotation = 0;
309
+ }
310
+ /**
311
+ * component's name
312
+ * @readonly
313
+ */
314
+ static { this.componentName = 'Transform'; }
315
+ /**
316
+ * Init component
317
+ * @param params - Transform init data
318
+ */
319
+ init(params = {}) {
320
+ const props = ['position', 'size', 'origin', 'anchor', 'scale', 'skew'];
321
+ for (const key of props) {
322
+ Object.assign(this[key], params[key]);
323
+ }
324
+ this.rotation = params.rotation || this.rotation;
325
+ }
326
+ set parent(val) {
327
+ if (val) {
328
+ val.addChild(this);
329
+ }
330
+ else if (this.parent) {
331
+ this.parent.removeChild(this);
332
+ }
333
+ }
334
+ /**
335
+ * Get parent of this component
336
+ */
337
+ get parent() {
338
+ return this._parent;
339
+ }
340
+ /**
341
+ * Add Child Transform
342
+ * @remarks
343
+ * If `child` is already a child of this component, `child` will removed to the last of children list
344
+ * If `child` is already a child of other component, `child` will removed from its parent first
345
+ * @param child - child gameObject's transform component
346
+ */
347
+ addChild(child) {
348
+ if (child.parent === this) {
349
+ const index = this.children.findIndex(item => item === child);
350
+ this.children.splice(index, 1);
351
+ }
352
+ else if (child.parent) {
353
+ child.parent.removeChild(child);
354
+ }
355
+ child._parent = this;
356
+ this.children.push(child);
357
+ }
358
+ /**
359
+ * Remove child transform
360
+ * @param child - child gameObject's transform component
361
+ */
362
+ removeChild(child) {
363
+ const index = this.children.findIndex(item => item === child);
364
+ if (index > -1) {
365
+ this.children.splice(index, 1);
366
+ child._parent = null;
367
+ }
368
+ }
369
+ /** Clear all child transform */
370
+ clearChildren() {
371
+ this.children.length = 0;
372
+ }
373
+ }
374
+ tslib.__decorate([
375
+ inspectorDecorator.type('vector2'),
376
+ inspectorDecorator.step(1)
377
+ ], Transform.prototype, "position", void 0);
378
+ tslib.__decorate([
379
+ inspectorDecorator.type('size'),
380
+ inspectorDecorator.step(1)
381
+ ], Transform.prototype, "size", void 0);
382
+ tslib.__decorate([
383
+ inspectorDecorator.type('vector2'),
384
+ inspectorDecorator.step(0.1)
385
+ ], Transform.prototype, "origin", void 0);
386
+ tslib.__decorate([
387
+ inspectorDecorator.type('vector2'),
388
+ inspectorDecorator.step(0.1)
389
+ ], Transform.prototype, "anchor", void 0);
390
+ tslib.__decorate([
391
+ inspectorDecorator.type('vector2'),
392
+ inspectorDecorator.step(0.1)
393
+ ], Transform.prototype, "scale", void 0);
394
+ tslib.__decorate([
395
+ inspectorDecorator.type('vector2'),
396
+ inspectorDecorator.step(0.1)
397
+ ], Transform.prototype, "skew", void 0);
398
+ tslib.__decorate([
399
+ inspectorDecorator.type('number'),
400
+ inspectorDecorator.step(0.1)
401
+ ], Transform.prototype, "rotation", void 0);
402
+
403
+ let _id = 0;
404
+ /** Generate unique id for gameObject */
405
+ function getId() {
406
+ return ++_id;
407
+ }
408
+ /**
409
+ * GameObject is a general purpose object. It consists of a unique id and components.
410
+ * @public
411
+ */
412
+ class GameObject {
413
+ /**
414
+ * Consruct a new gameObject
415
+ * @param name - the name of this gameObject
416
+ * @param obj - optional transform parameters for default Transform component
417
+ */
418
+ constructor(name, obj) {
419
+ /** A key-value map for components on this gameObject */
420
+ this._componentCache = {};
421
+ /** Components apply to this gameObject */
422
+ this.components = [];
423
+ /** GameObject has been destroyed */
424
+ this.destroyed = false;
425
+ this._name = name;
426
+ this.id = getId();
427
+ this.addComponent(Transform, obj);
428
+ }
429
+ /**
430
+ * Get default transform component
431
+ * @returns transform component on this gameObject
432
+ * @readonly
433
+ */
434
+ get transform() {
435
+ return this.getComponent(Transform);
436
+ }
437
+ /**
438
+ * Get parent gameObject
439
+ * @returns parent gameObject
440
+ * @readonly
441
+ */
442
+ get parent() {
443
+ return this.transform && this.transform.parent && this.transform.parent.gameObject;
444
+ }
445
+ /**
446
+ * Get the name of this gameObject
447
+ * @readonly
448
+ */
449
+ get name() {
450
+ return this._name;
451
+ }
452
+ set scene(val) {
453
+ if (this._scene === val)
454
+ return;
455
+ const scene = this._scene;
456
+ this._scene = val;
457
+ if (this.transform && this.transform.children) {
458
+ for (const child of this.transform.children) {
459
+ child.gameObject.scene = val;
460
+ }
461
+ }
462
+ if (val) {
463
+ val.addGameObject(this);
464
+ }
465
+ else {
466
+ scene && scene.removeGameObject(this);
467
+ }
468
+ }
469
+ /**
470
+ * Get the scene which this gameObject added on
471
+ * @returns scene
472
+ * @readonly
473
+ */
474
+ get scene() {
475
+ return this._scene;
476
+ }
477
+ /**
478
+ * Add child gameObject
479
+ * @param gameObject - child gameobject
480
+ */
481
+ addChild(gameObject) {
482
+ if (!gameObject || !gameObject.transform || gameObject === this)
483
+ return;
484
+ if (!(gameObject instanceof GameObject)) {
485
+ throw new Error('addChild only receive GameObject');
486
+ }
487
+ if (!this.transform) {
488
+ throw new Error(`gameObject '${this.name}' has been destroy`);
489
+ }
490
+ gameObject.transform.parent = this.transform;
491
+ gameObject.scene = this.scene;
492
+ }
493
+ /**
494
+ * Remove child gameObject
495
+ * @param gameObject - child gameobject
496
+ */
497
+ removeChild(gameObject) {
498
+ if (!(gameObject instanceof GameObject) || !gameObject.parent || gameObject.parent !== this) {
499
+ return gameObject;
500
+ }
501
+ gameObject.transform.parent = null;
502
+ gameObject.scene = null;
503
+ return gameObject;
504
+ }
505
+ addComponent(C, obj) {
506
+ if (this.destroyed)
507
+ return;
508
+ const componentName = getComponentName(C);
509
+ if (this._componentCache[componentName])
510
+ return;
511
+ let component;
512
+ if (C instanceof Function) {
513
+ component = new C(obj);
514
+ }
515
+ else if (C instanceof Component) {
516
+ component = C;
517
+ }
518
+ else {
519
+ throw new Error('addComponent recieve Component and Component Constructor');
520
+ }
521
+ if (component.gameObject) {
522
+ throw new Error(`component has been added on gameObject ${component.gameObject.name}`);
523
+ }
524
+ component.gameObject = this;
525
+ component.init && component.init(component.__componentDefaultParams);
526
+ observerAdded(component, component.name);
527
+ observer(component, component.name);
528
+ this.components.push(component);
529
+ this._componentCache[componentName] = component;
530
+ component.awake && component.awake();
531
+ return component;
532
+ }
533
+ removeComponent(c) {
534
+ let componentName;
535
+ if (typeof c === 'string') {
536
+ componentName = c;
537
+ }
538
+ else if (c instanceof Component) {
539
+ componentName = c.name;
540
+ }
541
+ else if (c.componentName) {
542
+ componentName = c.componentName;
543
+ }
544
+ if (componentName === 'Transform') {
545
+ throw new Error("Transform can't be removed");
546
+ }
547
+ return this._removeComponent(componentName);
548
+ }
549
+ _removeComponent(componentName) {
550
+ const index = this.components.findIndex(({ name }) => name === componentName);
551
+ if (index === -1)
552
+ return;
553
+ const component = this.components.splice(index, 1)[0];
554
+ delete this._componentCache[componentName];
555
+ delete component.__componentDefaultParams;
556
+ component.onDestroy && component.onDestroy();
557
+ observerRemoved(component, componentName);
558
+ component.gameObject = undefined;
559
+ return component;
560
+ }
561
+ getComponent(c) {
562
+ let componentName;
563
+ if (typeof c === 'string') {
564
+ componentName = c;
565
+ }
566
+ else if (c instanceof Component) {
567
+ componentName = c.name;
568
+ }
569
+ else if (c.componentName) {
570
+ componentName = c.componentName;
571
+ }
572
+ if (typeof this._componentCache[componentName] !== 'undefined') {
573
+ return this._componentCache[componentName];
574
+ }
575
+ else {
576
+ return;
577
+ }
578
+ }
579
+ /**
580
+ * Remove this gameObject on its parent
581
+ * @returns return this gameObject
582
+ */
583
+ remove() {
584
+ if (this.parent)
585
+ return this.parent.removeChild(this);
586
+ }
587
+ /** Destory this gameObject */
588
+ destroy() {
589
+ if (!this.transform) {
590
+ console.error('Cannot destroy gameObject that have already been destroyed.');
591
+ return;
592
+ }
593
+ Array.from(this.transform.children).forEach(({ gameObject }) => {
594
+ gameObject.destroy();
595
+ });
596
+ this.remove();
597
+ this.transform.clearChildren();
598
+ for (const key in this._componentCache) {
599
+ this._removeComponent(key);
600
+ }
601
+ this.components.length = 0;
602
+ this.destroyed = true;
603
+ }
604
+ }
605
+
606
+ /**
607
+ * Management observe events
608
+ * @remarks
609
+ * See {@link System} for more details
610
+ * @public
611
+ */
612
+ class ComponentObserver {
613
+ constructor() {
614
+ /**
615
+ * Component property change events
616
+ * @defaultValue []
617
+ */
618
+ this.events = [];
619
+ }
620
+ /**
621
+ * Add event
622
+ * @remarks
623
+ * The same event will be placed last
624
+ * @param component - changed component
625
+ * @param prop - changed property on `component`
626
+ * @param type - change event type
627
+ * @param componentName - `component.name` this parameter will deprecated
628
+ */
629
+ add({ component, prop, type, componentName }) {
630
+ if (type === exports.OBSERVER_TYPE.REMOVE) {
631
+ if (this.events.find((changed) => changed.component === component && changed.type === exports.OBSERVER_TYPE.ADD)) {
632
+ this.events = this.events.filter(changed => changed.component !== component);
633
+ return;
634
+ }
635
+ this.events = this.events.filter(changed => changed.component !== component);
636
+ }
637
+ const index = this.events.findIndex(changed => changed.component === component && lodashEs.isEqual(changed.prop, prop) && changed.type === type);
638
+ if (index > -1) {
639
+ this.events.splice(index, 1);
640
+ }
641
+ this.events.push({
642
+ gameObject: component.gameObject,
643
+ component,
644
+ prop: prop,
645
+ type,
646
+ componentName,
647
+ });
648
+ }
649
+ /** Return change events */
650
+ getChanged() {
651
+ return this.events;
652
+ }
653
+ /**
654
+ * Return change events
655
+ * @readonly
656
+ */
657
+ get changed() {
658
+ return this.events;
659
+ }
660
+ /** Clear events */
661
+ clear() {
662
+ const events = this.events;
663
+ this.events = [];
664
+ return events;
665
+ }
666
+ }
667
+
668
+ /**
669
+ * Each System runs continuously and performs global actions on every Entity that possesses a Component of the same aspect as that System.
670
+ * @public
671
+ */
672
+ class System {
673
+ constructor(params) {
674
+ /** Represents the status of the component, if component has started, the value is true */
675
+ this.started = false;
676
+ this.componentObserver = new ComponentObserver();
677
+ this.__systemDefaultParams = params;
678
+ const Ctor = this.constructor;
679
+ this.name = Ctor.systemName;
680
+ }
681
+ /** Default destory method */
682
+ destroy() {
683
+ this.componentObserver = null;
684
+ this.__systemDefaultParams = null;
685
+ this.onDestroy?.();
686
+ }
687
+ }
688
+
689
+ function createNowTime() {
690
+ let nowtime = null;
691
+ if (Date.now) {
692
+ nowtime = Date.now;
693
+ }
694
+ else {
695
+ nowtime = () => new Date().getTime();
696
+ }
697
+ return nowtime;
698
+ }
699
+
700
+ const _nowtime = createNowTime();
701
+ const defaultOptions$1 = {
702
+ originTime: 0,
703
+ playbackRate: 1.0,
704
+ };
705
+ class Timeline {
706
+ constructor(options, parent) {
707
+ if (options instanceof Timeline) {
708
+ parent = options;
709
+ options = {};
710
+ }
711
+ options = Object.assign({}, defaultOptions$1, options);
712
+ if (parent) {
713
+ this._parent = parent;
714
+ }
715
+ this._createTime = _nowtime();
716
+ this._timeMark = [
717
+ {
718
+ globalTime: this.globalTime,
719
+ localTime: -options.originTime,
720
+ entropy: -options.originTime,
721
+ playbackRate: options.playbackRate,
722
+ globalEntropy: 0,
723
+ },
724
+ ];
725
+ if (this._parent) {
726
+ this._timeMark[0].globalEntropy = this._parent.entropy;
727
+ }
728
+ this._playbackRate = options.playbackRate;
729
+ }
730
+ get globalTime() {
731
+ return this.parent ? this.parent.currentTime : _nowtime() - this._createTime;
732
+ }
733
+ get parent() {
734
+ return this._parent;
735
+ }
736
+ get lastTimeMark() {
737
+ return this._timeMark[this._timeMark.length - 1];
738
+ }
739
+ markTime({ time = this.currentTime, entropy = this.entropy, playbackRate = this.playbackRate } = {}) {
740
+ const timeMark = {
741
+ globalTime: this.globalTime,
742
+ localTime: time,
743
+ entropy,
744
+ playbackRate,
745
+ globalEntropy: this.globalEntropy,
746
+ };
747
+ this._timeMark.push(timeMark);
748
+ }
749
+ get currentTime() {
750
+ const { localTime, globalTime } = this.lastTimeMark;
751
+ return localTime + (this.globalTime - globalTime) * this.playbackRate;
752
+ }
753
+ set currentTime(time) {
754
+ this.markTime({ time });
755
+ }
756
+ get globalEntropy() {
757
+ return this._parent ? this._parent.entropy : this.globalTime;
758
+ }
759
+ get entropy() {
760
+ const { entropy, globalEntropy } = this.lastTimeMark;
761
+ return entropy + Math.abs((this.globalEntropy - globalEntropy) * this.playbackRate);
762
+ }
763
+ // eslint-disable-next-line @typescript-eslint/adjacent-overload-signatures
764
+ set entropy(entropy) {
765
+ if (this.entropy > entropy) {
766
+ const idx = this.seekTimeMark(entropy);
767
+ this._timeMark.length = idx + 1;
768
+ }
769
+ this.markTime({ entropy });
770
+ }
771
+ fork(options) {
772
+ return new Timeline(options, this);
773
+ }
774
+ seekGlobalTime(seekEntropy) {
775
+ const idx = this.seekTimeMark(seekEntropy), timeMark = this._timeMark[idx];
776
+ const { entropy, playbackRate, globalTime } = timeMark;
777
+ return globalTime + (seekEntropy - entropy) / Math.abs(playbackRate);
778
+ }
779
+ seekLocalTime(seekEntropy) {
780
+ const idx = this.seekTimeMark(seekEntropy), timeMark = this._timeMark[idx];
781
+ const { localTime, entropy, playbackRate } = timeMark;
782
+ if (playbackRate > 0) {
783
+ return localTime + (seekEntropy - entropy);
784
+ }
785
+ return localTime - (seekEntropy - entropy);
786
+ }
787
+ seekTimeMark(entropy) {
788
+ const timeMark = this._timeMark;
789
+ let l = 0, r = timeMark.length - 1;
790
+ if (entropy <= timeMark[l].entropy) {
791
+ return l;
792
+ }
793
+ if (entropy >= timeMark[r].entropy) {
794
+ return r;
795
+ }
796
+ let m = Math.floor((l + r) / 2); // binary search
797
+ while (m > l && m < r) {
798
+ if (entropy === timeMark[m].entropy) {
799
+ return m;
800
+ }
801
+ if (entropy < timeMark[m].entropy) {
802
+ r = m;
803
+ }
804
+ else if (entropy > timeMark[m].entropy) {
805
+ l = m;
806
+ }
807
+ m = Math.floor((l + r) / 2);
808
+ }
809
+ return l;
810
+ }
811
+ get playbackRate() {
812
+ return this._playbackRate;
813
+ }
814
+ set playbackRate(rate) {
815
+ if (rate !== this.playbackRate) {
816
+ this.markTime({ playbackRate: rate });
817
+ this._playbackRate = rate;
818
+ }
819
+ }
820
+ get paused() {
821
+ if (this.playbackRate === 0)
822
+ return true;
823
+ let parent = this.parent;
824
+ while (parent) {
825
+ if (parent.playbackRate === 0)
826
+ return true;
827
+ parent = parent.parent;
828
+ }
829
+ return false;
830
+ }
831
+ }
832
+
833
+ /** Default Ticker Options */
834
+ const defaultOptions = {
835
+ autoStart: true,
836
+ frameRate: 60,
837
+ };
838
+ /**
839
+ * Timeline tool
840
+ */
841
+ class Ticker {
842
+ /**
843
+ * @param autoStart - auto start game
844
+ * @param frameRate - game frame rate
845
+ */
846
+ constructor(options) {
847
+ options = Object.assign({}, defaultOptions, options);
848
+ this._frameCount = 0;
849
+ this._frameDuration = 1000 / options.frameRate;
850
+ this.autoStart = options.autoStart;
851
+ this.frameRate = options.frameRate;
852
+ this.timeline = new Timeline({ originTime: 0, playbackRate: 1.0 });
853
+ this._lastFrameTime = this.timeline.currentTime;
854
+ this._tickers = new Set();
855
+ this._requestId = null;
856
+ this._ticker = () => {
857
+ if (this._started) {
858
+ this._requestId = requestAnimationFrame(this._ticker);
859
+ this.update();
860
+ }
861
+ };
862
+ if (this.autoStart) {
863
+ this.start();
864
+ }
865
+ }
866
+ /** Main loop, all _tickers will called in this method */
867
+ update() {
868
+ const currentTime = this.timeline.currentTime;
869
+ const durationTime = currentTime - this._lastFrameTime;
870
+ if (durationTime >= this._frameDuration) {
871
+ const frameTime = currentTime - (durationTime % this._frameDuration);
872
+ const deltaTime = frameTime - this._lastFrameTime;
873
+ this._lastFrameTime = frameTime;
874
+ const options = {
875
+ deltaTime,
876
+ time: frameTime,
877
+ currentTime: frameTime,
878
+ frameCount: ++this._frameCount,
879
+ fps: Math.round(1000 / deltaTime),
880
+ };
881
+ for (const func of this._tickers) {
882
+ if (typeof func === 'function') {
883
+ func(options);
884
+ }
885
+ }
886
+ }
887
+ }
888
+ /** Add ticker function */
889
+ add(fn) {
890
+ this._tickers.add(fn);
891
+ }
892
+ /** Remove ticker function */
893
+ remove(fn) {
894
+ this._tickers.delete(fn);
895
+ }
896
+ /** Start main loop */
897
+ start() {
898
+ if (this._started)
899
+ return;
900
+ this._started = true;
901
+ this.timeline.playbackRate = 1.0;
902
+ this._requestId = requestAnimationFrame(this._ticker);
903
+ }
904
+ /** Pause main loop */
905
+ pause() {
906
+ this._started = false;
907
+ this.timeline.playbackRate = 0;
908
+ }
909
+ setPlaybackRate(rate) {
910
+ this.timeline.playbackRate = rate;
911
+ }
912
+ }
913
+
914
+ /**
915
+ * Scene is a gameObject container
916
+ */
917
+ class Scene extends GameObject {
918
+ constructor(name, obj) {
919
+ super(name, obj);
920
+ this.gameObjects = [];
921
+ this.scene = this; // gameObject.scene = this
922
+ }
923
+ /**
924
+ * Add gameObject
925
+ * @param gameObject - game object
926
+ */
927
+ addGameObject(gameObject) {
928
+ this.gameObjects.push(gameObject);
929
+ if (gameObject.transform) {
930
+ gameObject.transform.inScene = true;
931
+ }
932
+ }
933
+ /**
934
+ * Remove gameObject
935
+ * @param gameObject - game object
936
+ */
937
+ removeGameObject(gameObject) {
938
+ const index = this.gameObjects.indexOf(gameObject);
939
+ if (index === -1)
940
+ return;
941
+ if (gameObject.transform) {
942
+ gameObject.transform.inScene = false;
943
+ }
944
+ this.gameObjects.splice(index, 1);
945
+ }
946
+ /**
947
+ * Destroy scene
948
+ */
949
+ destroy() {
950
+ this.scene = null;
951
+ super.destroy();
952
+ this.gameObjects = null;
953
+ this.canvas = null;
954
+ }
955
+ }
956
+
957
+ function systemClassName(ctor) {
958
+ if ('systemName' in ctor) {
959
+ const sn = ctor.systemName;
960
+ if (typeof sn === 'string')
961
+ return sn;
962
+ }
963
+ return 'UnknownSystem';
964
+ }
965
+ function componentClassName(ctor) {
966
+ if ('componentName' in ctor) {
967
+ const cn = ctor.componentName;
968
+ if (typeof cn === 'string')
969
+ return cn;
970
+ }
971
+ return 'UnknownComponent';
972
+ }
973
+ exports.LOAD_SCENE_MODE = void 0;
974
+ (function (LOAD_SCENE_MODE) {
975
+ LOAD_SCENE_MODE["SINGLE"] = "SINGLE";
976
+ LOAD_SCENE_MODE["MULTI_CANVAS"] = "MULTI_CANVAS";
977
+ })(exports.LOAD_SCENE_MODE || (exports.LOAD_SCENE_MODE = {}));
978
+ const triggerStart = (obj) => {
979
+ if (!(obj instanceof System) && !(obj instanceof Component))
980
+ return;
981
+ if (obj.started)
982
+ return;
983
+ obj.started = true;
984
+ try {
985
+ obj.start && obj.start();
986
+ }
987
+ catch (e) {
988
+ if (obj instanceof Component) {
989
+ console.error(`${componentClassName(obj.constructor)} start error`, e);
990
+ }
991
+ else {
992
+ console.error(`${systemClassName(obj.constructor)} start error`, e);
993
+ }
994
+ }
995
+ };
996
+ const getAllGameObjects = game => {
997
+ const mainSceneGameObjects = game?.scene?.gameObjects || [];
998
+ const gameObjectsArray = game?.multiScenes.map(({ gameObjects }) => gameObjects);
999
+ let otherSceneGameObjects = [];
1000
+ for (const gameObjects of gameObjectsArray) {
1001
+ otherSceneGameObjects = [...otherSceneGameObjects, ...gameObjects];
1002
+ }
1003
+ return [...mainSceneGameObjects, ...otherSceneGameObjects];
1004
+ };
1005
+ const gameObjectLoop = (e, gameObjects = []) => {
1006
+ for (const gameObject of gameObjects) {
1007
+ for (const component of gameObject.components) {
1008
+ try {
1009
+ triggerStart(component);
1010
+ component.update && component.update(e);
1011
+ }
1012
+ catch (e) {
1013
+ console.error(`gameObject: ${gameObject.name} ${component.name} update error`, e);
1014
+ }
1015
+ }
1016
+ }
1017
+ for (const gameObject of gameObjects) {
1018
+ for (const component of gameObject.components) {
1019
+ try {
1020
+ component.lateUpdate && component.lateUpdate(e);
1021
+ }
1022
+ catch (e) {
1023
+ console.error(`gameObject: ${gameObject.name} ${component.name} lateUpdate error`, e);
1024
+ }
1025
+ }
1026
+ }
1027
+ };
1028
+ const gameObjectResume = gameObjects => {
1029
+ for (const gameObject of gameObjects) {
1030
+ for (const component of gameObject.components) {
1031
+ try {
1032
+ component.onResume && component.onResume();
1033
+ }
1034
+ catch (e) {
1035
+ console.error(`gameObject: ${gameObject.name}, ${component.name}, onResume error`, e);
1036
+ }
1037
+ }
1038
+ }
1039
+ };
1040
+ const gameObjectPause = gameObjects => {
1041
+ for (const gameObject of gameObjects) {
1042
+ for (const component of gameObject.components) {
1043
+ try {
1044
+ component.onPause && component.onPause();
1045
+ }
1046
+ catch (e) {
1047
+ console.error(`gameObject: ${gameObject.name}, ${component.name}, onResume error`, e);
1048
+ }
1049
+ }
1050
+ }
1051
+ };
1052
+ class Game extends EventEmitter__default.default {
1053
+ constructor({ systems, frameRate = 60, autoStart = true, needScene = true, onSystemsBootstrapComplete, } = {}) {
1054
+ super();
1055
+ /**
1056
+ * State of game
1057
+ * @defaultValue false
1058
+ */
1059
+ this.playing = false;
1060
+ this.started = false;
1061
+ this.multiScenes = [];
1062
+ /** Systems alled to this game */
1063
+ this.systems = [];
1064
+ this.ticker = new Ticker({ autoStart: false, frameRate });
1065
+ this.initTicker();
1066
+ if (systems && systems.length) {
1067
+ const systemsToAdd = [...systems];
1068
+ void this.bootstrapSystemsAndMaybeStart(systemsToAdd, needScene, autoStart, onSystemsBootstrapComplete);
1069
+ }
1070
+ else {
1071
+ onSystemsBootstrapComplete?.(this);
1072
+ }
1073
+ }
1074
+ /** When `systems` is passed in the constructor, run async `init` for each before `loadScene` / `start`. */
1075
+ async bootstrapSystemsAndMaybeStart(systemsToAdd, needScene, autoStart, onComplete) {
1076
+ let error;
1077
+ try {
1078
+ for (const system of systemsToAdd) {
1079
+ await this.addSystem(system);
1080
+ }
1081
+ if (needScene) {
1082
+ this.loadScene(new Scene('scene'));
1083
+ }
1084
+ if (autoStart) {
1085
+ this.start();
1086
+ }
1087
+ }
1088
+ catch (e) {
1089
+ error = e;
1090
+ console.error('Game bootstrap failed', e);
1091
+ }
1092
+ finally {
1093
+ onComplete?.(this, error);
1094
+ }
1095
+ }
1096
+ /**
1097
+ * Get scene on this game
1098
+ */
1099
+ get scene() {
1100
+ return this._scene;
1101
+ }
1102
+ set scene(scene) {
1103
+ this._scene = scene;
1104
+ }
1105
+ get gameObjects() {
1106
+ return getAllGameObjects(this);
1107
+ }
1108
+ /**
1109
+ * Add system
1110
+ * @param S - system instance or system Class
1111
+ * @typeParam T - system which extends base `System` class
1112
+ * @typeparam U - type of system class
1113
+ */
1114
+ async addSystem(S, obj) {
1115
+ let system;
1116
+ if (S instanceof Function) {
1117
+ system = new S(obj);
1118
+ }
1119
+ else if (S instanceof System) {
1120
+ system = S;
1121
+ }
1122
+ else {
1123
+ console.warn('can only add System');
1124
+ return;
1125
+ }
1126
+ const hasTheSystem = this.systems.find(item => {
1127
+ return item.constructor === system.constructor;
1128
+ });
1129
+ if (hasTheSystem) {
1130
+ console.warn(`${systemClassName(system.constructor)} System has been added`);
1131
+ return;
1132
+ }
1133
+ system.game = this;
1134
+ if (system.init) {
1135
+ await Promise.resolve(system.init(system.__systemDefaultParams));
1136
+ }
1137
+ setSystemObserver(system, system.constructor);
1138
+ initObserver(system.constructor);
1139
+ try {
1140
+ system.awake && system.awake();
1141
+ }
1142
+ catch (e) {
1143
+ console.error(`${systemClassName(system.constructor)} awake error`, e);
1144
+ }
1145
+ this.systems.push(system);
1146
+ return system;
1147
+ }
1148
+ /**
1149
+ * Remove system from this game
1150
+ * @param system - one of system instance / system Class or system name
1151
+ */
1152
+ removeSystem(system) {
1153
+ if (!system)
1154
+ return;
1155
+ let index = -1;
1156
+ if (typeof system === 'string') {
1157
+ index = this.systems.findIndex(s => s.name === system);
1158
+ }
1159
+ else if (system instanceof Function) {
1160
+ index = this.systems.findIndex(s => s.constructor === system);
1161
+ }
1162
+ else if (system instanceof System) {
1163
+ index = this.systems.findIndex(s => s === system);
1164
+ }
1165
+ if (index > -1) {
1166
+ this.systems[index].destroy && this.systems[index].destroy();
1167
+ this.systems.splice(index, 1);
1168
+ }
1169
+ }
1170
+ /**
1171
+ * Get system
1172
+ * @param S - system class or system name
1173
+ * @returns system instance
1174
+ */
1175
+ getSystem(S) {
1176
+ return this.systems.find(system => {
1177
+ if (typeof S === 'string') {
1178
+ return system.name === S;
1179
+ }
1180
+ else {
1181
+ return system instanceof S;
1182
+ }
1183
+ });
1184
+ }
1185
+ /** Pause game */
1186
+ pause() {
1187
+ if (!this.playing)
1188
+ return;
1189
+ this.playing = false;
1190
+ this.ticker.pause();
1191
+ this.triggerPause();
1192
+ }
1193
+ /** Start game */
1194
+ start() {
1195
+ if (this.playing)
1196
+ return;
1197
+ this.playing = true;
1198
+ this.started = true;
1199
+ this.ticker.start();
1200
+ }
1201
+ /** Resume game */
1202
+ resume() {
1203
+ if (this.playing)
1204
+ return;
1205
+ this.playing = true;
1206
+ this.ticker.start();
1207
+ this.triggerResume();
1208
+ }
1209
+ /**
1210
+ * add main render method to ticker
1211
+ * @remarks
1212
+ * the method added to ticker will called in each requestAnimationFrame,
1213
+ * 1. call update method on all gameObject
1214
+ * 2. call lastUpdate method on all gameObject
1215
+ * 3. call update method on all system
1216
+ * 4. call lastUpdate method on all system
1217
+ */
1218
+ initTicker() {
1219
+ this.ticker.add(e => {
1220
+ this.scene && gameObjectLoop(e, this.gameObjects);
1221
+ for (const system of this.systems) {
1222
+ try {
1223
+ triggerStart(system);
1224
+ system.update && system.update(e);
1225
+ }
1226
+ catch (e) {
1227
+ console.error(`${systemClassName(system.constructor)} update error`, e);
1228
+ }
1229
+ }
1230
+ for (const system of this.systems) {
1231
+ try {
1232
+ system.lateUpdate && system.lateUpdate(e);
1233
+ }
1234
+ catch (e) {
1235
+ console.error(`${systemClassName(system.constructor)} lateUpdate error`, e);
1236
+ }
1237
+ }
1238
+ });
1239
+ }
1240
+ /** Call onResume method on all gameObject's, and then call onResume method on all system */
1241
+ triggerResume() {
1242
+ gameObjectResume(this.gameObjects);
1243
+ for (const system of this.systems) {
1244
+ try {
1245
+ system.onResume && system.onResume();
1246
+ }
1247
+ catch (e) {
1248
+ console.error(`${systemClassName(system.constructor)}, onResume error`, e);
1249
+ }
1250
+ }
1251
+ }
1252
+ /** Call onPause method on all gameObject */
1253
+ triggerPause() {
1254
+ gameObjectPause(this.gameObjects);
1255
+ for (const system of this.systems) {
1256
+ try {
1257
+ system.onPause && system.onPause();
1258
+ }
1259
+ catch (e) {
1260
+ console.error(`${systemClassName(system.constructor)}, onPause error`, e);
1261
+ }
1262
+ }
1263
+ }
1264
+ // TODO: call system destroy method
1265
+ /** remove all system on this game */
1266
+ destroySystems() {
1267
+ for (const system of [...this.systems]) {
1268
+ this.removeSystem(system);
1269
+ }
1270
+ this.systems.length = 0;
1271
+ }
1272
+ /** Destroy game instance */
1273
+ destroy() {
1274
+ this.removeAllListeners();
1275
+ this.pause();
1276
+ this.scene.destroy();
1277
+ this.destroySystems();
1278
+ this.ticker = null;
1279
+ this.scene = null;
1280
+ this.canvas = null;
1281
+ this.multiScenes = null;
1282
+ }
1283
+ loadScene({ scene, mode = exports.LOAD_SCENE_MODE.SINGLE, params = {} }) {
1284
+ if (!scene) {
1285
+ return;
1286
+ }
1287
+ switch (mode) {
1288
+ case exports.LOAD_SCENE_MODE.SINGLE:
1289
+ this.scene = scene;
1290
+ break;
1291
+ case exports.LOAD_SCENE_MODE.MULTI_CANVAS:
1292
+ this.multiScenes.push(scene);
1293
+ break;
1294
+ }
1295
+ this.emit('sceneChanged', { scene, mode, params });
1296
+ }
1297
+ }
1298
+
1299
+ /**
1300
+ * Collect property which react in Editor tooling
1301
+ * @param target - component instance
1302
+ * @param propertyKey - property name
1303
+ */
1304
+ function IDEProp(target, propertyKey) {
1305
+ if (!target.constructor.IDEProps) {
1306
+ target.constructor.IDEProps = [];
1307
+ }
1308
+ target.constructor.IDEProps.push(propertyKey);
1309
+ }
1310
+
1311
+ /**
1312
+ * Normailize system observer info
1313
+ * @param obj - system observer info
1314
+ */
1315
+ function componentObserver(observerInfo = {}) {
1316
+ return function (constructor) {
1317
+ if (!constructor.observerInfo) {
1318
+ for (const key in observerInfo) {
1319
+ for (const index in observerInfo[key]) {
1320
+ if (typeof observerInfo[key][index] === 'string') {
1321
+ observerInfo[key][index] = [observerInfo[key][index]];
1322
+ }
1323
+ let observerProp;
1324
+ if (Array.isArray(observerInfo[key][index])) {
1325
+ observerProp = {
1326
+ prop: observerInfo[key][index],
1327
+ deep: false,
1328
+ };
1329
+ observerInfo[key][index] = observerProp;
1330
+ }
1331
+ observerProp = observerInfo[key][index];
1332
+ if (typeof observerProp.prop === 'string') {
1333
+ observerProp.prop = [observerProp.prop];
1334
+ }
1335
+ }
1336
+ }
1337
+ constructor.observerInfo = observerInfo;
1338
+ }
1339
+ };
1340
+ }
1341
+
1342
+ /** Load lifecycle events (decoupled from Resource/Progress to avoid barrel import cycles). */
1343
+ exports.LOAD_EVENT = void 0;
1344
+ (function (LOAD_EVENT) {
1345
+ LOAD_EVENT["START"] = "start";
1346
+ LOAD_EVENT["PROGRESS"] = "progress";
1347
+ LOAD_EVENT["LOADED"] = "loaded";
1348
+ LOAD_EVENT["COMPLETE"] = "complete";
1349
+ LOAD_EVENT["ERROR"] = "error";
1350
+ })(exports.LOAD_EVENT || (exports.LOAD_EVENT = {}));
1351
+
1352
+ class Progress extends EventEmitter__default.default {
1353
+ constructor({ resource, resourceTotal }) {
1354
+ super();
1355
+ this.progress = 0;
1356
+ this.resourceTotal = 0;
1357
+ this.resourceLoadedCount = 0;
1358
+ this.resource = resource;
1359
+ this.resourceTotal = resourceTotal;
1360
+ if (resourceTotal === 0) {
1361
+ this.resource.emit(exports.LOAD_EVENT.COMPLETE, this);
1362
+ }
1363
+ }
1364
+ onStart() {
1365
+ this.resource.emit(exports.LOAD_EVENT.START, this);
1366
+ }
1367
+ onProgress(param) {
1368
+ this.resourceLoadedCount++;
1369
+ this.progress = Math.floor((this.resourceLoadedCount / this.resourceTotal) * 100) / 100;
1370
+ if (param.success) {
1371
+ this.resource.emit(exports.LOAD_EVENT.LOADED, this, param);
1372
+ }
1373
+ else {
1374
+ this.resource.emit(exports.LOAD_EVENT.ERROR, this, param);
1375
+ }
1376
+ this.resource.emit(exports.LOAD_EVENT.PROGRESS, this, param);
1377
+ if (this.resourceLoadedCount === this.resourceTotal) {
1378
+ this.resource.emit(exports.LOAD_EVENT.COMPLETE, this);
1379
+ }
1380
+ }
1381
+ }
1382
+
1383
+ const resourceLoader = {
1384
+ AbstractLoadStrategy: resourceLoader$1.AbstractLoadStrategy,
1385
+ AudioLoadStrategy: resourceLoader$1.AudioLoadStrategy,
1386
+ ImageLoadStrategy: resourceLoader$1.ImageLoadStrategy,
1387
+ XhrResponseType: resourceLoader$1.XhrResponseType,
1388
+ MediaElementLoadStrategy: resourceLoader$1.MediaElementLoadStrategy,
1389
+ VideoLoadStrategy: resourceLoader$1.VideoLoadStrategy,
1390
+ XhrLoadStrategy: resourceLoader$1.XhrLoadStrategy,
1391
+ Loader: resourceLoader$1.Loader,
1392
+ Resource: resourceLoader$1.Resource,
1393
+ ResourceType: resourceLoader$1.ResourceType,
1394
+ ResourceState: resourceLoader$1.ResourceState
1395
+ };
1396
+
1397
+ /** Resource type */
1398
+ exports.RESOURCE_TYPE = void 0;
1399
+ (function (RESOURCE_TYPE) {
1400
+ RESOURCE_TYPE["IMAGE"] = "IMAGE";
1401
+ RESOURCE_TYPE["SPRITE"] = "SPRITE";
1402
+ RESOURCE_TYPE["SPRITE_ANIMATION"] = "SPRITE_ANIMATION";
1403
+ RESOURCE_TYPE["AUDIO"] = "AUDIO";
1404
+ RESOURCE_TYPE["VIDEO"] = "VIDEO";
1405
+ })(exports.RESOURCE_TYPE || (exports.RESOURCE_TYPE = {}));
1406
+ resourceLoader$1.XhrLoadStrategy.setExtensionXhrType('json', resourceLoader$1.XhrResponseType.Json);
1407
+ resourceLoader$1.XhrLoadStrategy.setExtensionXhrType('tex', resourceLoader$1.XhrResponseType.Json);
1408
+ resourceLoader$1.XhrLoadStrategy.setExtensionXhrType('ske', resourceLoader$1.XhrResponseType.Json);
1409
+ resourceLoader$1.XhrLoadStrategy.setExtensionXhrType('mp3', resourceLoader$1.XhrResponseType.Buffer);
1410
+ resourceLoader$1.XhrLoadStrategy.setExtensionXhrType('wav', resourceLoader$1.XhrResponseType.Buffer);
1411
+ resourceLoader$1.XhrLoadStrategy.setExtensionXhrType('aac', resourceLoader$1.XhrResponseType.Buffer);
1412
+ resourceLoader$1.XhrLoadStrategy.setExtensionXhrType('ogg', resourceLoader$1.XhrResponseType.Buffer);
1413
+ const RESOURCE_TYPE_STRATEGY = {
1414
+ png: resourceLoader$1.ImageLoadStrategy,
1415
+ jpg: resourceLoader$1.ImageLoadStrategy,
1416
+ jpeg: resourceLoader$1.ImageLoadStrategy,
1417
+ webp: resourceLoader$1.ImageLoadStrategy,
1418
+ json: resourceLoader$1.XhrLoadStrategy,
1419
+ tex: resourceLoader$1.XhrLoadStrategy,
1420
+ ske: resourceLoader$1.XhrLoadStrategy,
1421
+ audio: resourceLoader$1.XhrLoadStrategy,
1422
+ video: resourceLoader$1.VideoLoadStrategy,
1423
+ };
1424
+ /**
1425
+ * Resource manager
1426
+ * @public
1427
+ */
1428
+ class Resource extends EventEmitter__default.default {
1429
+ constructor(options) {
1430
+ super();
1431
+ // TODO: specify timeout in config to overwrite it
1432
+ /** load resource timeout */
1433
+ this.timeout = 6000;
1434
+ this.preProcessResourceHandlers = [];
1435
+ /** Resource cache */
1436
+ this.resourcesMap = {};
1437
+ /** Collection of make resource instance function */
1438
+ this.makeInstanceFunctions = {};
1439
+ /** Collection of destroy resource instance function */
1440
+ this.destroyInstanceFunctions = {};
1441
+ /** Resource load promise */
1442
+ this.promiseMap = {};
1443
+ this.loaders = [];
1444
+ if (options && typeof options.timeout === 'number') {
1445
+ this.timeout = options.timeout;
1446
+ }
1447
+ }
1448
+ /** Add resource configs and then preload */
1449
+ loadConfig(resources) {
1450
+ this.addResource(resources);
1451
+ this.preload();
1452
+ }
1453
+ /** Add single resource config and then preload */
1454
+ loadSingle(resource) {
1455
+ this.addResource([resource]);
1456
+ return this.getResource(resource.name);
1457
+ }
1458
+ /** Add resource configs */
1459
+ addResource(resources) {
1460
+ if (!resources || resources.length < 1) {
1461
+ console.warn('no resources');
1462
+ return;
1463
+ }
1464
+ for (const res of resources) {
1465
+ if (this.resourcesMap[res.name]) {
1466
+ console.warn(res.name + ' was already added');
1467
+ continue;
1468
+ }
1469
+ this.resourcesMap[res.name] = res;
1470
+ this.resourcesMap[res.name].data = {};
1471
+ }
1472
+ }
1473
+ /** dd resource preprocesser*/
1474
+ addPreProcessResourceHandler(handler) {
1475
+ this.preProcessResourceHandlers.push(handler);
1476
+ }
1477
+ removePreProcessResourceHandler(handler) {
1478
+ this.preProcessResourceHandlers.splice(this.preProcessResourceHandlers.indexOf(handler), 1);
1479
+ }
1480
+ /** Start preload */
1481
+ preload() {
1482
+ const names = [];
1483
+ for (const key in this.resourcesMap) {
1484
+ const resource = this.resourcesMap[key];
1485
+ if (resource.preload && !resource.complete && !this.promiseMap[key]) {
1486
+ names.push(resource.name);
1487
+ }
1488
+ }
1489
+ this.progress = new Progress({
1490
+ resource: this,
1491
+ resourceTotal: names.length,
1492
+ });
1493
+ this.loadResource({ names, preload: true });
1494
+ }
1495
+ /** Get resource by name */
1496
+ async getResource(name) {
1497
+ this.loadResource({ names: [name] });
1498
+ return this.promiseMap[name] || Promise.resolve({});
1499
+ }
1500
+ /** Make resource instance by resource type */
1501
+ async instance(name) {
1502
+ const res = this.resourcesMap[name];
1503
+ return this.makeInstanceFunctions[res.type] && (await this.makeInstanceFunctions[res.type](res));
1504
+ }
1505
+ /** destory this resource manager */
1506
+ async destroy(name) {
1507
+ await this._destroy(name);
1508
+ }
1509
+ async _destroy(name, loadError = false) {
1510
+ const resource = this.resourcesMap[name];
1511
+ if (!resource)
1512
+ return;
1513
+ if (!loadError) {
1514
+ try {
1515
+ if (this.destroyInstanceFunctions[resource.type]) {
1516
+ await this.destroyInstanceFunctions[resource.type](resource);
1517
+ }
1518
+ }
1519
+ catch (e) {
1520
+ console.warn(`destroy resource ${resource.name} error with '${e.message}'`);
1521
+ }
1522
+ }
1523
+ delete this.promiseMap[name];
1524
+ resource.data = {};
1525
+ resource.complete = false;
1526
+ resource.instance = undefined;
1527
+ }
1528
+ /**
1529
+ * Register a custom resource type string on {@link RESOURCE_TYPE}.
1530
+ * For TypeScript, extend `RESOURCE_TYPE` via `declare module "@combos-fun/engine"` in your app’s ambient `.d.ts`.
1531
+ * Call this before {@link registerInstance} / {@link registerDestroy} for that type.
1532
+ */
1533
+ registerResourceType(type, value = type) {
1534
+ if (exports.RESOURCE_TYPE[type]) {
1535
+ throw new Error(`The type ${type} already exists in RESOURCE_TYPE`);
1536
+ }
1537
+ exports.RESOURCE_TYPE[type] = value;
1538
+ }
1539
+ /** Add resource instance function */
1540
+ registerInstance(type, callback) {
1541
+ this.makeInstanceFunctions[type] = callback;
1542
+ }
1543
+ /** Add resource destroy function */
1544
+ registerDestroy(type, callback) {
1545
+ this.destroyInstanceFunctions[type] = callback;
1546
+ }
1547
+ loadResource({ names = [], preload = false }) {
1548
+ const unLoadNames = names.filter(name => !this.promiseMap[name] && this.resourcesMap[name]);
1549
+ if (!unLoadNames.length)
1550
+ return;
1551
+ const resolves = {};
1552
+ const loader = this.getLoader(preload);
1553
+ unLoadNames.forEach(name => {
1554
+ this.promiseMap[name] = new Promise(r => (resolves[name] = r));
1555
+ const res = this.resourcesMap[name];
1556
+ for (const handler of this.preProcessResourceHandlers) {
1557
+ handler(res);
1558
+ }
1559
+ for (const key in res.src) {
1560
+ const resourceType = res.src[key].type;
1561
+ if (resourceType === 'data') {
1562
+ res.data[key] = res.src[key].data;
1563
+ this.doComplete(name, resolves[name], preload);
1564
+ }
1565
+ else {
1566
+ loader.add({
1567
+ url: res.src[key].url,
1568
+ name: `${res.name}_${key}`,
1569
+ strategy: RESOURCE_TYPE_STRATEGY[resourceType],
1570
+ metadata: {
1571
+ key,
1572
+ name: res.name,
1573
+ resolves,
1574
+ },
1575
+ });
1576
+ }
1577
+ }
1578
+ });
1579
+ loader.load();
1580
+ }
1581
+ async doComplete(name, resolve, preload = false) {
1582
+ const res = this.resourcesMap[name];
1583
+ const param = {
1584
+ name,
1585
+ resource: this.resourcesMap[name],
1586
+ success: true,
1587
+ };
1588
+ if (this.checkAllLoaded(name)) {
1589
+ try {
1590
+ res.instance = await this.instance(name);
1591
+ res.complete = true;
1592
+ if (preload) {
1593
+ this.progress.onProgress(param);
1594
+ }
1595
+ resolve(res);
1596
+ }
1597
+ catch (err) {
1598
+ console.error(err);
1599
+ res.complete = false;
1600
+ if (preload) {
1601
+ param.errMsg = err.message;
1602
+ param.success = false;
1603
+ this.progress.onProgress(param);
1604
+ }
1605
+ resolve({});
1606
+ }
1607
+ }
1608
+ }
1609
+ checkAllLoaded(name) {
1610
+ const res = this.resourcesMap[name];
1611
+ return Array.from(Object.keys(res.src)).every(resourceKey => res.data[resourceKey]);
1612
+ }
1613
+ getLoader(preload = false) {
1614
+ let loader = this.loaders.find(({ loading }) => !loading);
1615
+ if (!loader) {
1616
+ loader = new resourceLoader$1.Loader();
1617
+ this.loaders.push(loader);
1618
+ }
1619
+ if (preload) {
1620
+ loader.onStart.once(() => {
1621
+ this.progress.onStart();
1622
+ });
1623
+ }
1624
+ loader.onLoad.add((_, resource) => {
1625
+ this.onLoad({ preload, resource });
1626
+ });
1627
+ loader.onError.add((errMsg, _loader, resource) => {
1628
+ this.onError({ errMsg, resource, preload });
1629
+ });
1630
+ loader.onComplete.once(() => {
1631
+ loader.onLoad.detachAll();
1632
+ loader.onError.detachAll();
1633
+ loader.reset();
1634
+ });
1635
+ return loader;
1636
+ }
1637
+ async onLoad({ preload = false, resource }) {
1638
+ const { metadata: { key, name, resolves }, data, } = resource;
1639
+ const res = this.resourcesMap[name];
1640
+ res.data[key] = data;
1641
+ this.doComplete(name, resolves[name], preload);
1642
+ }
1643
+ async onError({ errMsg, preload = false, resource }) {
1644
+ const { metadata: { name, resolves }, } = resource;
1645
+ this._destroy(name, true);
1646
+ resolves[name]({});
1647
+ if (preload) {
1648
+ const param = {
1649
+ name,
1650
+ resource: this.resourcesMap[name],
1651
+ success: false,
1652
+ errMsg,
1653
+ };
1654
+ this.progress.onProgress(param);
1655
+ }
1656
+ }
1657
+ }
1658
+ /** Resource manager single instance */
1659
+ const resource = new Resource();
1660
+
1661
+ /** Decorators util */
1662
+ const decorators = {
1663
+ IDEProp,
1664
+ componentObserver,
1665
+ };
1666
+ const version = '__VERSION__';
1667
+ console.log(`@combos-fun/engine version: ${version}`);
1668
+
1669
+ exports.Component = Component;
1670
+ exports.Game = Game;
1671
+ exports.GameObject = GameObject;
1672
+ exports.IDEProp = IDEProp;
1673
+ exports.RESOURCE_TYPE_STRATEGY = RESOURCE_TYPE_STRATEGY;
1674
+ exports.Scene = Scene;
1675
+ exports.System = System;
1676
+ exports.Transform = Transform;
1677
+ exports.componentObserver = componentObserver;
1678
+ exports.decorators = decorators;
1679
+ exports.resource = resource;
1680
+ exports.resourceLoader = resourceLoader;
1681
+ exports.version = version;
1682
+ //# sourceMappingURL=engine.cjs.js.map