forked from playcanvas/engine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomponent.js
More file actions
656 lines (536 loc) · 23.4 KB
/
component.js
File metadata and controls
656 lines (536 loc) · 23.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
Object.assign(pc, function () {
/**
* @component
* @name pc.ScriptComponent
* @class The ScriptComponent allows you to extend the functionality of an Entity by attaching your own Script Types defined in JavaScript files
* to be executed with access to the Entity. For more details on scripting see <a href="//developer.playcanvas.com/user-manual/scripting/">Scripting</a>.
* @param {pc.ScriptComponentSystem} system The ComponentSystem that created this Component
* @param {pc.Entity} entity The Entity that this Component is attached to.
* @extends pc.Component
* @property {ScriptType[]} scripts An array of all script instances attached to an entity. This Array shall not be modified by developer.
*/
var ScriptComponent = function ScriptComponent(system, entity) {
pc.Component.call(this, system, entity);
this._scripts = [];
this._scriptsIndex = {};
this._destroyedScripts = [];
this._destroyed = false;
this._scriptsData = null;
this._oldState = true;
this._beingEnabled = false;
this._isLoopingThroughScripts = false;
this.on('set_enabled', this._onSetEnabled, this);
};
ScriptComponent.prototype = Object.create(pc.Component.prototype);
ScriptComponent.prototype.constructor = ScriptComponent;
ScriptComponent.scriptMethods = {
initialize: 'initialize',
postInitialize: 'postInitialize',
update: 'update',
postUpdate: 'postUpdate',
swap: 'swap'
};
/**
* @event
* @name pc.ScriptComponent#enable
* @description Fired when Component becomes enabled
* Note: this event does not take in account entity or any of its parent enabled state
* @example
* entity.script.on('enable', function () {
* // component is enabled
* });
*/
/**
* @event
* @name pc.ScriptComponent#disable
* @description Fired when Component becomes disabled
* Note: this event does not take in account entity or any of its parent enabled state
* @example
* entity.script.on('disable', function () {
* // component is disabled
* });
*/
/**
* @event
* @name pc.ScriptComponent#state
* @description Fired when Component changes state to enabled or disabled
* Note: this event does not take in account entity or any of its parent enabled state
* @param {Boolean} enabled True if now enabled, False if disabled
* @example
* entity.script.on('state', function (enabled) {
* // component changed state
* });
*/
/**
* @event
* @name pc.ScriptComponent#remove
* @description Fired when Component is removed from entity
* @example
* entity.script.on('remove', function () {
* // entity has no more script component
* });
*/
/**
* @event
* @name pc.ScriptComponent#create
* @description Fired when a script instance is created and attached to component
* @param {String} name The name of the Script Type
* @param {ScriptType} scriptInstance The instance of the {@link ScriptType} that has been created
* @example
* entity.script.on('create', function (name, scriptInstance) {
* // new script instance added to component
* });
*/
/**
* @event
* @name pc.ScriptComponent#create:[name]
* @description Fired when a script instance is created and attached to component
* @param {ScriptType} scriptInstance The instance of the {@link ScriptType} that has been created
* @example
* entity.script.on('create:playerController', function (scriptInstance) {
* // new script instance 'playerController' is added to component
* });
*/
/**
* @event
* @name pc.ScriptComponent#destroy
* @description Fired when a script instance is destroyed and removed from component
* @param {String} name The name of the Script Type
* @param {ScriptType} scriptInstance The instance of the {@link ScriptType} that has been destroyed
* @example
* entity.script.on('destroy', function (name, scriptInstance) {
* // script instance has been destroyed and removed from component
* });
*/
/**
* @event
* @name pc.ScriptComponent#destroy:[name]
* @description Fired when a script instance is destroyed and removed from component
* @param {ScriptType} scriptInstance The instance of the {@link ScriptType} that has been destroyed
* @example
* entity.script.on('destroy:playerController', function (scriptInstance) {
* // script instance 'playerController' has been destroyed and removed from component
* });
*/
/**
* @event
* @name pc.ScriptComponent#move
* @description Fired when a script instance is moved in component
* @param {String} name The name of the Script Type
* @param {ScriptType} scriptInstance The instance of the {@link ScriptType} that has been moved
* @param {Number} ind New position index
* @param {Number} indOld Old position index
* @example
* entity.script.on('move', function (name, scriptInstance, ind, indOld) {
* // script instance has been moved in component
* });
*/
/**
* @event
* @name pc.ScriptComponent#move:[name]
* @description Fired when a script instance is moved in component
* @param {ScriptType} scriptInstance The instance of the {@link ScriptType} that has been moved
* @param {Number} ind New position index
* @param {Number} indOld Old position index
* @example
* entity.script.on('move:playerController', function (scriptInstance, ind, indOld) {
* // script instance 'playerController' has been moved in component
* });
*/
/**
* @event
* @name pc.ScriptComponent#error
* @description Fired when a script instance had an exception
* @param {ScriptType} scriptInstance The instance of the {@link ScriptType} that raised the exception
* @param {Error} err Native JS Error object with details of an error
* @param {String} method The method of the script instance that the exception originated from.
* @example
* entity.script.on('error', function (scriptInstance, err, method) {
* // script instance caught an exception
* });
*/
Object.assign(ScriptComponent.prototype, {
onEnable: function () {
pc.Component.prototype.onEnable.call(this);
this._beingEnabled = true;
this._checkState();
if (!this.entity._beingEnabled) {
this.onPostStateChange();
}
this._beingEnabled = false;
},
onDisable: function () {
pc.Component.prototype.onDisable.call(this);
this._checkState();
},
onPostStateChange: function () {
var script;
var wasLooping = this._beginLooping();
for (var i = 0, len = this.scripts.length; i < len; i++) {
script = this.scripts[i];
if (script._initialized && !script._postInitialized && script.enabled) {
script._postInitialized = true;
if (script.postInitialize)
this._scriptMethod(script, ScriptComponent.scriptMethods.postInitialize);
}
}
this._endLooping(wasLooping);
},
// Sets isLoopingThroughScripts to false and returns
// its previous value
_beginLooping: function () {
var looping = this._isLoopingThroughScripts;
this._isLoopingThroughScripts = true;
return looping;
},
// Restores isLoopingThroughScripts to the specified parameter
// If all loops are over then remove destroyed scripts form the _scripts array
_endLooping: function (wasLoopingBefore) {
this._isLoopingThroughScripts = wasLoopingBefore;
if (!this._isLoopingThroughScripts) {
this._removeDestroyedScripts();
}
},
// We also need this handler because it is fired
// when value === old instead of onEnable and onDisable
// which are only fired when value !== old
_onSetEnabled: function (prop, old, value) {
this._beingEnabled = true;
this._checkState();
this._beingEnabled = false;
},
_checkState: function () {
var state = this.enabled && this.entity.enabled;
if (state === this._oldState)
return;
this._oldState = state;
this.fire(state ? 'enable' : 'disable');
this.fire('state', state);
var wasLooping = this._beginLooping();
var script;
for (var i = 0, len = this.scripts.length; i < len; i++) {
script = this.scripts[i];
script.enabled = script._enabled;
}
this._endLooping(wasLooping);
},
_onBeforeRemove: function () {
this.fire('remove');
var wasLooping = this._beginLooping();
// destroy all scripts
for (var i = 0; i < this.scripts.length; i++) {
var script = this.scripts[i];
if (!script) continue;
this.destroy(script.__scriptType.__name);
}
this._endLooping(wasLooping);
},
_removeDestroyedScripts: function () {
var len = this._destroyedScripts.length;
if (!len) return;
for (var i = 0; i < len; i++) {
var idx = this._scripts.indexOf(this._destroyedScripts[i]);
if (idx >= 0) {
this._scripts.splice(idx, 1);
}
}
this._destroyedScripts.length = 0;
},
_onInitializeAttributes: function () {
for (var i = 0, len = this.scripts.length; i < len; i++)
this.scripts[i].__initializeAttributes();
},
_scriptMethod: function (script, method, arg) {
try {
script[method](arg);
} catch (ex) {
// disable script if it fails to call method
script.enabled = false;
if (!script._callbacks || !script._callbacks.error) {
console.warn('unhandled exception while calling "' + method + '" for "' + script.__scriptType.__name + '" script: ', ex);
console.error(ex);
}
script.fire('error', ex, method);
this.fire('error', script, ex, method);
}
},
_onInitialize: function () {
var script, scripts = this._scripts;
var wasLooping = this._beginLooping();
for (var i = 0, len = scripts.length; i < len; i++) {
script = scripts[i];
if (!script._initialized && script.enabled) {
script._initialized = true;
if (script.initialize)
this._scriptMethod(script, ScriptComponent.scriptMethods.initialize);
}
}
this._endLooping(wasLooping);
},
_onPostInitialize: function () {
this.onPostStateChange();
},
_onUpdate: function (dt) {
var script, scripts = this._scripts;
var wasLooping = this._beginLooping();
for (var i = 0, len = scripts.length; i < len; i++) {
script = scripts[i];
if (script.update && script.enabled)
this._scriptMethod(script, ScriptComponent.scriptMethods.update, dt);
}
this._endLooping(wasLooping);
},
_onPostUpdate: function (dt) {
var i;
var len;
var wasLooping = this._beginLooping();
var script, scripts = this._scripts;
for (i = 0, len = scripts.length; i < len; i++) {
script = scripts[i];
if (script.postUpdate && script.enabled)
this._scriptMethod(script, ScriptComponent.scriptMethods.postUpdate, dt);
}
this._endLooping(wasLooping);
},
/**
* @function
* @name pc.ScriptComponent#has
* @description Detect if script is attached to an entity using name of {@link ScriptType}.
* @param {String} name The name of the Script Type
* @returns {Boolean} If script is attached to an entity
* @example
* if (entity.script.has('playerController')) {
* // entity has script
* }
*/
has: function (name) {
var scriptType = name;
// shorthand using script name
if (typeof scriptType === 'string')
scriptType = this.system.app.scripts.get(scriptType);
return !!this._scriptsIndex[scriptType.__name];
},
/**
* @function
* @name pc.ScriptComponent#create
* @description Create a script instance using name of a {@link ScriptType} and attach to an entity script component.
* @param {String} name The name of the Script Type
* @param {Object} [args] Object with arguments for a script
* @param {Boolean} [args.enabled] if script instance is enabled after creation
* @param {Object} [args.attributes] Object with values for attributes, where key is name of an attribute
* @returns {ScriptType} Returns an instance of a {@link ScriptType} if successfully attached to an entity,
* or null if it failed because a script with a same name has already been added
* or if the {@link ScriptType} cannot be found by name in the {@link pc.ScriptRegistry}.
* @example
* entity.script.create('playerController', {
* attributes: {
* speed: 4
* }
* });
*/
create: function (name, args) {
var self = this;
args = args || { };
var scriptType = name;
var scriptName = name;
// shorthand using script name
if (typeof scriptType === 'string') {
scriptType = this.system.app.scripts.get(scriptType);
} else if (scriptType) {
scriptName = scriptType.__name;
}
if (scriptType) {
if (!this._scriptsIndex[scriptType.__name] || !this._scriptsIndex[scriptType.__name].instance) {
// create script instance
var scriptInstance = new scriptType({
app: this.system.app,
entity: this.entity,
enabled: args.hasOwnProperty('enabled') ? args.enabled : true,
attributes: args.attributes || null
});
var ind = -1;
if (typeof args.ind === 'number' && args.ind !== -1 && this._scripts.length > args.ind)
ind = args.ind;
if (ind === -1) {
this._scripts.push(scriptInstance);
} else {
this._scripts.splice(ind, 0, scriptInstance);
}
this._scriptsIndex[scriptType.__name] = {
instance: scriptInstance,
onSwap: function () {
self.swap(scriptType.__name);
}
};
this[scriptType.__name] = scriptInstance;
if (!args.preloading)
scriptInstance.__initializeAttributes();
this.fire('create', scriptType.__name, scriptInstance);
this.fire('create:' + scriptType.__name, scriptInstance);
this.system.app.scripts.on('swap:' + scriptType.__name, this._scriptsIndex[scriptType.__name].onSwap);
if (!args.preloading) {
if (scriptInstance.enabled && !scriptInstance._initialized) {
scriptInstance._initialized = true;
if (scriptInstance.initialize)
this._scriptMethod(scriptInstance, ScriptComponent.scriptMethods.initialize);
}
if (scriptInstance.enabled && !scriptInstance._postInitialized) {
scriptInstance._postInitialized = true;
if (scriptInstance.postInitialize)
this._scriptMethod(scriptInstance, ScriptComponent.scriptMethods.postInitialize);
}
}
return scriptInstance;
}
console.warn('script \'' + scriptName + '\' is already added to entity \'' + this.entity.name + '\'');
} else {
this._scriptsIndex[scriptName] = {
awaiting: true,
ind: this._scripts.length
};
console.warn('script \'' + scriptName + '\' is not found, awaiting it to be added to registry');
}
return null;
},
/**
* @function
* @name pc.ScriptComponent#destroy
* @description Destroy the script instance that is attached to an entity.
* @param {String} name The name of the Script Type
* @returns {Boolean} If it was successfully destroyed
* @example
* entity.script.destroy('playerController');
*/
destroy: function (name) {
var scriptName = name;
var scriptType = name;
// shorthand using script name
if (typeof scriptType === 'string') {
scriptType = this.system.app.scripts.get(scriptType);
if (scriptType)
scriptName = scriptType.__name;
}
var scriptData = this._scriptsIndex[scriptName];
delete this._scriptsIndex[scriptName];
if (!scriptData) return false;
if (scriptData.instance && !scriptData.instance._destroyed) {
scriptData.instance.enabled = false;
scriptData.instance._destroyed = true;
// if we are not currently looping through our scripts
// then it's safe to remove the script
if (!this._isLoopingThroughScripts) {
var ind = this._scripts.indexOf(scriptData.instance);
this._scripts.splice(ind, 1);
} else {
// otherwise push the script in _destroyedScripts and
// remove it from _scripts when the loop is over
this._destroyedScripts.push(scriptData.instance);
}
}
// remove swap event
this.system.app.scripts.off('swap:' + scriptName, scriptData.onSwap);
delete this[scriptName];
this.fire('destroy', scriptName, scriptData.instance || null);
this.fire('destroy:' + scriptName, scriptData.instance || null);
if (scriptData.instance)
scriptData.instance.fire('destroy');
return true;
},
swap: function (script) {
var scriptType = script;
// shorthand using script name
if (typeof scriptType === 'string')
scriptType = this.system.app.scripts.get(scriptType);
var old = this._scriptsIndex[scriptType.__name];
if (!old || !old.instance) return false;
var scriptInstanceOld = old.instance;
var ind = this._scripts.indexOf(scriptInstanceOld);
var scriptInstance = new scriptType({
app: this.system.app,
entity: this.entity,
enabled: scriptInstanceOld.enabled,
attributes: scriptInstanceOld.__attributes
});
if (!scriptInstance.swap)
return false;
scriptInstance.__initializeAttributes();
// add to component
this._scripts[ind] = scriptInstance;
this._scriptsIndex[scriptType.__name].instance = scriptInstance;
this[scriptType.__name] = scriptInstance;
this._scriptMethod(scriptInstance, ScriptComponent.scriptMethods.swap, scriptInstanceOld);
this.fire('swap', scriptType.__name, scriptInstance);
this.fire('swap:' + scriptType.__name, scriptInstance);
return true;
},
/**
* @function
* @name pc.ScriptComponent#move
* @description Move script instance to different position to alter update order of scripts within entity.
* @param {String} name The name of the Script Type
* @param {Number} ind New position index
* @returns {Boolean} If it was successfully moved
* @example
* entity.script.move('playerController', 0);
*/
move: function (name, ind) {
if (ind >= this._scripts.length)
return false;
var scriptName = name;
if (typeof scriptName !== 'string')
scriptName = name.__name;
var scriptData = this._scriptsIndex[scriptName];
if (!scriptData || !scriptData.instance)
return false;
var indOld = this._scripts.indexOf(scriptData.instance);
if (indOld === -1 || indOld === ind)
return false;
// move script to another position
this._scripts.splice(ind, 0, this._scripts.splice(indOld, 1)[0]);
this.fire('move', scriptName, scriptData.instance, ind, indOld);
this.fire('move:' + scriptName, scriptData.instance, ind, indOld);
return true;
}
});
Object.defineProperty(ScriptComponent.prototype, 'scripts', {
get: function () {
return this._scripts;
},
set: function (value) {
this._scriptsData = value;
for (var key in value) {
if (!value.hasOwnProperty(key))
continue;
var script = this._scriptsIndex[key];
if (script) {
// existing script
// enabled
if (typeof value[key].enabled === 'boolean')
script.enabled = !!value[key].enabled;
// attributes
if (typeof value[key].attributes === 'object') {
for (var attr in value[key].attributes) {
if (pc.createScript.reservedAttributes[attr])
continue;
if (!script.__attributes.hasOwnProperty(attr)) {
// new attribute
var scriptType = this.system.app.scripts.get(key);
if (scriptType)
scriptType.attributes.add(attr, { });
}
// update attribute
script[attr] = value[key].attributes[attr];
}
}
} else {
// TODO scripts2
// new script
console.log(this.order);
}
}
}
});
return {
ScriptComponent: ScriptComponent
};
}());