-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
app-base.js
2096 lines (1818 loc) · 71.2 KB
/
app-base.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
// #if _DEBUG
import { version, revision } from '../core/core.js';
// #endif
import { platform } from '../core/platform.js';
import { now } from '../core/time.js';
import { path } from '../core/path.js';
import { TRACEID_RENDER_FRAME, TRACEID_RENDER_FRAME_TIME } from '../core/constants.js';
import { Debug } from '../core/debug.js';
import { EventHandler } from '../core/event-handler.js';
import { Color } from '../core/math/color.js';
import { Mat4 } from '../core/math/mat4.js';
import { math } from '../core/math/math.js';
import { Quat } from '../core/math/quat.js';
import { Vec3 } from '../core/math/vec3.js';
import {
PRIMITIVE_TRIANGLES, PRIMITIVE_TRIFAN, PRIMITIVE_TRISTRIP, CULLFACE_NONE
} from '../platform/graphics/constants.js';
import { DebugGraphics } from '../platform/graphics/debug-graphics.js';
import { http } from '../platform/net/http.js';
import {
LAYERID_DEPTH, LAYERID_IMMEDIATE, LAYERID_SKYBOX, LAYERID_UI, LAYERID_WORLD,
SORTMODE_NONE, SORTMODE_MANUAL
} from '../scene/constants.js';
import { setProgramLibrary } from '../scene/shader-lib/get-program-library.js';
import { ProgramLibrary } from '../scene/shader-lib/program-library.js';
import { ForwardRenderer } from '../scene/renderer/forward-renderer.js';
import { FrameGraph } from '../scene/frame-graph.js';
import { AreaLightLuts } from '../scene/area-light-luts.js';
import { Layer } from '../scene/layer.js';
import { LayerComposition } from '../scene/composition/layer-composition.js';
import { Scene } from '../scene/scene.js';
import { ShaderMaterial } from '../scene/materials/shader-material.js';
import { StandardMaterial } from '../scene/materials/standard-material.js';
import { setDefaultMaterial } from '../scene/materials/default-material.js';
import {
FILLMODE_FILL_WINDOW, FILLMODE_KEEP_ASPECT,
RESOLUTION_AUTO, RESOLUTION_FIXED
} from './constants.js';
import { Asset } from './asset/asset.js';
import { AssetRegistry } from './asset/asset-registry.js';
import { BundleRegistry } from './bundle/bundle-registry.js';
import { ComponentSystemRegistry } from './components/registry.js';
import { BundleHandler } from './handlers/bundle.js';
import { ResourceLoader } from './handlers/loader.js';
import { I18n } from './i18n/i18n.js';
import { ScriptRegistry } from './script/script-registry.js';
import { Entity } from './entity.js';
import { SceneRegistry } from './scene-registry.js';
import { script } from './script.js';
import { ApplicationStats } from './stats.js';
import { getApplication, setApplication } from './globals.js';
/**
* @import { AppOptions } from './app-options.js'
* @import { BatchManager } from '../scene/batching/batch-manager.js'
* @import { ElementInput } from './input/element-input.js'
* @import { GamePads } from '../platform/input/game-pads.js'
* @import { GraphicsDevice } from '../platform/graphics/graphics-device.js'
* @import { Keyboard } from '../platform/input/keyboard.js'
* @import { Lightmapper } from './lightmapper/lightmapper.js'
* @import { Material } from '../scene/materials/material.js'
* @import { MeshInstance } from '../scene/mesh-instance.js'
* @import { Mesh } from '../scene/mesh.js'
* @import { Mouse } from '../platform/input/mouse.js'
* @import { SoundManager } from '../platform/sound/manager.js'
* @import { Texture } from '../platform/graphics/texture.js'
* @import { TouchDevice } from '../platform/input/touch-device.js'
* @import { XrManager } from './xr/xr-manager.js'
*/
/**
* Callback used by {@link AppBase#configure} when configuration file is loaded and parsed (or an
* error occurs).
*
* @callback ConfigureAppCallback
* @param {string|null} err - The error message in the case where the loading or parsing fails.
* @returns {void}
*/
/**
* Callback used by {@link AppBase#preload} when all assets (marked as 'preload') are loaded.
*
* @callback PreloadAppCallback
* @returns {void}
*/
/**
* Callback used by {@link AppBase#start} and itself to request the rendering of a new animation
* frame.
*
* @callback MakeTickCallback
* @param {number} [timestamp] - The timestamp supplied by requestAnimationFrame.
* @param {XRFrame} [frame] - XRFrame from requestAnimationFrame callback.
* @returns {void}
*/
/**
* Gets the current application, if any.
*
* @type {AppBase|null}
* @ignore
*/
let app = null;
/**
* An Application represents and manages your PlayCanvas application. If you are developing using
* the PlayCanvas Editor, the Application is created for you. You can access your Application
* instance in your scripts. Below is a skeleton script which shows how you can access the
* application 'app' property inside the initialize and update functions:
*
* ```javascript
* // Editor example: accessing the pc.Application from a script
* var MyScript = pc.createScript('myScript');
*
* MyScript.prototype.initialize = function() {
* // Every script instance has a property 'this.app' accessible in the initialize...
* const app = this.app;
* };
*
* MyScript.prototype.update = function(dt) {
* // ...and update functions.
* const app = this.app;
* };
* ```
*
* If you are using the Engine without the Editor, you have to create the application instance
* manually.
*/
class AppBase extends EventHandler {
/**
* The application's batch manager.
*
* @type {BatchManager|null}
* @private
*/
_batcher = null;
/** @private */
_destroyRequested = false;
/** @private */
_inFrameUpdate = false;
/** @private */
_librariesLoaded = false;
/** @private */
_fillMode = FILLMODE_KEEP_ASPECT;
/** @private */
_resolutionMode = RESOLUTION_FIXED;
/** @private */
_allowResize = true;
/**
* @type {Asset|null}
* @private
*/
_skyboxAsset = null;
/**
* @type {SoundManager}
* @private
*/
_soundManager;
/** @private */
_visibilityChangeHandler;
/**
* Stores all entities that have been created for this app by guid.
*
* @type {Object<string, Entity>}
* @ignore
*/
_entityIndex = {};
/**
* @type {boolean}
* @ignore
*/
_inTools = false;
/**
* @type {string}
* @ignore
*/
_scriptPrefix = '';
/** @ignore */
_time = 0;
/**
* Set this to false if you want to run without using bundles. We set it to true only if
* TextDecoder is available because we currently rely on it for untarring.
*
* @type {boolean}
* @ignore
*/
enableBundles = (typeof TextDecoder !== 'undefined');
/**
* A request id returned by requestAnimationFrame, allowing us to cancel it.
*
* @ignore
*/
frameRequestId;
/**
* Scales the global time delta. Defaults to 1.
*
* @type {number}
* @example
* // Set the app to run at half speed
* this.app.timeScale = 0.5;
*/
timeScale = 1;
/**
* Clamps per-frame delta time to an upper bound. Useful since returning from a tab
* deactivation can generate huge values for dt, which can adversely affect game state.
* Defaults to 0.1 (seconds).
*
* @type {number}
* @example
* // Don't clamp inter-frame times of 200ms or less
* this.app.maxDeltaTime = 0.2;
*/
maxDeltaTime = 0.1; // Maximum delta is 0.1s or 10 fps.
/**
* The total number of frames the application has updated since start() was called.
*
* @type {number}
* @ignore
*/
frame = 0;
/**
* The frame graph.
*
* @type {FrameGraph}
* @ignore
*/
frameGraph = new FrameGraph();
/**
* The forward renderer.
*
* @type {ForwardRenderer}
* @ignore
*/
renderer;
/**
* Scripts in order of loading first.
*
* @type {string[]}
*/
scriptsOrder = [];
/**
* The application's performance stats.
*
* @type {ApplicationStats}
* @ignore
*/
stats;
/**
* When true, the application's render function is called every frame. Setting autoRender to
* false is useful to applications where the rendered image may often be unchanged over time.
* This can heavily reduce the application's load on the CPU and GPU. Defaults to true.
*
* @type {boolean}
* @example
* // Disable rendering every frame and only render on a keydown event
* this.app.autoRender = false;
* this.app.keyboard.on('keydown', (event) => {
* this.app.renderNextFrame = true;
* });
*/
autoRender = true;
/**
* Set to true to render the scene on the next iteration of the main loop. This only has an
* effect if {@link AppBase#autoRender} is set to false. The value of renderNextFrame is set
* back to false again as soon as the scene has been rendered.
*
* @type {boolean}
* @example
* // Render the scene only while space key is pressed
* if (this.app.keyboard.isPressed(pc.KEY_SPACE)) {
* this.app.renderNextFrame = true;
* }
*/
renderNextFrame = false;
/**
* The graphics device used by the application.
*
* @type {GraphicsDevice}
*/
graphicsDevice;
/**
* The root entity of the application.
*
* @type {Entity}
* @example
* // Return the first entity called 'Camera' in a depth-first search of the scene hierarchy
* const camera = this.app.root.findByName('Camera');
*/
root;
/**
* The scene managed by the application.
*
* @type {Scene}
* @example
* // Set the tone mapping property of the application's scene
* this.app.scene.rendering.toneMapping = pc.TONEMAP_FILMIC;
*/
scene;
/**
* The run-time lightmapper.
*
* @type {Lightmapper|null}
*/
lightmapper = null;
/**
* The resource loader.
*
* @type {ResourceLoader}
*/
loader = new ResourceLoader(this);
/**
* The asset registry managed by the application.
*
* @type {AssetRegistry}
* @example
* // Search the asset registry for all assets with the tag 'vehicle'
* const vehicleAssets = this.app.assets.findByTag('vehicle');
*/
assets;
/**
* The bundle registry managed by the application.
*
* @type {BundleRegistry}
* @ignore
*/
bundles;
/**
* The scene registry managed by the application.
*
* @type {SceneRegistry}
* @example
* // Search the scene registry for a item with the name 'racetrack1'
* const sceneItem = this.app.scenes.find('racetrack1');
*
* // Load the scene using the item's url
* this.app.scenes.loadScene(sceneItem.url);
*/
scenes = new SceneRegistry(this);
/**
* The application's script registry.
*
* @type {ScriptRegistry}
*/
scripts = new ScriptRegistry(this);
/**
* The application's component system registry.
*
* @type {ComponentSystemRegistry}
* @example
* // Set global gravity to zero
* this.app.systems.rigidbody.gravity.set(0, 0, 0);
* @example
* // Set the global sound volume to 50%
* this.app.systems.sound.volume = 0.5;
*/
systems = new ComponentSystemRegistry();
/**
* Handles localization.
*
* @type {I18n}
*/
i18n = new I18n(this);
/**
* The keyboard device.
*
* @type {Keyboard|null}
*/
keyboard = null;
/**
* The mouse device.
*
* @type {Mouse|null}
*/
mouse = null;
/**
* Used to get touch events input.
*
* @type {TouchDevice|null}
*/
touch = null;
/**
* Used to access GamePad input.
*
* @type {GamePads|null}
*/
gamepads = null;
/**
* Used to handle input for {@link ElementComponent}s.
*
* @type {ElementInput|null}
*/
elementInput = null;
/**
* The XR Manager that provides ability to start VR/AR sessions.
*
* @type {XrManager|null}
* @example
* // check if VR is available
* if (app.xr.isAvailable(pc.XRTYPE_VR)) {
* // VR is available
* }
*/
xr = null;
/**
* Create a new AppBase instance.
*
* @param {HTMLCanvasElement} canvas - The canvas element.
* @example
* // Engine-only example: create the application manually
* const options = new AppOptions();
* const app = new pc.AppBase(canvas);
* app.init(options);
*
* // Start the application's main loop
* app.start();
*/
constructor(canvas) {
super();
// #if _DEBUG
if (version?.indexOf('$') < 0) {
Debug.log(`Powered by PlayCanvas ${version} ${revision}`);
}
// #endif
// Store application instance
AppBase._applications[canvas.id] = this;
setApplication(this);
app = this;
this.root = new Entity();
this.root._enabledInHierarchy = true;
}
/**
* Initialize the app.
*
* @param {AppOptions} appOptions - Options specifying the init parameters for the app.
*/
init(appOptions) {
const {
assetPrefix, batchManager, componentSystems, elementInput, gamepads, graphicsDevice, keyboard,
lightmapper, mouse, resourceHandlers, scriptsOrder, scriptPrefix, soundManager, touch, xr
} = appOptions;
Debug.assert(graphicsDevice, 'The application cannot be created without a valid GraphicsDevice');
this.graphicsDevice = graphicsDevice;
this._initDefaultMaterial();
this._initProgramLibrary();
this.stats = new ApplicationStats(graphicsDevice);
this._soundManager = soundManager;
this.scene = new Scene(graphicsDevice);
this._registerSceneImmediate(this.scene);
this.assets = new AssetRegistry(this.loader);
if (assetPrefix) this.assets.prefix = assetPrefix;
this.bundles = new BundleRegistry(this.assets);
this.scriptsOrder = scriptsOrder || [];
this.defaultLayerWorld = new Layer({ name: 'World', id: LAYERID_WORLD });
this.defaultLayerDepth = new Layer({ name: 'Depth', id: LAYERID_DEPTH, enabled: false, opaqueSortMode: SORTMODE_NONE });
this.defaultLayerSkybox = new Layer({ name: 'Skybox', id: LAYERID_SKYBOX, opaqueSortMode: SORTMODE_NONE });
this.defaultLayerUi = new Layer({ name: 'UI', id: LAYERID_UI, transparentSortMode: SORTMODE_MANUAL });
this.defaultLayerImmediate = new Layer({ name: 'Immediate', id: LAYERID_IMMEDIATE, opaqueSortMode: SORTMODE_NONE });
const defaultLayerComposition = new LayerComposition('default');
defaultLayerComposition.pushOpaque(this.defaultLayerWorld);
defaultLayerComposition.pushOpaque(this.defaultLayerDepth);
defaultLayerComposition.pushOpaque(this.defaultLayerSkybox);
defaultLayerComposition.pushTransparent(this.defaultLayerWorld);
defaultLayerComposition.pushOpaque(this.defaultLayerImmediate);
defaultLayerComposition.pushTransparent(this.defaultLayerImmediate);
defaultLayerComposition.pushTransparent(this.defaultLayerUi);
this.scene.layers = defaultLayerComposition;
// Placeholder texture for area light LUTs
AreaLightLuts.createPlaceholder(graphicsDevice);
this.renderer = new ForwardRenderer(graphicsDevice);
this.renderer.scene = this.scene;
if (lightmapper) {
this.lightmapper = new lightmapper(graphicsDevice, this.root, this.scene, this.renderer, this.assets);
this.once('prerender', this._firstBake, this);
}
if (batchManager) {
this._batcher = new batchManager(graphicsDevice, this.root, this.scene);
this.once('prerender', this._firstBatch, this);
}
this.keyboard = keyboard || null;
this.mouse = mouse || null;
this.touch = touch || null;
this.gamepads = gamepads || null;
if (elementInput) {
this.elementInput = elementInput;
this.elementInput.app = this;
}
this.xr = xr ? new xr(this) : null;
if (this.elementInput) this.elementInput.attachSelectEvents();
this._scriptPrefix = scriptPrefix || '';
if (this.enableBundles) {
this.loader.addHandler('bundle', new BundleHandler(this));
}
// Create and register all required resource handlers
resourceHandlers.forEach((resourceHandler) => {
const handler = new resourceHandler(this);
this.loader.addHandler(handler.handlerType, handler);
});
// Create and register all required component systems
componentSystems.forEach((componentSystem) => {
this.systems.add(new componentSystem(this));
});
this._visibilityChangeHandler = this.onVisibilityChange.bind(this);
// Depending on browser add the correct visibilitychange event and store the name of the
// hidden attribute in this._hiddenAttr.
if (typeof document !== 'undefined') {
if (document.hidden !== undefined) {
this._hiddenAttr = 'hidden';
document.addEventListener('visibilitychange', this._visibilityChangeHandler, false);
} else if (document.mozHidden !== undefined) {
this._hiddenAttr = 'mozHidden';
document.addEventListener('mozvisibilitychange', this._visibilityChangeHandler, false);
} else if (document.msHidden !== undefined) {
this._hiddenAttr = 'msHidden';
document.addEventListener('msvisibilitychange', this._visibilityChangeHandler, false);
} else if (document.webkitHidden !== undefined) {
this._hiddenAttr = 'webkitHidden';
document.addEventListener('webkitvisibilitychange', this._visibilityChangeHandler, false);
}
}
// bind tick function to current scope
/* eslint-disable-next-line no-use-before-define */
this.tick = makeTick(this); // Circular linting issue as makeTick and Application reference each other
}
static _applications = {};
/**
* Get the current application. In the case where there are multiple running applications, the
* function can get an application based on a supplied canvas id. This function is particularly
* useful when the current Application is not readily available. For example, in the JavaScript
* console of the browser's developer tools.
*
* @param {string} [id] - If defined, the returned application should use the canvas which has
* this id. Otherwise current application will be returned.
* @returns {AppBase|undefined} The running application, if any.
* @example
* const app = pc.AppBase.getApplication();
*/
static getApplication(id) {
return id ? AppBase._applications[id] : getApplication();
}
/** @private */
_initDefaultMaterial() {
const material = new StandardMaterial();
material.name = 'Default Material';
setDefaultMaterial(this.graphicsDevice, material);
}
/** @private */
_initProgramLibrary() {
const library = new ProgramLibrary(this.graphicsDevice, new StandardMaterial());
setProgramLibrary(this.graphicsDevice, library);
}
/**
* @type {SoundManager}
* @ignore
*/
get soundManager() {
return this._soundManager;
}
/**
* The application's batch manager. The batch manager is used to merge mesh instances in
* the scene, which reduces the overall number of draw calls, thereby boosting performance.
*
* @type {BatchManager}
*/
get batcher() {
Debug.assert(this._batcher, 'BatchManager has not been created and is required for correct functionality.');
return this._batcher;
}
/**
* The current fill mode of the canvas. Can be:
*
* - {@link FILLMODE_NONE}: the canvas will always match the size provided.
* - {@link FILLMODE_FILL_WINDOW}: the canvas will simply fill the window, changing aspect ratio.
* - {@link FILLMODE_KEEP_ASPECT}: the canvas will grow to fill the window as best it can while
* maintaining the aspect ratio.
*
* @type {string}
*/
get fillMode() {
return this._fillMode;
}
/**
* The current resolution mode of the canvas, Can be:
*
* - {@link RESOLUTION_AUTO}: if width and height are not provided, canvas will be resized to
* match canvas client size.
* - {@link RESOLUTION_FIXED}: resolution of canvas will be fixed.
*
* @type {string}
*/
get resolutionMode() {
return this._resolutionMode;
}
/**
* Load the application configuration file and apply application properties and fill the asset
* registry.
*
* @param {string} url - The URL of the configuration file to load.
* @param {ConfigureAppCallback} callback - The Function called when the configuration file is
* loaded and parsed (or an error occurs).
*/
configure(url, callback) {
http.get(url, (err, response) => {
if (err) {
callback(err);
return;
}
const props = response.application_properties;
const scenes = response.scenes;
const assets = response.assets;
this._parseApplicationProperties(props, (err) => {
this._parseScenes(scenes);
this._parseAssets(assets);
if (!err) {
callback(null);
} else {
callback(err);
}
});
});
}
/**
* Load all assets in the asset registry that are marked as 'preload'.
*
* @param {PreloadAppCallback} callback - Function called when all assets are loaded.
*/
preload(callback) {
this.fire('preload:start');
// get list of assets to preload
const assets = this.assets.list({
preload: true
});
if (assets.length === 0) {
this.fire('preload:end');
callback();
return;
}
let loadedCount = 0;
const onAssetLoadOrError = () => {
loadedCount++;
this.fire('preload:progress', loadedCount / assets.length);
if (loadedCount === assets.length) {
this.fire('preload:end');
callback();
}
};
// for each asset
assets.forEach((asset) => {
if (!asset.loaded) {
asset.once('load', onAssetLoadOrError);
asset.once('error', onAssetLoadOrError);
this.assets.load(asset);
} else {
onAssetLoadOrError();
}
});
}
_preloadScripts(sceneData, callback) {
callback();
}
// set application properties from data file
_parseApplicationProperties(props, callback) {
// configure retrying assets
if (typeof props.maxAssetRetries === 'number' && props.maxAssetRetries > 0) {
this.loader.enableRetry(props.maxAssetRetries);
}
// TODO: remove this temporary block after migrating properties
if (!props.useDevicePixelRatio) {
props.useDevicePixelRatio = props.use_device_pixel_ratio;
}
if (!props.resolutionMode) {
props.resolutionMode = props.resolution_mode;
}
if (!props.fillMode) {
props.fillMode = props.fill_mode;
}
this._width = props.width;
this._height = props.height;
if (props.useDevicePixelRatio) {
this.graphicsDevice.maxPixelRatio = window.devicePixelRatio;
}
this.setCanvasResolution(props.resolutionMode, this._width, this._height);
this.setCanvasFillMode(props.fillMode, this._width, this._height);
// set up layers
if (props.layers && props.layerOrder) {
const composition = new LayerComposition('application');
const layers = {};
for (const key in props.layers) {
const data = props.layers[key];
data.id = parseInt(key, 10);
// depth layer should only be enabled when needed
// by incrementing its ref counter
data.enabled = data.id !== LAYERID_DEPTH;
layers[key] = new Layer(data);
}
for (let i = 0, len = props.layerOrder.length; i < len; i++) {
const sublayer = props.layerOrder[i];
const layer = layers[sublayer.layer];
if (!layer) continue;
if (sublayer.transparent) {
composition.pushTransparent(layer);
} else {
composition.pushOpaque(layer);
}
composition.subLayerEnabled[i] = sublayer.enabled;
}
this.scene.layers = composition;
}
// add batch groups
if (props.batchGroups) {
const batcher = this.batcher;
if (batcher) {
for (let i = 0, len = props.batchGroups.length; i < len; i++) {
const grp = props.batchGroups[i];
batcher.addGroup(grp.name, grp.dynamic, grp.maxAabbSize, grp.id, grp.layers);
}
}
}
// set localization assets
if (props.i18nAssets) {
this.i18n.assets = props.i18nAssets;
}
this._loadLibraries(props.libraries, callback);
}
/**
* @param {string[]} urls - List of URLs to load.
* @param {Function} callback - Callback function.
* @private
*/
_loadLibraries(urls, callback) {
const len = urls.length;
let count = len;
const regex = /^https?:\/\//;
if (len) {
const onLoad = (err, script) => {
count--;
if (err) {
callback(err);
} else if (count === 0) {
this.onLibrariesLoaded();
callback(null);
}
};
for (let i = 0; i < len; ++i) {
let url = urls[i];
if (!regex.test(url.toLowerCase()) && this._scriptPrefix) {
url = path.join(this._scriptPrefix, url);
}
this.loader.load(url, 'script', onLoad);
}
} else {
this.onLibrariesLoaded();
callback(null);
}
}
/**
* Insert scene name/urls into the registry.
*
* @param {*} scenes - Scenes to add to the scene registry.
* @private
*/
_parseScenes(scenes) {
if (!scenes) return;
for (let i = 0; i < scenes.length; i++) {
this.scenes.add(scenes[i].name, scenes[i].url);
}
}
/**
* Insert assets into registry.
*
* @param {*} assets - Assets to insert.
* @private
*/
_parseAssets(assets) {
const list = [];
const scriptsIndex = {};
const bundlesIndex = {};
// add scripts in order of loading first
for (let i = 0; i < this.scriptsOrder.length; i++) {
const id = this.scriptsOrder[i];
if (!assets[id]) {
continue;
}
scriptsIndex[id] = true;
list.push(assets[id]);
}
// then add bundles
if (this.enableBundles) {
for (const id in assets) {
if (assets[id].type === 'bundle') {
bundlesIndex[id] = true;
list.push(assets[id]);
}
}
}
// then add rest of assets
for (const id in assets) {
if (scriptsIndex[id] || bundlesIndex[id]) {
continue;
}
list.push(assets[id]);
}
for (let i = 0; i < list.length; i++) {
const data = list[i];
const asset = new Asset(data.name, data.type, data.file, data.data);
asset.id = parseInt(data.id, 10);
asset.preload = data.preload ? data.preload : false;
// if this is a script asset and has already been embedded in the page then
// mark it as loaded
asset.loaded = data.type === 'script' && data.data && data.data.loadingType > 0;
// tags
asset.tags.add(data.tags);
// i18n
if (data.i18n) {
for (const locale in data.i18n) {
asset.addLocalizedAssetId(locale, data.i18n[locale]);
}
}
// registry
this.assets.add(asset);
}
}
/**
* Start the application. This function does the following:
*
* 1. Fires an event on the application named 'start'
* 2. Calls initialize for all components on entities in the hierarchy
* 3. Fires an event on the application named 'initialize'
* 4. Calls postInitialize for all components on entities in the hierarchy
* 5. Fires an event on the application named 'postinitialize'
* 6. Starts executing the main loop of the application
*
* This function is called internally by PlayCanvas applications made in the Editor but you
* will need to call start yourself if you are using the engine stand-alone.
*
* @example
* app.start();
*/
start() {
Debug.call(() => {
Debug.assert(!this._alreadyStarted, 'The application can be started only one time.');
this._alreadyStarted = true;
});
this.frame = 0;
this.fire('start', {
timestamp: now(),
target: this
});
if (!this._librariesLoaded) {
this.onLibrariesLoaded();
}
this.systems.fire('initialize', this.root);
this.fire('initialize');
this.systems.fire('postInitialize', this.root);
this.systems.fire('postPostInitialize', this.root);
this.fire('postinitialize');
this.tick();
}
/**
* Update all input devices managed by the application.
*
* @param {number} dt - The time in seconds since the last update.
* @private
*/
inputUpdate(dt) {
if (this.controller) {
this.controller.update(dt);
}
if (this.mouse) {
this.mouse.update();
}
if (this.keyboard) {
this.keyboard.update();
}