forked from playcanvas/engine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapplication.js
More file actions
1421 lines (1193 loc) · 51.3 KB
/
application.js
File metadata and controls
1421 lines (1193 loc) · 51.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
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
pc.extend(pc, function () {
/**
* @name pc.Application
* @class Default application which performs general setup code and initiates the main game loop.
* @description Create a new Application.
* @param {Element} canvas The canvas element
* @param {Object} options
* @param {pc.Keyboard} [options.keyboard] Keyboard handler for input
* @param {pc.Mouse} [options.mouse] Mouse handler for input
* @param {pc.TouchDevice} [options.touch] TouchDevice handler for input
* @param {pc.GamePads} [options.gamepads] Gamepad handler for input
* @param {String} [options.scriptPrefix] Prefix to apply to script urls before loading
* @param {String} [options.assetPrefix] Prefix to apply to asset urls before loading
* @param {Object} [options.graphicsDeviceOptions] Options object that is passed into the {@link pc.GraphicsDevice} constructor
*
* @example
* // Create application
* var app = new pc.Application(canvas, options);
* // Start game loop
* app.start()
*/
// PROPERTIES
/**
* @name pc.Application#scene
* @type {pc.Scene}
* @description The current {@link pc.Scene}
*/
/**
* @name pc.Application#timeScale
* @type {Number}
* @description Scales the global time delta.
*/
/**
* @name pc.Application#maxDeltaTime
* @type {Number}
* @description 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).
*/
/**
* @name pc.Application#assets
* @type {pc.AssetRegistry}
* @description The assets available to the application.
*/
/**
* @name pc.Application#graphicsDevice
* @type {pc.GraphicsDevice}
* @description The graphics device used by the application.
*/
/**
* @name pc.Application#systems
* @type {pc.ComponentSystemRegistry}
* @description The component systems.
*/
/**
* @name pc.Application#loader
* @type {pc.ResourceLoader}
* @description The resource loader.
*/
/**
* @name pc.Application#root
* @type {pc.Entity}
* @description The root {@link pc.Entity} of the application.
*/
/**
* @name pc.Application#keyboard
* @type {pc.Keyboard}
* @description The keyboard device.
*/
/**
* @name pc.Application#mouse
* @type {pc.Mouse}
* @description The mouse device.
*/
/**
* @name pc.Application#touch
* @type {pc.TouchDevice}
* @description Used to get touch events input.
*/
/**
* @name pc.Application#gamepads
* @type {pc.GamePads}
* @description Used to access GamePad input.
*/
/**
* @name pc.Application#elementInput
* @type {pc.ElementInput}
* @description Used to handle input for {@link pc.ElementComponent}s.
*/
/**
* @name pc.Application#scripts
* @type pc.ScriptRegistry
* @description The Script Registry of the Application
*/
/**
* @name pc.Application#batcher
* @type pc.BatchManager
* @description The Batch Manager of the Application
*/
/**
* @name pc.Application#autoRender
* @type Boolean
* @description When true (the default) the application's render function is called every frame.
*/
/**
* @name pc.Application#renderNextFrame
* @type Boolean
* @description If {@link pc.Application#autoRender} is false, set `app.renderNextFrame` true to force application to render the scene once next frame.
* @example
* // render the scene only while space key is pressed
* if (this.app.keyboard.isPressed(pc.KEY_SPACE)) {
* this.app.renderNextFrame = true;
* }
*/
var Application = function (canvas, options) {
options = options || {};
// Open the log
pc.log.open();
// Add event support
pc.events.attach(this);
// Store application instance
Application._applications[canvas.id] = this;
Application._currentApplication = this;
this._time = 0;
this.timeScale = 1;
this.maxDeltaTime = 0.1; // Maximum delta is 0.1s or 10 fps.
this.autoRender = true;
this.renderNextFrame = false;
this._librariesLoaded = false;
this._fillMode = pc.FILLMODE_KEEP_ASPECT;
this._resolutionMode = pc.RESOLUTION_FIXED;
this._allowResize = true;
// for compatibility
this.context = this;
this.graphicsDevice = new pc.GraphicsDevice(canvas, options.graphicsDeviceOptions);
this.stats = new pc.ApplicationStats(this.graphicsDevice);
this.systems = new pc.ComponentSystemRegistry();
this._audioManager = new pc.SoundManager(options);
this.loader = new pc.ResourceLoader();
this.scene = new pc.Scene();
this.root = new pc.Entity(this);
this.root._enabledInHierarchy = true;
this._enableList = [ ];
this._enableList.size = 0;
this.assets = new pc.AssetRegistry(this.loader);
if (options.assetPrefix) this.assets.prefix = options.assetPrefix;
this.scriptsOrder = options.scriptsOrder || [ ];
this.scripts = new pc.ScriptRegistry(this);
this.renderer = new pc.ForwardRenderer(this.graphicsDevice);
this.lightmapper = new pc.Lightmapper(this.graphicsDevice, this.root, this.scene, this.renderer, this.assets);
this.once('prerender', this._firstBake, this);
this.batcher = new pc.BatchManager(this.graphicsDevice, this.root, this.scene);
this.once('prerender', this._firstBatch, this);
this.keyboard = options.keyboard || null;
this.mouse = options.mouse || null;
this.touch = options.touch || null;
this.gamepads = options.gamepads || null;
this.elementInput = options.elementInput || null;
if (this.elementInput)
this.elementInput.app = this;
this.vr = null;
// you can enable vr here, or in application properties
if (options.vr) {
this._onVrChange(options.vr);
}
this._inTools = false;
this._skyboxLast = 0;
this._scriptPrefix = options.scriptPrefix || '';
this.loader.addHandler("animation", new pc.AnimationHandler());
this.loader.addHandler("model", new pc.ModelHandler(this.graphicsDevice));
this.loader.addHandler("material", new pc.MaterialHandler(this));
this.loader.addHandler("texture", new pc.TextureHandler(this.graphicsDevice, this.assets, this.loader));
this.loader.addHandler("text", new pc.TextHandler());
this.loader.addHandler("json", new pc.JsonHandler());
this.loader.addHandler("audio", new pc.AudioHandler(this._audioManager));
this.loader.addHandler("script", new pc.ScriptHandler(this));
this.loader.addHandler("scene", new pc.SceneHandler(this));
this.loader.addHandler("cubemap", new pc.CubemapHandler(this.graphicsDevice, this.assets, this.loader));
this.loader.addHandler("html", new pc.HtmlHandler());
this.loader.addHandler("css", new pc.CssHandler());
this.loader.addHandler("shader", new pc.ShaderHandler());
this.loader.addHandler("hierarchy", new pc.HierarchyHandler(this));
this.loader.addHandler("scenesettings", new pc.SceneSettingsHandler(this));
this.loader.addHandler("folder", new pc.FolderHandler());
this.loader.addHandler("font", new pc.FontHandler(this.loader));
this.loader.addHandler("binary", new pc.BinaryHandler());
this.loader.addHandler("textureatlas", new pc.TextureAtlasHandler(this.loader));
this.loader.addHandler("sprite", new pc.SpriteHandler(this.assets, this.graphicsDevice));
new pc.RigidBodyComponentSystem(this);
new pc.CollisionComponentSystem(this);
new pc.AnimationComponentSystem(this);
new pc.ModelComponentSystem(this);
new pc.CameraComponentSystem(this);
new pc.LightComponentSystem(this);
if (pc.script.legacy) {
new pc.ScriptLegacyComponentSystem(this);
} else {
new pc.ScriptComponentSystem(this);
}
new pc.AudioSourceComponentSystem(this, this._audioManager);
new pc.SoundComponentSystem(this, this._audioManager);
new pc.AudioListenerComponentSystem(this, this._audioManager);
new pc.ParticleSystemComponentSystem(this);
new pc.ScreenComponentSystem(this);
new pc.ElementComponentSystem(this);
new pc.SpriteComponentSystem(this);
new pc.ZoneComponentSystem(this);
this._visibilityChangeHandler = this.onVisibilityChange.bind(this);
// Depending on browser add the correct visibiltychange event and store the name of the hidden attribute
// in this._hiddenAttr.
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
this.tick = makeTick(this);
};
Application._currentApplication = null;
Application._applications = {};
Application.getApplication = function (id) {
if (id) {
return Application._applications[id];
} else {
return Application._currentApplication;
}
};
// Mini-object used to measure progress of loading sets
var Progress = function (length) {
this.length = length;
this.count = 0;
this.inc = function () {
this.count++;
};
this.done = function () {
return (this.count === this.length);
};
};
Application.prototype = {
/**
* @function
* @name pc.Application#configure
* @description 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 {Function} callback The Function called when the configuration file is loaded and parsed
*/
configure: function (url, callback) {
var self = this;
pc.http.get(url, function (err, response) {
if (err) {
callback(err);
return;
}
var props = response.application_properties;
var assets = response.assets;
self._parseApplicationProperties(props, function (err) {
self._onVrChange(props.vr);
self._parseAssets(assets);
if (!err) {
callback(null);
} else {
callback(err);
}
});
});
},
/**
* @function
* @name pc.Application#preload
* @description Load all assets in the asset registry that are marked as 'preload'
* @param {Function} callback Function called when all assets are loaded
*/
preload: function (callback) {
var self = this;
self.fire("preload:start");
// get list of assets to preload
var assets = this.assets.list({
preload: true
});
var _assets = new Progress(assets.length);
var _done = false;
// check if all loading is done
var done = function () {
// do not proceed if application destroyed
if (!self.graphicsDevice) {
return;
}
if (!_done && _assets.done()) {
_done = true;
self.fire("preload:end");
callback();
}
};
// totals loading progress of assets
var total = assets.length;
var count = function () {
return _assets.count;
};
var i;
if (_assets.length) {
var onAssetLoad = function(asset) {
_assets.inc();
self.fire('preload:progress', count() / total);
if (_assets.done())
done();
};
var onAssetError = function(err, asset) {
_assets.inc();
self.fire('preload:progress', count() / total);
if (_assets.done())
done();
};
// for each asset
for (i = 0; i < assets.length; i++) {
if (!assets[i].loaded) {
assets[i].once('load', onAssetLoad);
assets[i].once('error', onAssetError);
this.assets.load(assets[i]);
} else {
_assets.inc();
self.fire("preload:progress", count() / total);
if (_assets.done())
done();
}
}
} else {
done();
}
},
/**
* @function
* @name pc.Application#loadSceneHierarchy
* @description Load a scene file, create and initialize the Entity hierarchy
* and add the hierarchy to the application root Entity.
* @param {String} url The URL of the scene file. Usually this will be "scene_id.json"
* @param {Function} callback The function to call after loading, passed (err, entity) where err is null if no errors occurred.
* @example
*
* app.loadSceneHierarchy("1000.json", function (err, entity) {
* if (!err) {
* var e = app.root.find("My New Entity");
* } else {
* // error
* }
* }
* });
*/
loadSceneHierarchy: function (url, callback) {
var self = this;
// Because we need to load scripts before we instance the hierarchy (i.e. before we create script components)
// Split loading into load and open
var handler = this.loader.getHandler("hierarchy");
// include asset prefix if present
if (this.assets && this.assets.prefix && !pc.ABSOLUTE_URL.test(url)) {
url = pc.path.join(this.assets.prefix, url);
}
handler.load(url, function (err, data) {
if (err) {
if (callback) callback(err);
return;
}
// called after scripts are preloaded
var _loaded = function () {
var entity = handler.open(url, data);
// clear from cache because this data is modified by entity operations (e.g. destroy)
self.loader.clearCache(url, "hierarchy");
// add to hierarchy
self.root.addChild(entity);
// initialize components
pc.ComponentSystem.initialize(entity);
pc.ComponentSystem.postInitialize(entity);
if (callback) callback(err, entity);
};
// load priority and referenced scripts before opening scene
self._preloadScripts(data, _loaded);
});
},
/**
* @function
* @name pc.Application#loadSceneSettings
* @description Load a scene file and apply the scene settings to the current scene
* @param {String} url The URL of the scene file. Usually this will be "scene_id.json"
* @param {Function} callback The function called after the settings are applied. Passed (err) where err is null if no error occurred.
* @example
* app.loadSceneSettings("1000.json", function (err) {
* if (!err) {
* // success
* } else {
* // error
* }
* }
* });
*/
loadSceneSettings: function (url, callback) {
// include asset prefix if present
if (this.assets && this.assets.prefix && !pc.ABSOLUTE_URL.test(url)) {
url = pc.path.join(this.assets.prefix, url);
}
this.loader.load(url, "scenesettings", function (err, settings) {
if (!err) {
this.applySceneSettings(settings);
if (callback) {
callback(null);
}
} else {
if (callback) {
callback(err);
}
}
}.bind(this));
},
loadScene: function (url, callback) {
var self = this;
var handler = this.loader.getHandler("scene");
// include asset prefix if present
if (this.assets && this.assets.prefix && !pc.ABSOLUTE_URL.test(url)) {
url = pc.path.join(this.assets.prefix, url);
}
handler.load(url, function (err, data) {
if (!err) {
var _loaded = function () {
// parse and create scene
var scene = handler.open(url, data);
// clear scene from cache because we'll destroy it when we load another one
// so data will be invalid
self.loader.clearCache(url, "scene");
self.loader.patch({
resource: scene,
type: "scene"
}, self.assets);
self.root.addChild(scene.root);
// Initialise pack settings
if (self.systems.rigidbody && typeof Ammo !== 'undefined') {
self.systems.rigidbody.setGravity(scene._gravity.x, scene._gravity.y, scene._gravity.z);
}
if (callback) {
callback(null, scene);
}
};
// preload scripts before opening scene
this._preloadScripts(data, _loaded);
} else {
if (callback) {
callback(err);
}
}
}.bind(this));
},
_preloadScripts: function (sceneData, callback) {
if (! pc.script.legacy) {
callback();
return;
}
var self = this;
self.systems.script.preloading = true;
var scripts = this._getScriptReferences(sceneData);
var i = 0, l = scripts.length;
var progress = new Progress(l);
var scriptUrl;
var regex = /^http(s)?:\/\//;
if (l) {
var onLoad = function (err, ScriptType) {
if (err)
console.error(err);
progress.inc();
if (progress.done()) {
self.systems.script.preloading = false;
callback();
}
};
for (i = 0; i < l; i++) {
scriptUrl = scripts[i];
// support absolute URLs (for now)
if (!regex.test(scriptUrl.toLowerCase()) && self._scriptPrefix)
scriptUrl = pc.path.join(self._scriptPrefix, scripts[i]);
this.loader.load(scriptUrl, 'script', onLoad);
}
} else {
self.systems.script.preloading = false;
callback();
}
},
// set application properties from data file
_parseApplicationProperties: function (props, callback) {
// 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;
if (! props.vrPolyfillUrl)
props.vrPolyfillUrl = props.vr_polyfill_url;
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);
// if VR is enabled in the project and there is no native VR support
// load the polyfill
if (props.vr && props.vrPolyfillUrl) {
if (!pc.VrManager.isSupported || pc.platform.android) {
props.libraries.push(props.vrPolyfillUrl);
}
}
// add batch groups
if (props.batchGroups) {
for (var i = 0, len = props.batchGroups.length; i < len; i++) {
var grp = props.batchGroups[i];
this.batcher.addGroup(grp.name, grp.dynamic, grp.maxAabbSize, grp.id);
}
}
this._loadLibraries(props.libraries, callback);
},
_loadLibraries: function (urls, callback) {
var len = urls.length;
var count = len;
var self = this;
var regex = /^http(s)?:\/\//;
if (len) {
var onLoad = function(err, script) {
count--;
if (err) {
callback(err);
} else if (count === 0) {
self.onLibrariesLoaded();
callback(null);
}
};
for (var i = 0; i < len; ++i) {
var url = urls[i];
if (!regex.test(url.toLowerCase()) && self._scriptPrefix)
url = pc.path.join(self._scriptPrefix, url);
this.loader.load(url, 'script', onLoad);
}
} else {
callback(null);
}
},
// insert assets into registry
_parseAssets: function (assets) {
var i, id;
var list = [ ];
var scriptsIndex = { };
if (! pc.script.legacy) {
// add scripts in order of loading first
for (i = 0; i < this.scriptsOrder.length; i++) {
id = this.scriptsOrder[i];
if (! assets[id])
continue;
scriptsIndex[id] = true;
list.push(assets[id]);
}
// then add rest of assets
for (id in assets) {
if (scriptsIndex[id])
continue;
list.push(assets[id]);
}
} else {
for (id in assets)
list.push(assets[id]);
}
for (i = 0; i < list.length; i++) {
var data = list[i];
var asset = new pc.Asset(data.name, data.type, data.file, data.data);
asset.id = parseInt(data.id);
asset.preload = data.preload ? data.preload : false;
// tags
asset.tags.add(data.tags);
// registry
this.assets.add(asset);
}
},
_getScriptReferences: function (scene) {
var i, key;
var priorityScripts = [];
if (scene.settings.priority_scripts) {
priorityScripts = scene.settings.priority_scripts;
}
var _scripts = [];
var _index = {};
// first add priority scripts
for (i = 0; i < priorityScripts.length; i++) {
_scripts.push(priorityScripts[i]);
_index[priorityScripts[i]] = true;
}
// then iterate hierarchy to get referenced scripts
var entities = scene.entities;
for (key in entities) {
if (!entities[key].components.script) {
continue;
}
var scripts = entities[key].components.script.scripts;
for(i = 0; i < scripts.length; i++) {
if (_index[scripts[i].url])
continue;
_scripts.push(scripts[i].url);
_index[scripts[i].url] = true;
}
}
return _scripts;
},
/**
* @function
* @name pc.Application#start
* @description Start the Application updating
*/
start: function () {
this.fire("start", {
timestamp: pc.now(),
target: this
});
if (!this._librariesLoaded) {
this.onLibrariesLoaded();
}
pc.ComponentSystem.initialize(this.root);
this.fire("initialize");
pc.ComponentSystem.postInitialize(this.root);
this.fire("postinitialize");
this.tick();
},
/**
* @function
* @name pc.Application#update
* @description Application specific update method. Override this if you have a custom Application
* @param {Number} dt The time delta since the last frame.
*/
update: function (dt) {
this.graphicsDevice.updateClientRect();
if (this.vr) this.vr.poll();
// #ifdef PROFILER
this.stats.frame.updateStart = pc.now();
// #endif
// Perform ComponentSystem update
if (pc.script.legacy)
pc.ComponentSystem.fixedUpdate(1.0 / 60.0, this._inTools);
pc.ComponentSystem.update(dt, this._inTools);
pc.ComponentSystem.postUpdate(dt, this._inTools);
// fire update event
this.fire("update", dt);
if (this.controller) {
this.controller.update(dt);
}
if (this.mouse) {
this.mouse.update(dt);
}
if (this.keyboard) {
this.keyboard.update(dt);
}
if (this.gamepads) {
this.gamepads.update(dt);
}
// #ifdef PROFILER
this.stats.frame.updateTime = pc.now() - this.stats.frame.updateStart;
// #endif
},
/**
* @function
* @name pc.Application#render
* @description Application specific render method. Override this if you have a custom Application
*/
render: function () {
// #ifdef PROFILER
this.stats.frame.renderStart = pc.now();
// #endif
this.fire("prerender");
var cameras = this.systems.camera.cameras;
var camera = null;
var renderer = this.renderer;
this.root.syncHierarchy();
this.batcher.updateAll();
// render the scene from each camera
for (var i=0,len=cameras.length; i<len; i++) {
camera = cameras[i];
camera.frameBegin();
renderer.render(this.scene, camera.camera);
camera.frameEnd();
}
// #ifdef PROFILER
this.stats.frame.renderTime = pc.now() - this.stats.frame.renderStart;
// #endif
},
_fillFrameStats: function(now, dt, ms) {
// Timing stats
var stats = this.stats.frame;
stats.dt = dt;
stats.ms = ms;
if (now > stats._timeToCountFrames) {
stats.fps = stats._fpsAccum;
stats._fpsAccum = 0;
stats._timeToCountFrames = now + 1000;
} else {
stats._fpsAccum++;
}
// Render stats
stats.cameras = this.renderer._camerasRendered;
stats.materials = this.renderer._materialSwitches;
stats.shaders = this.graphicsDevice._shaderSwitchesPerFrame;
stats.shadowMapUpdates = this.renderer._shadowMapUpdates;
stats.shadowMapTime = this.renderer._shadowMapTime;
stats.depthMapTime = this.renderer._depthMapTime;
stats.forwardTime = this.renderer._forwardTime;
var prims = this.graphicsDevice._primsPerFrame;
stats.triangles = prims[pc.PRIMITIVE_TRIANGLES]/3 +
Math.max(prims[pc.PRIMITIVE_TRISTRIP]-2, 0) +
Math.max(prims[pc.PRIMITIVE_TRIFAN]-2, 0);
stats.cullTime = this.renderer._cullTime;
stats.sortTime = this.renderer._sortTime;
stats.skinTime = this.renderer._skinTime;
stats.morphTime = this.renderer._morphTime;
stats.instancingTime = this.renderer._instancingTime;
stats.otherPrimitives = 0;
for(var i=0; i<prims.length; i++) {
if (i<pc.PRIMITIVE_TRIANGLES) {
stats.otherPrimitives += prims[i];
}
prims[i] = 0;
}
this.renderer._camerasRendered = 0;
this.renderer._materialSwitches = 0;
this.renderer._shadowMapUpdates = 0;
this.graphicsDevice._shaderSwitchesPerFrame = 0;
this.renderer._cullTime = 0;
this.renderer._sortTime = 0;
this.renderer._skinTime = 0;
this.renderer._morphTime = 0;
this.renderer._instancingTime = 0;
this.renderer._shadowMapTime = 0;
this.renderer._depthMapTime = 0;
this.renderer._forwardTime = 0;
// Draw call stats
stats = this.stats.drawCalls;
stats.forward = this.renderer._forwardDrawCalls;
stats.depth = this.renderer._depthDrawCalls;
stats.shadow = this.renderer._shadowDrawCalls;
stats.skinned = this.renderer._skinDrawCalls;
stats.immediate = this.renderer._immediateRendered;
stats.instanced = this.renderer._instancedDrawCalls;
stats.removedByInstancing = this.renderer._removedByInstancing;
stats.total = this.graphicsDevice._drawCallsPerFrame;
stats.misc = stats.total - (stats.forward + stats.depth + stats.shadow);
this.renderer._depthDrawCalls = 0;
this.renderer._shadowDrawCalls = 0;
this.renderer._forwardDrawCalls = 0;
this.renderer._skinDrawCalls = 0;
this.renderer._immediateRendered = 0;
this.renderer._instancedDrawCalls = 0;
this.renderer._removedByInstancing = 0;
this.graphicsDevice._drawCallsPerFrame = 0;
this.stats.misc.renderTargetCreationTime = this.graphicsDevice.renderTargetCreationTime;
stats = this.stats.particles;
stats.updatesPerFrame = stats._updatesPerFrame;
stats.frameTime = stats._frameTime;
stats._updatesPerFrame = 0;
stats._frameTime = 0;
},
/**
* @function
* @name pc.Application#setCanvasFillMode
* @description Controls how the canvas fills the window and resizes when the window changes.
* @param {String} mode The mode to use when setting the size of the canvas. Can be:
* <ul>
* <li>pc.FILLMODE_NONE: the canvas will always match the size provided.</li>
* <li>pc.FILLMODE_FILL_WINDOW: the canvas will simply fill the window, changing aspect ratio.</li>
* <li>pc.FILLMODE_KEEP_ASPECT: the canvas will grow to fill the window as best it can while maintaining the aspect ratio.</li>
* </ul>
* @param {Number} [width] The width of the canvas (only used when mode is pc.FILLMODE_NONE).
* @param {Number} [height] The height of the canvas (only used when mode is pc.FILLMODE_NONE).
*/
setCanvasFillMode: function (mode, width, height) {
this._fillMode = mode;
this.resizeCanvas(width, height);
},
/**
* @function
* @name pc.Application#setCanvasResolution
* @description Change the resolution of the canvas, and set the way it behaves when the window is resized
* @param {string} mode The mode to use when setting the resolution. Can be:
* <ul>
* <li>pc.RESOLUTION_AUTO: if width and height are not provided, canvas will be resized to match canvas client size.</li>
* <li>pc.RESOLUTION_FIXED: resolution of canvas will be fixed.</li>
* </ul>
* @param {Number} [width] The horizontal resolution, optional in AUTO mode, if not provided canvas clientWidth is used
* @param {Number} [height] The vertical resolution, optional in AUTO mode, if not provided canvas clientHeight is used
*/
setCanvasResolution: function (mode, width, height) {
this._resolutionMode = mode;
// In AUTO mode the resolution is the same as the canvas size, unless specified
if (mode === pc.RESOLUTION_AUTO && (width === undefined)) {
width = this.graphicsDevice.canvas.clientWidth;
height = this.graphicsDevice.canvas.clientHeight;
}
this.graphicsDevice.resizeCanvas(width, height);
},
/**
* @function
* @name pc.Application#isFullscreen
* @description Returns true if the application is currently running fullscreen
* @returns {Boolean} True if the application is running fullscreen
*/
isFullscreen: function () {
return !!document.fullscreenElement;
},
/**
* @function
* @name pc.Application#enableFullscreen
* @description Request that the browser enters fullscreen mode. This is not available on all browsers.
* Note: Switching to fullscreen can only be initiated by a user action, e.g. in the event hander for a mouse or keyboard input
* @param {Element} [element] The element to display in fullscreen, if element is not provided the application canvas is used
* @param {Function} [success] Function called if the request for fullscreen was successful
* @param {Function} [error] Function called if the request for fullscreen was unsuccessful
* @example
* var button = document.getElementById('my-button');
* button.addEventListener('click', function () {
* app.enableFullscreen(canvas, function () {
* console.log('Now fullscreen');
* }, function () {
* console.log('Something went wrong!');
* });
* }, false);
*/
enableFullscreen: function (element, success, error) {
element = element || this.graphicsDevice.canvas;
// success callback
var s = function () {
success();
document.removeEventListener('fullscreenchange', s);
};
// error callback
var e = function () {
error();
document.removeEventListener('fullscreenerror', e);
};
if (success) {
document.addEventListener('fullscreenchange', s, false);