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