forked from playcanvas/engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
asset-registry.js
767 lines (677 loc) · 25 KB
/
asset-registry.js
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
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
import { path } from '../../core/path.js';
import { Debug } from '../../core/debug.js';
import { EventHandler } from '../../core/event-handler.js';
import { TagsCache } from '../../core/tags-cache.js';
import { standardMaterialTextureParameters } from '../../scene/materials/standard-material-parameters.js';
import { script } from '../script.js';
import { Asset } from './asset.js';
/**
* Callback used by {@link AssetRegistry#filter} to filter assets.
*
* @callback FilterAssetCallback
* @param {Asset} asset - The current asset to filter.
* @returns {boolean} Return `true` to include asset to result list.
*/
/**
* Callback used by {@link AssetRegistry#loadFromUrl} and called when an asset is loaded (or an
* error occurs).
*
* @callback LoadAssetCallback
* @param {string|null} err - The error message is null if no errors were encountered.
* @param {Asset} [asset] - The loaded asset if no errors were encountered.
*/
/**
* Callback used by {@link ResourceLoader#load} and called when an asset is choosing a bundle
* to load from. Return a single bundle to ensure asset is loaded from it.
*
* @callback BundlesFilterCallback
* @param {import('../bundle/bundle.js').Bundle[]} bundles - List of bundles which contain the asset.
*/
/**
* Container for all assets that are available to this application. Note that PlayCanvas scripts
* are provided with an AssetRegistry instance as `app.assets`.
*
* @augments EventHandler
* @category Asset
*/
class AssetRegistry extends EventHandler {
/**
* Fired when an asset completes loading. This event is available in three forms. They are as
* follows:
*
* 1. `load` - Fired when any asset finishes loading.
* 2. `load:[id]` - Fired when a specific asset has finished loading, where `[id]` is the
* unique id of the asset.
* 3. `load:url:[url]` - Fired when an asset finishes loading whose URL matches `[url]`, where
* `[url]` is the URL of the asset.
*
* @event
* @example
* app.assets.on('load', (asset) => {
* console.log(`Asset loaded: ${asset.name}`);
* });
* @example
* const id = 123456;
* const asset = app.assets.get(id);
* app.assets.on('load:' + id, (asset) => {
* console.log(`Asset loaded: ${asset.name}`);
* });
* app.assets.load(asset);
* @example
* const id = 123456;
* const asset = app.assets.get(id);
* app.assets.on('load:url:' + asset.file.url, (asset) => {
* console.log(`Asset loaded: ${asset.name}`);
* });
* app.assets.load(asset);
*/
static EVENT_LOAD = 'load';
/**
* Fired when an asset is added to the registry. This event is available in three forms. They
* are as follows:
*
* 1. `add` - Fired when any asset is added to the registry.
* 2. `add:[id]` - Fired when an asset is added to the registry, where `[id]` is the unique id
* of the asset.
* 3. `add:url:[url]` - Fired when an asset is added to the registry and matches the URL
* `[url]`, where `[url]` is the URL of the asset.
*
* @event
* @example
* app.assets.on('add', (asset) => {
* console.log(`Asset added: ${asset.name}`);
* });
* @example
* const id = 123456;
* app.assets.on('add:' + id, (asset) => {
* console.log(`Asset added: ${asset.name}`);
* });
* @example
* const id = 123456;
* const asset = app.assets.get(id);
* app.assets.on('add:url:' + asset.file.url, (asset) => {
* console.log(`Asset added: ${asset.name}`);
* });
*/
static EVENT_ADD = 'add';
/**
* Fired when an asset is removed from the registry. This event is available in three forms.
* They are as follows:
*
* 1. `remove` - Fired when any asset is removed from the registry.
* 2. `remove:[id]` - Fired when an asset is removed from the registry, where `[id]` is the
* unique id of the asset.
* 3. `remove:url:[url]` - Fired when an asset is removed from the registry and matches the
* URL `[url]`, where `[url]` is the URL of the asset.
*
* @event
* @param {Asset} asset - The asset that was removed.
* @example
* app.assets.on('remove', (asset) => {
* console.log(`Asset removed: ${asset.name}`);
* });
* @example
* const id = 123456;
* app.assets.on('remove:' + id, (asset) => {
* console.log(`Asset removed: ${asset.name}`);
* });
* @example
* const id = 123456;
* const asset = app.assets.get(id);
* app.assets.on('remove:url:' + asset.file.url, (asset) => {
* console.log(`Asset removed: ${asset.name}`);
* });
*/
static EVENT_REMOVE = 'remove';
/**
* Fired when an error occurs during asset loading. This event is available in two forms. They
* are as follows:
*
* 1. `error` - Fired when any asset reports an error in loading.
* 2. `error:[id]` - Fired when an asset reports an error in loading, where `[id]` is the
* unique id of the asset.
*
* @event
* @example
* const id = 123456;
* const asset = app.assets.get(id);
* app.assets.on('error', (err, asset) => {
* console.error(err);
* });
* app.assets.load(asset);
* @example
* const id = 123456;
* const asset = app.assets.get(id);
* app.assets.on('error:' + id, (err, asset) => {
* console.error(err);
* });
* app.assets.load(asset);
*/
static EVENT_ERROR = 'error';
/**
* @type {Set<Asset>}
* @private
*/
_assets = new Set();
/**
* @type {Map<number, Asset>}
* @private
*/
_idToAsset = new Map();
/**
* @type {Map<string, Asset>}
* @private
*/
_urlToAsset = new Map();
/**
* @type {Map<string, Set<Asset>>}
* @private
*/
_nameToAsset = new Map();
/**
* Index for looking up by tags.
*
* @private
*/
_tags = new TagsCache('_id');
/**
* A URL prefix that will be added to all asset loading requests.
*
* @type {string|null}
*/
prefix = null;
/**
* BundleRegistry
*
* @type {import('../bundle/bundle-registry.js').BundleRegistry|null}
*/
bundles = null;
/**
* Create an instance of an AssetRegistry.
*
* @param {import('../handlers/loader.js').ResourceLoader} loader - The ResourceLoader used to
* load the asset files.
*/
constructor(loader) {
super();
this._loader = loader;
}
/**
* Create a filtered list of assets from the registry.
*
* @param {object} filters - Properties to filter on, currently supports: 'preload: true|false'.
* @returns {Asset[]} The filtered list of assets.
*/
list(filters = {}) {
const assets = Array.from(this._assets);
if (filters.preload !== undefined) {
return assets.filter(asset => asset.preload === filters.preload);
}
return assets;
}
/**
* Add an asset to the registry.
*
* @param {Asset} asset - The asset to add.
* @example
* const asset = new pc.Asset("My Asset", "texture", {
* url: "../path/to/image.jpg"
* });
* app.assets.add(asset);
*/
add(asset) {
if (this._assets.has(asset)) return;
this._assets.add(asset);
this._idToAsset.set(asset.id, asset);
if (asset.file?.url) {
this._urlToAsset.set(asset.file.url, asset);
}
if (!this._nameToAsset.has(asset.name))
this._nameToAsset.set(asset.name, new Set());
this._nameToAsset.get(asset.name).add(asset);
asset.on('name', this._onNameChange, this);
asset.registry = this;
// tags cache
this._tags.addItem(asset);
asset.tags.on('add', this._onTagAdd, this);
asset.tags.on('remove', this._onTagRemove, this);
this.fire('add', asset);
this.fire('add:' + asset.id, asset);
if (asset.file?.url) {
this.fire('add:url:' + asset.file.url, asset);
}
if (asset.preload)
this.load(asset);
}
/**
* Remove an asset from the registry.
*
* @param {Asset} asset - The asset to remove.
* @returns {boolean} True if the asset was successfully removed and false otherwise.
* @example
* const asset = app.assets.get(100);
* app.assets.remove(asset);
*/
remove(asset) {
if (!this._assets.has(asset)) return false;
this._assets.delete(asset);
this._idToAsset.delete(asset.id);
if (asset.file?.url) {
this._urlToAsset.delete(asset.file.url);
}
asset.off('name', this._onNameChange, this);
if (this._nameToAsset.has(asset.name)) {
const items = this._nameToAsset.get(asset.name);
items.delete(asset);
if (items.size === 0) {
this._nameToAsset.delete(asset.name);
}
}
// tags cache
this._tags.removeItem(asset);
asset.tags.off('add', this._onTagAdd, this);
asset.tags.off('remove', this._onTagRemove, this);
asset.fire('remove', asset);
this.fire('remove', asset);
this.fire('remove:' + asset.id, asset);
if (asset.file?.url) {
this.fire('remove:url:' + asset.file.url, asset);
}
return true;
}
/**
* Retrieve an asset from the registry by its id field.
*
* @param {number} id - The id of the asset to get.
* @returns {Asset|undefined} The asset.
* @example
* const asset = app.assets.get(100);
*/
get(id) {
// Since some apps incorrectly pass the id as a string, force a conversion to a number
return this._idToAsset.get(Number(id));
}
/**
* Retrieve an asset from the registry by its file's URL field.
*
* @param {string} url - The url of the asset to get.
* @returns {Asset|undefined} The asset.
* @example
* const asset = app.assets.getByUrl("../path/to/image.jpg");
*/
getByUrl(url) {
return this._urlToAsset.get(url);
}
/**
* Load the asset's file from a remote source. Listen for "load" events on the asset to find
* out when it is loaded.
*
* @param {Asset} asset - The asset to load.
* @param {object} [options] - Options for asset loading.
* @param {boolean} [options.bundlesIgnore] - If set to true, then asset will not try to load
* from a bundle. Defaults to false.
* @param {boolean} [options.force] - If set to true, then the check of asset being loaded or
* is already loaded is bypassed, which forces loading of asset regardless.
* @param {BundlesFilterCallback} [options.bundlesFilter] - A callback that will be called
* when loading an asset that is contained in any of the bundles. It provides an array of
* bundles and will ensure asset is loaded from bundle returned from a callback. By default
* smallest filesize bundle is choosen.
* @example
* // load some assets
* const assetsToLoad = [
* app.assets.find("My Asset"),
* app.assets.find("Another Asset")
* ];
* let count = 0;
* assetsToLoad.forEach(function (assetToLoad) {
* assetToLoad.ready(function (asset) {
* count++;
* if (count === assetsToLoad.length) {
* // done
* }
* });
* app.assets.load(assetToLoad);
* });
*/
load(asset, options) {
// do nothing if asset is already loaded
// note: lots of code calls assets.load() assuming this check is present
// don't remove it without updating calls to assets.load() with checks for the asset.loaded state
if ((asset.loading || asset.loaded) && !options?.force) {
return;
}
const file = asset.file;
const _fireLoad = () => {
this.fire('load', asset);
this.fire('load:' + asset.id, asset);
if (file && file.url)
this.fire('load:url:' + file.url, asset);
asset.fire('load', asset);
};
// open has completed on the resource
const _opened = (resource) => {
if (resource instanceof Array) {
asset.resources = resource;
} else {
asset.resource = resource;
}
// let handler patch the resource
this._loader.patch(asset, this);
if (asset.type === 'bundle') {
const assetIds = asset.data.assets;
for (let i = 0; i < assetIds.length; i++) {
const assetInBundle = this._idToAsset.get(assetIds[i]);
if (assetInBundle && !assetInBundle.loaded) {
this.load(assetInBundle, { force: true });
}
}
if (asset.resource.loaded) {
_fireLoad();
} else {
this.fire('load:start', asset);
this.fire('load:start:' + asset.id, asset);
if (file && file.url)
this.fire('load:start:url:' + file.url, asset);
asset.fire('load:start', asset);
asset.resource.on('load', _fireLoad);
}
} else {
_fireLoad();
}
};
// load has completed on the resource
const _loaded = (err, resource, extra) => {
asset.loaded = true;
asset.loading = false;
if (err) {
this.fire('error', err, asset);
this.fire('error:' + asset.id, err, asset);
asset.fire('error', err, asset);
} else {
if (!script.legacy && asset.type === 'script') {
const handler = this._loader.getHandler('script');
if (handler._cache[asset.id] && handler._cache[asset.id].parentNode === document.head) {
// remove old element
document.head.removeChild(handler._cache[asset.id]);
}
handler._cache[asset.id] = extra;
}
_opened(resource);
}
};
if (file || asset.type === 'cubemap') {
// start loading the resource
this.fire('load:start', asset);
this.fire('load:' + asset.id + ':start', asset);
asset.loading = true;
const fileUrl = asset.getFileUrl();
// mark bundle assets as loading
if (asset.type === 'bundle') {
const assetIds = asset.data.assets;
for (let i = 0; i < assetIds.length; i++) {
const assetInBundle = this._idToAsset.get(assetIds[i]);
if (!assetInBundle)
continue;
if (assetInBundle.loaded || assetInBundle.resource || assetInBundle.loading)
continue;
assetInBundle.loading = true;
}
}
this._loader.load(fileUrl, asset.type, _loaded, asset, options);
} else {
// asset has no file to load, open it directly
const resource = this._loader.open(asset.type, asset.data);
asset.loaded = true;
_opened(resource);
}
}
/**
* Use this to load and create an asset if you don't have assets created. Usually you would
* only use this if you are not integrated with the PlayCanvas Editor.
*
* @param {string} url - The url to load.
* @param {string} type - The type of asset to load.
* @param {LoadAssetCallback} callback - Function called when asset is loaded, passed (err,
* asset), where err is null if no errors were encountered.
* @example
* app.assets.loadFromUrl("../path/to/texture.jpg", "texture", function (err, asset) {
* const texture = asset.resource;
* });
*/
loadFromUrl(url, type, callback) {
this.loadFromUrlAndFilename(url, null, type, callback);
}
/**
* Use this to load and create an asset when both the URL and filename are required. For
* example, use this function when loading BLOB assets, where the URL does not adequately
* identify the file.
*
* @param {string} url - The url to load.
* @param {string} filename - The filename of the asset to load.
* @param {string} type - The type of asset to load.
* @param {LoadAssetCallback} callback - Function called when asset is loaded, passed (err,
* asset), where err is null if no errors were encountered.
* @example
* const file = magicallyObtainAFile();
* app.assets.loadFromUrlAndFilename(URL.createObjectURL(file), "texture.png", "texture", function (err, asset) {
* const texture = asset.resource;
* });
*/
loadFromUrlAndFilename(url, filename, type, callback) {
const name = path.getBasename(filename || url);
const file = {
filename: filename || name,
url: url
};
let asset = this.getByUrl(url);
if (!asset) {
asset = new Asset(name, type, file);
this.add(asset);
} else if (asset.loaded) {
// asset is already loaded
callback(asset.loadFromUrlError || null, asset);
return;
}
const startLoad = (asset) => {
asset.once('load', (loadedAsset) => {
if (type === 'material') {
this._loadTextures(loadedAsset, (err, textures) => {
callback(err, loadedAsset);
});
} else {
callback(null, loadedAsset);
}
});
asset.once('error', (err) => {
// store the error on the asset in case user requests this asset again
if (err) {
this.loadFromUrlError = err;
}
callback(err, asset);
});
this.load(asset);
};
if (asset.resource) {
callback(null, asset);
} else if (type === 'model') {
this._loadModel(asset, startLoad);
} else {
startLoad(asset);
}
}
// private method used for engine-only loading of model data
_loadModel(modelAsset, continuation) {
const url = modelAsset.getFileUrl();
const ext = path.getExtension(url);
if (ext === '.json' || ext === '.glb') {
const dir = path.getDirectory(url);
const basename = path.getBasename(url);
// PlayCanvas model format supports material mapping file
const mappingUrl = path.join(dir, basename.replace(ext, '.mapping.json'));
this._loader.load(mappingUrl, 'json', (err, data) => {
if (err) {
modelAsset.data = { mapping: [] };
continuation(modelAsset);
} else {
this._loadMaterials(modelAsset, data, (e, materials) => {
modelAsset.data = data;
continuation(modelAsset);
});
}
});
} else {
// other model format (e.g. obj)
continuation(modelAsset);
}
}
// private method used for engine-only loading of model materials
_loadMaterials(modelAsset, mapping, callback) {
const materials = [];
let count = 0;
const onMaterialLoaded = (err, materialAsset) => {
// load dependent textures
this._loadTextures(materialAsset, (err, textures) => {
materials.push(materialAsset);
if (materials.length === count) {
callback(null, materials);
}
});
};
for (let i = 0; i < mapping.mapping.length; i++) {
const path = mapping.mapping[i].path;
if (path) {
count++;
const url = modelAsset.getAbsoluteUrl(path);
this.loadFromUrl(url, 'material', onMaterialLoaded);
}
}
if (count === 0) {
callback(null, materials);
}
}
// private method used for engine-only loading of the textures referenced by
// the material asset
_loadTextures(materialAsset, callback) {
const textures = [];
let count = 0;
const data = materialAsset.data;
if (data.mappingFormat !== 'path') {
Debug.warn(`Skipping: ${materialAsset.name}, material files must be mappingFormat: "path" to be loaded from URL`);
callback(null, textures);
return;
}
const onTextureLoaded = (err, texture) => {
if (err) console.error(err);
textures.push(texture);
if (textures.length === count) {
callback(null, textures);
}
};
const texParams = standardMaterialTextureParameters;
for (let i = 0; i < texParams.length; i++) {
const path = data[texParams[i]];
if (path && typeof path === 'string') {
count++;
const url = materialAsset.getAbsoluteUrl(path);
this.loadFromUrl(url, 'texture', onTextureLoaded);
}
}
if (count === 0) {
callback(null, textures);
}
}
_onTagAdd(tag, asset) {
this._tags.add(tag, asset);
}
_onTagRemove(tag, asset) {
this._tags.remove(tag, asset);
}
_onNameChange(asset, name, nameOld) {
// remove
if (this._nameToAsset.has(nameOld)) {
const items = this._nameToAsset.get(nameOld);
items.delete(asset);
if (items.size === 0) {
this._nameToAsset.delete(nameOld);
}
}
// add
if (!this._nameToAsset.has(asset.name))
this._nameToAsset.set(asset.name, new Set());
this._nameToAsset.get(asset.name).add(asset);
}
/**
* Return all Assets that satisfy the search query. Query can be simply a string, or comma
* separated strings, to have inclusive results of assets that match at least one query. A
* query that consists of an array of tags can be used to match assets that have each tag of
* array.
*
* @param {...*} query - Name of a tag or array of tags.
* @returns {Asset[]} A list of all Assets matched query.
* @example
* const assets = app.assets.findByTag("level-1");
* // returns all assets that tagged by `level-1`
* @example
* const assets = app.assets.findByTag("level-1", "level-2");
* // returns all assets that tagged by `level-1` OR `level-2`
* @example
* const assets = app.assets.findByTag(["level-1", "monster"]);
* // returns all assets that tagged by `level-1` AND `monster`
* @example
* const assets = app.assets.findByTag(["level-1", "monster"], ["level-2", "monster"]);
* // returns all assets that tagged by (`level-1` AND `monster`) OR (`level-2` AND `monster`)
*/
findByTag() {
return this._tags.find(arguments);
}
/**
* Return all Assets that satisfy a filter callback.
*
* @param {FilterAssetCallback} callback - The callback function that is used to filter assets.
* Return `true` to include an asset in the returned array.
* @returns {Asset[]} A list of all Assets found.
* @example
* const assets = app.assets.filter(asset => asset.name.includes('monster'));
* console.log(`Found ${assets.length} assets with a name containing 'monster'`);
*/
filter(callback) {
return Array.from(this._assets).filter(asset => callback(asset));
}
/**
* Return the first Asset with the specified name and type found in the registry.
*
* @param {string} name - The name of the Asset to find.
* @param {string} [type] - The type of the Asset to find.
* @returns {Asset|null} A single Asset or null if no Asset is found.
* @example
* const asset = app.assets.find("myTextureAsset", "texture");
*/
find(name, type) {
const items = this._nameToAsset.get(name);
if (!items) return null;
for (const asset of items) {
if (!type || asset.type === type) {
return asset;
}
}
return null;
}
/**
* Return all Assets with the specified name and type found in the registry.
*
* @param {string} name - The name of the Assets to find.
* @param {string} [type] - The type of the Assets to find.
* @returns {Asset[]} A list of all Assets found.
* @example
* const assets = app.assets.findAll('brick', 'texture');
* console.log(`Found ${assets.length} texture assets named 'brick'`);
*/
findAll(name, type) {
const items = this._nameToAsset.get(name);
if (!items) return [];
const results = Array.from(items);
if (!type) return results;
return results.filter(asset => asset.type === type);
}
}
export { AssetRegistry };