-
Notifications
You must be signed in to change notification settings - Fork 9
/
assets.js
1024 lines (914 loc) · 35.4 KB
/
assets.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
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Asset } from './asset.js';
import { globals as api } from './globals.js';
import { Events, ObserverList } from '@playcanvas/observer';
import { uploadFile } from './assets/upload.js';
import { createTemplate } from './assets/createTemplate.js';
import { createScript } from './assets/createScript.js';
import { instantiateTemplates } from './assets/instantiateTemplates.js';
/**
* Arguments passed when uploading an asset file.
*
* @typedef {object} AssetUploadArguments
* @property {Asset} folder - The parent folder asset where the asset should be placed.
* @property {string} filename - The filename of the uploaded file.
* @property {File} file - The file being uploaded.
* @property {string} type - The type of the asset we are uploading. See {@link Asset} for available asset types.
* @property {string} name - The name of the asset.
* @property {string[]} tags - The tags of the asset.
* @property {number} sourceAssetId - The id of the source asset.
* @property {object} data - The asset data. This depends on the asset type. See {@link Asset} for asset data depending on the type.
* @property {boolean} preload - Whether to preload the asset. Defaults to true.
* @property {number} id - If an asset id is specified then this asset will be updated instead of creating a new asset.
*/
/**
* Import settings used when uploading a texture asset.
*
* @typedef {object} TextureImportSettings
* @property {boolean} pow2 - Whether to resize the texture to power of 2.
* @property {boolean} searchRelatedAssets - Whether to search for target assets to update
* throughout the whole project instead of just the same folder.
*/
/**
* Import settings used when uploading a scene (fbx etc.).
*
* @typedef {object} SceneImportSettings
* @property {boolean} searchRelatedAssets - Whether to search for target assets to update
* throughout the whole project instead of just the same folder. Defaults to true.
* @property {boolean} overwriteModel - Whether to overwrite existing model or create a new one. Defaults to true.
* @property {boolean} overwriteAnimation - Whether to overwrite existing animations or create new ones. Defaults to true.
* @property {boolean} overwriteMaterial - Whether to overwrite existing materials or create new ones. Defaults to true.
* @property {boolean} overwriteTexture - Whether to overwrite existing textures or create new ones. Defaults to true.
* @property {boolean} pow2 - Whether to resize embedded textures to power of 2. Defaults to true.
* @property {boolean} useGlb - Whether to convert models to GLB. Defaults to true.
* @property {boolean} animSampleRate - The desired animation sample rate. Defaults to 10.
* @property {boolean} animCurveTolerance - The animation curve tolerance. Defaults to 0.
* @property {boolean} animEnableCubic - Whether to enable cubic curves. Defaults to false.
* @property {boolean} animUseFbxFilename - Whether to use the fbx filename for animation names. Defaults to false.
*/
/**
* The Assets Editor API
*/
class Assets extends Events {
/**
* Constructor
*
* @param {object} options - Options
* @param {boolean} options.autoSubscribe - Whether to auto subscribe to asset changes when assets are loaded.
*/
constructor(options = {}) {
super();
this._uniqueIdToItemId = {};
this._assets = new ObserverList({
index: 'id',
sorted: (a, b) => {
const f = (b._data.type === 'folder') - (a._data.type === 'folder');
if (f !== 0)
return f;
if ((a._data.name || '').toLowerCase() > (b._data.name || '').toLowerCase()) {
return 1;
} else if ((a._data.name || '').toLowerCase() < (b._data.name || '').toLowerCase()) {
return -1;
}
return 0;
}
});
this._parseScriptCallback = null;
this._defaultUploadCompletedCallback = null;
this._defaultUploadProgressCallback = null;
this._defaultUploadErrorCallback = null;
this._uploadId = 0;
this._autoSubscribe = options.autoSubscribe || false;
if (this._autoSubscribe && !api.messenger) {
throw new Error('Cannot autosubscribe to asset changes without the messenger API');
}
if (api.messenger) {
api.messenger.on('asset.new', this._onMessengerAddAsset.bind(this));
api.messenger.on('asset.delete', this._onMessengerDeleteAsset.bind(this));
api.messenger.on('assets.delete', this._onMessengerDeleteAssets.bind(this));
}
}
_onMessengerAddAsset(data) {
if (data.asset.branchId !== api.branchId) return;
const uniqueId = parseInt(data.asset.id, 10);
if (data.asset.source === false && data.asset.status && data.asset.status !== 'complete') {
return;
}
let asset = this.getUnique(uniqueId);
if (asset) return;
asset = new Asset({
id: uniqueId,
uniqueId: uniqueId,
type: data.asset.type,
source: data.asset.source,
source_asset_id: parseInt(data.asset.source_asset_id, 10),
createdAt: data.asset.createdAt
});
if (this._autoSubscribe) {
asset.loadAndSubscribe().then(() => {
this.add(asset);
});
} else {
asset.load().then(() => {
this.add(asset);
});
}
}
_onMessengerDeleteAsset(data) {
const asset = this.getUnique(data.asset.id);
if (asset) {
this.remove(asset);
}
}
_onMessengerDeleteAssets(data) {
for (let i = 0; i < data.assets.length; i++) {
const asset = this.getUnique(parseInt(data.assets[i], 10));
if (asset) {
this.remove(asset);
}
}
}
/**
* Gets asset by id
*
* @param {number} id - The asset id
* @returns {Asset} The asset
*/
get(id) {
const a = this._assets.get(id);
return a ? a.apiAsset : null;
}
/**
* Gets asset by its unique id
*
* @param {number} uniqueId - The unique id
* @returns {Asset} The asset
*/
getUnique(uniqueId) {
const id = this._uniqueIdToItemId[uniqueId];
return id ? this.get(id) : null;
}
/**
* Returns array of all assets
*
* @returns {Asset[]} The assets
*/
list() {
return this._assets.array().map(a => a.apiAsset);
}
/**
* Finds all assets with specified tags
*
* @param {...string|...string[]} tags - The tags. If multiple tags are specified then assets that contain ANY of the specified
* tags will be included. If an argument is an array of tags then assets that contain ALL of the tags in the array will be included.
* @returns {Asset[]} The assets
*/
listByTag(...tags) {
return this.filter((asset) => {
const t = asset.get('tags');
for (let i = 0; i < tags.length; i++) {
if (Array.isArray(tags[i])) {
let countTags = 0;
for (let j = 0; j < tags[i].length; j++) {
if (t.includes(tags[i][j])) {
countTags++;
} else {
break;
}
}
if (countTags === tags[i].length) {
return true;
}
} else {
if (t.includes(tags[i])) {
return true;
}
}
}
return false;
});
}
/**
* Adds asset to the list
*
* @category Internal
* @param {Asset} asset - The asset
*/
add(asset) {
asset._initializeHistory();
const pos = this._assets.add(asset._observer);
if (pos === null) return;
const id = asset.get('id');
this._uniqueIdToItemId[asset.get('uniqueId')] = id;
asset._observer.on('name:set', (name, oldName) => {
name = (name || '').toLowerCase();
oldName = (oldName || '').toLowerCase();
const ind = this._assets.data.indexOf(asset._observer);
let pos = this._assets.positionNextClosest(asset._observer, (a, b) => {
const f = (b._data.type === 'folder') - (a._data.type === 'folder');
if (f !== 0)
return f;
if ((a === b ? oldName : (a._data.name || '').toLowerCase()) > name) {
return 1;
} else if ((a === b ? oldName : (a._data.name || '').toLowerCase()) < name) {
return -1;
}
return 0;
});
if (pos === -1 && (ind + 1) === this._assets.data.length)
return;
if (ind !== -1 && (ind + 1 === pos) || (ind === pos))
return;
if (ind < pos)
pos--;
this._assets.move(asset._observer, pos);
this.emit('move', asset, pos);
});
this.emit(`add[${id}]`, asset, pos);
this.emit('add', asset, pos);
}
/**
* Removes asset from the list
*
* @category Internal
* @param {Asset} asset - The asset
*/
remove(asset) {
if (!this._assets.has(asset._observer)) return;
this._assets.remove(asset._observer);
delete this._uniqueIdToItemId[asset.get('uniqueId')];
asset._observer.destroy();
if (api.realtime) {
api.realtime.assets.unload(asset.get('uniqueId'));
}
this.emit(`remove`, asset);
this.emit(`remove[${asset.get('id')}]`);
}
/**
* Removes all assets from the list
*
* @category Internal
*/
clear() {
const assets = this.list();
if (!assets.length) return;
this._assets.clear();
let i = assets.length;
while (i--) {
this.remove(assets[i]);
}
this.emit('clear');
}
/**
* Gets assets that satisfy function
*
* @param {Function} fn - The function (takes an asset as an argument and returns boolean).
* @returns {Asset[]} The assets
*/
filter(fn) {
return this._assets.data
.filter(observer => fn(observer.apiAsset))
.map(observer => observer.apiAsset);
}
/**
* Finds first asset that satisfies function
*
* @param {Function} fn - A function that takes an asset as an argument and returns boolean.
* @returns {Asset} The asset
*/
findOne(fn) {
const result = this._assets.data.find(observer => fn(observer.apiAsset));
return result ? result.apiAsset : null;
}
/**
* Loads all assets in the current project / branch. Does not
* subscribe to realtime changes.
*
* @category Internal
* @param {object} options - Options
* @param {string} options.view - The desired view for the REST API e.g 'designer', 'shader-editor'. This might limit
* the assets returned to a smaller subset depending on the view.
*/
async loadAll(options = {}) {
this.clear();
this.emit('load:progress', 0.1);
const response = await fetch(`/api/projects/${api.projectId}/assets?branchId=${api.branchId}&view=${options.view || 'designer'}`);
if (!response.ok) {
console.error(`Could not load assets: [${response.status}] - ${response.statusText}`);
return;
}
const assets = await response.json();
this.emit('load:progress', 0.5);
const total = assets.length;
if (!total) {
this.emit('load:progress', 1);
this.emit('load:all');
return;
}
let loaded = 0;
const onProgress = () => {
loaded++;
if (loaded === total) {
this.emit('load:progress', 1);
this.emit('load:all');
} else {
this.emit('load:progress', (loaded / total) * 0.5 + 0.5);
}
};
for (let i = 0; i < total; i++) {
const asset = new Asset(assets[i]);
asset.load().then(() => {
this.add(asset);
onProgress();
}).catch((err) => {
onProgress();
});
}
}
/**
* Loads all assets in the current project / branch
* and subscribes to changes.
*
* @param {object} options - Options
* @param {string} options.view - The desired view for the REST API e.g 'designer', 'shader-editor'. This might limit
* the assets returned to a smaller subset depending on the view.
* @category Internal
*/
async loadAllAndSubscribe(options = {}) {
this.clear();
this.emit('load:progress', 0.1);
const response = await fetch(`/api/projects/${api.projectId}/assets?branchId=${api.branchId}&view=${options.view || 'designer'}`);
if (!response.ok) {
console.error(`Could not load assets: [${response.status}] - ${response.statusText}`);
return;
}
const assets = await response.json();
this.emit('load:progress', 0.5);
const total = assets.length;
if (!total) {
this.emit('load:progress', 1);
this.emit('load:all');
return;
}
const batchSize = 256;
let loaded = 0;
let startBatch = 0;
const onProgress = () => {
loaded++;
if (loaded === total) {
this.emit('load:progress', 1);
this.emit('load:all');
} else {
this.emit('load:progress', (loaded / total) * 0.5 + 0.5);
}
};
while (startBatch < total) {
api.realtime.connection.startBulkSubscribe();
for (let i = startBatch; i < startBatch + batchSize && i < total; i++) {
const asset = new Asset(assets[i]);
asset.loadAndSubscribe().then(() => {
this.add(asset);
onProgress();
}).catch((err) => {
onProgress();
});
}
api.realtime.connection.endBulkSubscribe();
startBatch += batchSize;
}
}
/**
* Gets the first script asset that contains the specified script
*
* @param {string} script - The script name
* @returns {Asset} The script asset
*/
getAssetForScript(script) {
return this.findOne((asset) => {
return asset.get('type') === 'script' &&
asset.has('data.scripts.' + script);
});
}
/**
* Creates new asset
*
* @private
* @param {AssetUploadArguments} data - The asset fields
* @param {TextureImportSettings|SceneImportSettings} settings - Import settings
* @param {Function} onProgress - Function to report progress
* @returns {Promise<Asset>} The new asset
*/
async upload(data, settings = {}, onProgress = null) {
if (data.folder) {
data.folderId = data.folder.get('id');
}
const uploadId = this._uploadId++;
if (!onProgress && this._defaultUploadProgressCallback) {
onProgress = (progress) => {
this._defaultUploadProgressCallback(uploadId, progress);
};
}
try {
const result = await uploadFile(data, settings, onProgress || this._defaultUploadProgressCallback);
let asset = this.get(result.id);
if (!asset) {
asset = await new Promise((resolve) => {
this.once(`add[${result.id}]`, (a) => {
resolve(a);
});
});
}
if (this._defaultUploadCompletedCallback) {
this._defaultUploadCompletedCallback(uploadId, asset);
}
return asset;
} catch (err) {
if (this._defaultUploadErrorCallback) {
this._defaultUploadErrorCallback(uploadId, err);
}
throw err;
}
}
/**
* Creates new anim state graph asset.
*
* @param {object} options - Options
* @param {string} options.name - The asset name
* @param {boolean} options.preload - Whether to preload the asset. Defaults to true.
* @param {object} options.data - The asset data. See {@link Asset} for Animstategraph data.
* @param {Asset} options.folder - The parent folder asset
* @param {Function} options.onProgress - Function to report progress
* @returns {Promise<Asset>} The new asset
*/
createAnimStateGraph(options = {}) {
return this.upload({
name: options.name || 'New Anim State Graph',
type: 'animstategraph',
data: options.data || api.schema.assets.getDefaultData('animstategraph'),
folder: options.folder,
preload: options.preload
}, null, options.onProgress);
}
/**
* Creates new bundle asset
*
* @param {object} options - Options
* @param {string} options.name - The asset name
* @param {Asset[]} options.assets - The assets that the bundle will contain
* @param {Asset} options.folder - The parent folder asset
* @param {boolean} options.preload - Whether to preload the asset. Defaults to true.
* @param {Function} options.onProgress - Function to report progress
* @returns {Promise<Asset>} The new asset
*/
createBundle(options = {}) {
return this.upload({
name: options.name || 'New Bundle',
type: 'bundle',
folder: options.folder,
data: {
assets: (options.assets || []).map(a => a.get('id'))
},
preload: options.preload
}, null, options.onProgress);
}
/**
* Creates new CSS asset
*
* @param {object} options - Options
* @param {string} options.name - The asset name
* @param {string} options.text - The CSS
* @param {string} options.folder - The parent folder asset
* @param {boolean} options.preload - Whether to preload the asset. Defaults to true.
* @param {Function} options.onProgress - Function to report progress
* @returns {Promise<Asset>} The new asset
*/
createCss(options = {}) {
return this.upload({
name: options.name || 'New Css',
type: 'css',
folder: options.folder,
filename: 'asset.css',
file: new Blob([options.text || '\n'], { type: 'text/css' }),
preload: options.preload
}, null, options.onProgress);
}
/**
* Creates new cubemap asset
*
* @param {object} options - Options
* @param {string} options.name - The asset name
* @param {Asset[]} options.textures - The textures for each cubemap face in this order:
* right, left, up, down, front, back
* @param {number} options.minFilter - Cubemap minFilter value. Defaults to pc.FILTER_LINEAR_MIPMAP_LINEAR.
* @param {number} options.magFilter - Cubemap magFilter value. Defaults to pc.FILTER_LINEAR.
* @param {number} options.anisotropy - Cubemap anisotropy value. Defaults to 1.
* @param {Asset} options.folder - The parent folder asset
* @param {boolean} options.preload - Whether to preload the asset. Defaults to true.
* @param {Function} options.onProgress - Function to report progress
* @returns {Promise<Asset>} The new asset
*/
createCubemap(options = {}) {
const textures = (options.textures || new Array(6)).slice(0, 6);
for (let i = 0; i < 6; i++) {
textures[i] = (textures[i] ? textures[i].get('id') : null);
}
return this.upload({
name: options.name || 'New Cubemap',
type: 'cubemap',
folder: options.folder,
preload: options.preload,
data: {
name: options.name || 'New Cubemap',
textures: textures,
minFilter: options.minFilter !== undefined ? options.minFilter : 5, // linear mipmap linear
magFilter: options.magFilter !== undefined ? options.magFilter : 1, // linear
anisotropy: options.anisotropy !== undefined ? options.anisotropy : 1
}
}, null, options.onProgress);
}
/**
* Creates a new folder asset
*
* @param {object} options - Options
* @param {string} options.name - The asset name
* @param {Asset} options.folder - The parent folder asset
* @param {Function} options.onProgress - Function to report progress
* @returns {Promise<Asset>} The new asset
*/
createFolder(options = {}) {
return this.upload({
name: options.name || 'New Folder',
type: 'folder',
folder: options.folder
}, null, options.onProgress);
}
/**
* Creates new HTML asset
*
* @param {object} options - Options
* @param {string} options.name - The asset name
* @param {string} options.text - The HTML
* @param {Asset} options.folder - The parent folder asset
* @param {boolean} options.preload - Whether to preload the asset. Defaults to true.
* @param {Function} options.onProgress - Function to report progress
* @returns {Promise<Asset>} The new asset
*/
createHtml(options = {}) {
return this.upload({
name: options.name || 'New Html',
type: 'html',
folder: options.folder,
preload: options.preload,
filename: 'asset.html',
file: new Blob([options.text || '\n'], { type: 'text/html' })
}, null, options.onProgress);
}
/**
* Creates new JSON asset
*
* @param {object} options - Options
* @param {string} options.name - The asset name
* @param {object} options.json - The JSON
* @param {number} options.spaces - The number of spaces used for indentation. Defaults to 0
* (tightly packed output).
* @param {Asset} options.folder - The parent folder asset
* @param {boolean} options.preload - Whether to preload the asset. Defaults to true.
* @param {Function} options.onProgress - Function to report progress
* @returns {Promise<Asset>} The new asset
*/
createJson(options = {}) {
const spaces = options.spaces ?? 0;
const str = JSON.stringify(options.json || {}, null, spaces);
return this.upload({
name: options.name || 'New Json',
type: 'json',
folder: options.folder,
preload: options.preload,
filename: 'asset.json',
file: new Blob([str], { type: 'application/json' })
}, null, options.onProgress);
}
/**
* Creates new localization JSON asset
*
* @param {object} options - The options
* @param {string} options.name - The asset name
* @param {object} options.localizationData - The localization data. If null then default data will be used.
* @param {Asset} options.folder - The parent folder asset
* @param {boolean} options.preload - Whether to preload the asset. Defaults to true.
* @param {Function} options.onProgress - Function to report progress
* @returns {Promise<Asset>} The new asset
*/
createI18n(options = {}) {
return this.createJson({
name: options.name,
json: options.localizationData || {
"header": {
"version": 1
},
"data": [{
"info": {
"locale": "en-US"
},
"messages": {
"key": "Single key translation",
"key plural": ["One key translation", "Translation for {number} keys"]
}
}]
},
folder: options.folder,
preload: options.preload,
spaces: 4
}, null, options.onProgress);
}
/**
* Creates new material asset
*
* @param {object} options - Options
* @param {string} options.name - The asset name
* @param {object} options.data - The material data. Default values will be used for missing fields. See {@link Asset} for material data.
* @param {Asset} options.folder - The parent folder asset
* @param {boolean} options.preload - Whether to preload the asset. Defaults to true.
* @param {Function} options.onProgress - Function to report progress
* @returns {Promise<Asset>} The new asset
*/
createMaterial(options = {}) {
const defaultData = api.schema.assets.getDefaultData('material');
if (options.data) {
for (const key in defaultData) {
if (options.data[key]) {
defaultData[key] = options.data[key];
}
}
}
return this.upload({
name: options.name || 'New Material',
type: 'material',
folder: options.folder,
data: defaultData,
preload: options.preload
}, null, options.onProgress);
}
/**
* Creates new script asset
*
* @param {object} options - Options
* @param {string} options.filename - The filename of the script. This will also be the name of the script asset. If not defined it will be generated
* from the name of the script.
* @param {string} options.text - The contents of the script. If none then boilerplate code will be used.
* @param {object} options.data - The script data. See {@link Asset} for Script data.
* @param {Asset} options.folder - The parent folder asset
* @param {boolean} options.preload - Whether to preload the asset. Defaults to true.
* @param {Function} options.onProgress - Function to report progress
* @returns {Promise<Asset>} The new asset
*/
async createScript(options = {}) {
if (!options.filename) {
throw new Error('createScript: missing required filename');
}
const result = createScript(options.filename, options.text);
const asset = await this.upload({
name: result.filename,
type: 'script',
folder: options.folder,
filename: result.filename,
file: new Blob([result.content], { type: 'text/javascript' }),
preload: options.preload,
data: options.data || {
scripts: { },
loading: false,
loadingType: 0 // load script as asset
}
}, null, options.onProgress);
// wait for asset to have a file url
if (this._parseScriptCallback) {
if (!asset.get('file.url')) {
await new Promise((resolve) => {
asset.once('file.url:set', resolve);
});
}
const scripts = await this._parseScriptCallback(asset);
// check if all scripts have been set to the asset
// because of possible network delays.
// if not then wait until those scripts have been set
// before returning
const wait = [];
scripts.forEach((script) => {
if (!asset.has(`data.scripts.${script}`)) {
wait.push(new Promise((resolve) => {
asset.once(`data.scripts.${script}:set`, resolve);
}));
}
});
await Promise.all(wait);
}
return asset;
}
/**
* Creates new shader asset
*
* @param {object} options - Options
* @param {string} options.name - The asset name
* @param {string} options.text - The GLSL
* @param {Asset} options.folder - The parent folder asset
* @param {boolean} options.preload - Whether to preload the asset. Defaults to true.
* @param {Function} options.onProgress - Function to report progress
* @returns {Promise<Asset>} The new asset
*/
createShader(options = {}) {
return this.upload({
name: options.name || 'New Shader',
type: 'shader',
folder: options.folder,
preload: options.preload,
filename: 'asset.glsl',
file: new Blob([options.text || '\n'], { type: 'text/x-glsl' })
}, null, options.onProgress);
}
/**
* Creates new sprite asset
*
* @param {object} options - Options
* @param {string} options.name - The asset name
* @param {number} options.pixelsPerUnit - The sprite's pixels per unit value. Defaults to 100.
* @param {number[]} options.frameKeys - The sprite's frame keys
* @param {Asset} options.textureAtlas - The sprite's texture atlas asset
* @param {number} options.renderMode - The sprite's render mode. Defaults to pc.SPRITE_RENDERMODE_SIMPLE.
* @param {Asset} options.folder - The parent folder asset
* @param {boolean} options.preload - Whether to preload the asset. Defaults to true.
* @param {Function} options.onProgress - Function to report progress
* @returns {Promise<Asset>} The new asset
*/
createSprite(options = {}) {
const data = {};
data.pixelsPerUnit = options.pixelsPerUnit !== undefined ? options.pixelsPerUnit : 100;
data.frameKeys = options.frameKeys ? options.frameKeys.map(val => val.toString()) : [];
data.textureAtlasAsset = options.textureAtlas ? options.textureAtlas.get('id') : null;
data.renderMode = options.renderMode !== undefined ? options.renderMode : 0;
return this.upload({
name: options.name || 'New Sprite',
type: 'sprite',
folder: options.folder,
preload: options.preload,
data: data
}, null, options.onProgress);
}
/**
* Creates new text asset
*
* @param {object} options - Options
* @param {string} options.name - The asset name
* @param {string} options.text - The text
* @param {Asset} options.folder - The parent folder asset
* @param {boolean} options.preload - Whether to preload the asset. Defaults to true.
* @param {Function} options.onProgress - Function to report progress
* @returns {Promise<Asset>} The new asset
*/
createText(options = {}) {
return this.upload({
name: options.name || 'New Text',
type: 'text',
folder: options.folder,
preload: options.preload,
filename: 'asset.txt',
file: new Blob([options.text || '\n'], { type: 'text/plain' })
}, null, options.onProgress);
}
/**
* Creates new template asset
*
* @typedef {import("./entity").Entity} Entity
* @param {object} options - Options
* @param {string} options.name - The asset name
* @param {Entity} options.entity - The entity to create the template from
* @param {Asset} options.folder - The parent folder asset
* @param {boolean} options.preload - Whether to preload the asset. Defaults to true.
* @param {Function} options.onProgress - Function to report progress
* @returns {Promise<Asset>} The new asset
*/
async createTemplate(options = {}) {
const {
entities,
oldToNewIds
} = createTemplate(options.entity);
const asset = await this.upload({
name: options.name || options.entity.get('name'),
type: 'template',
folder: options.folder,
preload: options.preload,
data: { entities }
}, null, options.onProgress);
const history = options.entity.history.enabled;
options.entity.history.enabled = false;
options.entity.set('template_id', parseInt(asset.get('id'), 10));
options.entity.set('template_ent_ids', oldToNewIds);
options.entity.history.enabled = history;
}
/**
* Deletes specified assets
*
* @param {Asset[]} assets - The assets
*/
async delete(assets) {
const response = await fetch('/api/assets', {
body: JSON.stringify({
assets: assets.map(a => a.get('id')),
branchId: api.branchId
}),
method: 'DELETE',
headers: {
'Content-Type': 'application/json'
}
});
if (!response.ok) {
throw new Error(response.status + ': ' + response.statusText);
}
assets.forEach(a => this.remove(a));
}
/**
* Instantiates the specified template assets under the specified
* parent entity.
*
* @param {Asset[]} assets - The template assets.
* @param {Entity} parent - The parent entity
* @param {object} options - Options
* @param {number} options.index - The desired index under the parent to instantiate the templates.
* @param {boolean} options.history - Whether to record a history action.
* @param {boolean} options.select - Whether to select the new entities.
* @param {object} options.extraData - Extra data passed to the backend. Used by the Editor on specific cases.
* @returns {Promise<Entity[]>} The new entities
*/
instantiateTemplates(assets, parent, options = {}) {
return instantiateTemplates(assets, parent, options);
}
/**
* Sets the default callback called when on asset upload succeeds.
* The function takes 2 arguments: the upload id, and the new asset.
*
* @type {Function<number, Asset>}
*/
set defaultUploadCompletedCallback(value) {
this._defaultUploadCompletedCallback = value;
}
/**
* Gets the default callback called when on asset upload succeeds.
*
* @type {Function<number, Asset>}
*/
get defaultUploadCompletedCallback() {
return this._defaultUploadCompletedCallback;
}
/**
* Sets the default callback called when on asset upload progress.
* The function takes 2 arguments: the upload id and the progress.
*
* @type {Function<number, number>}
*/
set defaultUploadProgressCallback(value) {
this._defaultUploadProgressCallback = value;
}
/**
* Gets the default callback called when on asset upload progress.
*
* @type {Function<number, number>}
*/
get defaultUploadProgressCallback() {
return this._defaultUploadProgressCallback;
}
/**
* Sets the default callback called when on asset upload progress.
* The function takes 2 arguments: the upload id, and the error.
*
* @type {Function<number, Error>}
*/
set defaultUploadErrorCallback(value) {
this._defaultUploadErrorCallback = value;
}
/**
* Gets the default callback called when on asset upload fails.
*
* @type {Function<number, Error>}
*/
get defaultUploadErrorCallback() {
return this._defaultUploadErrorCallback;
}