forked from playcanvas/engine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript_component.js
More file actions
282 lines (243 loc) · 11.9 KB
/
Copy pathscript_component.js
File metadata and controls
282 lines (243 loc) · 11.9 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
pc.extend(pc, function () {
/**
* @component
* @name pc.ScriptComponent
* @class The ScriptComponent allows you to extend the functionality of an Entity by attaching your own 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 {Boolean} enabled Enables or disables the Component. If the Component is disabled then the following methods will not be called on the script instances:
* <ul>
* <li>initialize</li>
* <li>postInitialize</li>
* <li>update</li>
* <li>fixedUpdate</li>
* <li>postUpdate</li>
* </ul>
* @property {Array} scripts An array of all the scripts to load. Each script object has this format:
* {url: 'url.js', name: 'url', 'attributes': [attribute1, attribute2, ...]}
*/
var ScriptComponent = function ScriptComponent(system, entity) {
this.on("set_scripts", this.onSetScripts, this);
};
ScriptComponent = pc.inherits(ScriptComponent, pc.Component);
pc.extend(ScriptComponent.prototype, {
/**
* @private
* @function
* @name pc.ScriptComponent#send
* @description Send a message to a script attached to the entity.
* Sending a message to a script is similar to calling a method on a Script Object, except that the message will not fail if the method isn't present.
* @param {String} name The name of the script to send the message to
* @param {String} functionName The name of the function to call on the script
* @returns The result of the function call
* @example
* // Call doDamage(10) on the script object called 'enemy' attached to entity.
* entity.script.send('enemy', 'doDamage', 10);
*/
send: function (name, functionName) {
console.warn("DEPRECATED: ScriptComponent.send() is deprecated and will be removed soon. Please use: http://developer.playcanvas.com/user-manual/scripting/communication/")
var args = pc.makeArray(arguments).slice(2);
var instances = this.entity.script.instances;
var fn;
if(instances && instances[name]) {
fn = instances[name].instance[functionName];
if (fn) {
return fn.apply(instances[name].instance, args);
}
}
},
onEnable: function () {
ScriptComponent._super.onEnable.call(this);
// if the scripts of the component have been loaded
// then call the appropriate methods on the component
if (this.data.areScriptsLoaded && !this.system.preloading) {
if (!this.data.initialized) {
this.system._initializeScriptComponent(this);
} else {
this.system._enableScriptComponent(this);
}
if (!this.data.postInitialized) {
this.system._postInitializeScriptComponent(this);
}
}
},
onDisable: function () {
ScriptComponent._super.onDisable.call(this);
this.system._disableScriptComponent(this);
},
onSetScripts: function(name, oldValue, newValue) {
if (!this.system._inTools || this.runInTools) {
// if we only need to update script attributes then update them and return
if (this._updateScriptAttributes(oldValue, newValue)) {
return;
}
// disable the script first
if (this.enabled) {
this.system._disableScriptComponent(this);
}
this.system._destroyScriptComponent(this);
this.data.areScriptsLoaded = false;
// get the urls
var scripts = newValue;
var urls = scripts.map(function (s) {
return s.url;
});
// try to load the scripts synchronously first
if (this._loadFromCache(urls)) {
return;
}
// not all scripts are in the cache so load them asynchronously
this._loadScripts(urls);
}
},
// Check if only script attributes need updating in which
// case just update the attributes and return otherwise return false
_updateScriptAttributes: function (oldValue, newValue) {
var onlyUpdateAttributes = true;
if (oldValue.length !== newValue.length) {
onlyUpdateAttributes = false;
} else {
var i; len = newValue.length;
for (i=0; i<len; i++) {
if (oldValue[i].url !== newValue[i].url) {
onlyUpdateAttributes = false;
break;
}
}
}
if (onlyUpdateAttributes) {
for (var key in this.instances) {
if (this.instances.hasOwnProperty(key)) {
this.system._updateAccessors(this.entity, this.instances[key]);
}
}
}
return onlyUpdateAttributes;
},
// Load each url from the cache synchronously. If one of the urls is not in the cache
// then stop and return false.
_loadFromCache: function (urls) {
var cached = [];
for (var i=0, len=urls.length; i<len; i++) {
var type = this.system.app.loader.getFromCache(urls[i]);
// if we cannot find the script in the cache then return and load
// all scripts with the resource loader
if (!type) {
return false;
} else {
cached.push(type);
}
}
for (var i=0, len=cached.length; i<len; i++) {
var ScriptType = cached[i];
// check if this is a regular JS file
if (ScriptType === true) {
continue;
}
// ScriptType may be null if the script component is loading an ordinary javascript lib rather than a PlayCanvas script
// Make sure that script component hasn't been removed since we started loading
if (ScriptType && this.entity.script) {
// Make sure that we haven't already instanciated another identical script while loading
// e.g. if you do addComponent, removeComponent, addComponent, in quick succession
if (!this.entity.script.instances[ScriptType._pcScriptName]) {
var instance = new ScriptType(this.entity);
this.system._preRegisterInstance(this.entity, urls[i], ScriptType._pcScriptName, instance);
}
}
}
if (this.data) {
this.data.areScriptsLoaded = true;
}
// We only need to initalize after preloading is complete
// During preloading all scripts are initialized after everything is loaded
if (!this.system.preloading) {
this.system.onInitialize(this.entity);
this.system.onPostInitialize(this.entity);
}
return true;
},
_loadScripts: function (urls) {
var count = urls.length;
var prefix = this.system._prefix || "";
urls.forEach(function (url) {
var _url = null;
var _unprefixed = null;
// support absolute URLs (for now)
if (pc.string.startsWith(url.toLowerCase(), "http://") || pc.string.startsWith(url.toLowerCase(), "https://")) {
_unprefixed = url;
_url = url;
} else {
_unprefixed = url;
_url = pc.path.join(prefix, url);
}
this.system.app.loader.load(_url, "script", function (err, ScriptType) {
count--;
if (!err) {
// ScriptType is null if the script is not a PlayCanvas script
if (ScriptType && this.entity.script) {
if (!this.entity.script.instances[ScriptType._pcScriptName]) {
var instance = new ScriptType(this.entity);
this.system._preRegisterInstance(this.entity, _unprefixed, ScriptType._pcScriptName, instance);
}
}
} else {
console.error(err);
}
if (count === 0) {
this.data.areScriptsLoaded = true;
// We only need to initalize after preloading is complete
// During preloading all scripts are initialized after everything is loaded
if (!this.system.preloading) {
this.system.onInitialize(this.entity);
this.system.onPostInitialize(this.entity);
}
}
}.bind(this));
}.bind(this));
},
// Load each script url asynchronously using the resource loader
// _loadScripts: function (urls) {
// // Load and register new scripts and instances
// var requests = urls.map(function (url) {
// return new pc.resources.ScriptRequest(url);
// });
// var options = {
// parent: this.entity.getRequest()
// };
// var promise = this.system.app.loader.request(requests, options);
// promise.then(function (resources) {
// resources.forEach(function (ScriptType, index) {
// // ScriptType may be null if the script component is loading an ordinary javascript lib rather than a PlayCanvas script
// // Make sure that script component hasn't been removed since we started loading
// if (ScriptType && this.entity.script) {
// // Make sure that we haven't already instaciated another identical script while loading
// // e.g. if you do addComponent, removeComponent, addComponent, in quick succession
// if (!this.entity.script.instances[ScriptType._pcScriptName]) {
// var instance = new ScriptType(this.entity);
// this.system._preRegisterInstance(this.entity, urls[index], ScriptType._pcScriptName, instance);
// }
// }
// }, this);
// if (this.data) {
// this.data.areScriptsLoaded = true;
// }
// // If there is no request batch, then this is not part of a load request and so we need
// // to register the instances immediately to call the initialize function
// if (!options.parent) {
// this.system.onInitialize(this.entity);
// this.system.onPostInitialize(this.entity);
// }
// }.bind(this)).then(null, function (error) {
// // Re-throw any exceptions from the Script constructor to stop them being swallowed by the Promises lib
// setTimeout(function () {
// throw error;
// })
// });
// }
});
return {
ScriptComponent: ScriptComponent
};
}());