-
-
Notifications
You must be signed in to change notification settings - Fork 191
/
Engine.ts
1502 lines (1308 loc) · 50.1 KB
/
Engine.ts
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 { EX_VERSION } from './';
import { Flags } from './Flags';
import { polyfill } from './Polyfill';
polyfill();
import { CanUpdate, CanDraw, CanInitialize } from './Interfaces/LifecycleEvents';
import { Loadable } from './Interfaces/Loadable';
import { Vector } from './Math/vector';
import { Screen, DisplayMode, ScreenDimension, Resolution } from './Screen';
import { ScreenElement } from './ScreenElement';
import { Actor } from './Actor';
import { Timer } from './Timer';
import { TileMap } from './TileMap';
import { Loader } from './Loader';
import { Detector } from './Util/Detector';
import {
VisibleEvent,
HiddenEvent,
GameStartEvent,
GameStopEvent,
PreUpdateEvent,
PostUpdateEvent,
PreFrameEvent,
PostFrameEvent,
GameEvent,
DeactivateEvent,
ActivateEvent,
PreDrawEvent,
PostDrawEvent,
InitializeEvent
} from './Events';
import { Logger, LogLevel } from './Util/Log';
import { Color } from './Color';
import { Scene } from './Scene';
import { Entity } from './EntityComponentSystem/Entity';
import { Debug, DebugStats } from './Debug/Debug';
import { Class } from './Class';
import * as Input from './Input/Index';
import * as Events from './Events';
import { BrowserEvents } from './Util/Browser';
import { ExcaliburGraphicsContext, ExcaliburGraphicsContext2DCanvas, ExcaliburGraphicsContextWebGL, TextureLoader } from './Graphics';
import { PointerEventReceiver } from './Input/PointerEventReceiver';
import { Clock, StandardClock } from './Util/Clock';
import { ImageFiltering } from './Graphics/Filtering';
import { GraphicsDiagnostics } from './Graphics/GraphicsDiagnostics';
import { Toaster } from './Util/Toaster';
/**
* Enum representing the different mousewheel event bubble prevention
*/
export enum ScrollPreventionMode {
/**
* Do not prevent any page scrolling
*/
None,
/**
* Prevent page scroll if mouse is over the game canvas
*/
Canvas,
/**
* Prevent all page scrolling via mouse wheel
*/
All
}
/**
* Defines the available options to configure the Excalibur engine at constructor time.
*/
export interface EngineOptions {
/**
* Optionally configure the width of the viewport in css pixels
*/
width?: number;
/**
* Optionally configure the height of the viewport in css pixels
*/
height?: number;
/**
* Optionally configure the width & height of the viewport in css pixels.
* Use `viewport` instead of [[EngineOptions.width]] and [[EngineOptions.height]], or vice versa.
*/
viewport?: ScreenDimension;
/**
* Optionally specify the size the logical pixel resolution, if not specified it will be width x height.
* See [[Resolution]] for common presets.
*/
resolution?: ScreenDimension;
/**
* Optionally specify antialiasing (smoothing), by default true (smooth pixels)
*
* * `true` - useful for high resolution art work you would like smoothed, this also hints excalibur to load images
* with [[ImageFiltering.Blended]]
*
* * `false` - useful for pixel art style art work you would like sharp, this also hints excalibur to load images
* with [[ImageFiltering.Pixel]]
*/
antialiasing?: boolean;
/**
* Optionally upscale the number of pixels in the canvas. Normally only useful if you need a smoother look to your assets, especially
* [[Text]].
*
* **WARNING** It is recommended you try using `antialiasing: true` before adjusting pixel ratio. Pixel ratio will consume more memory
* and on mobile may break if the internal size of the canvas exceeds 4k pixels in width or height.
*
* Default is based the display's pixel ratio, for example a HiDPI screen might have the value 2;
*/
pixelRatio?: number;
/**
* Optionally configure the native canvas transparent backdrop
*/
enableCanvasTransparency?: boolean;
/**
* Optionally specify the target canvas DOM element to render the game in
*/
canvasElementId?: string;
/**
* Optionally specify the target canvas DOM element directly
*/
canvasElement?: HTMLCanvasElement;
/**
* Optionally snap graphics to nearest pixel, default is false
*/
snapToPixel?: boolean;
/**
* The [[DisplayMode]] of the game, by default [[DisplayMode.FitScreen]] with aspect ratio 4:3 (800x600).
* Depending on this value, [[width]] and [[height]] may be ignored.
*/
displayMode?: DisplayMode;
/**
* Configures the pointer scope. Pointers scoped to the 'Canvas' can only fire events within the canvas viewport; whereas, 'Document'
* (default) scoped will fire anywhere on the page.
*/
pointerScope?: Input.PointerScope;
/**
* Suppress boot up console message, which contains the "powered by Excalibur message"
*/
suppressConsoleBootMessage?: boolean;
/**
* Suppress minimum browser feature detection, it is not recommended users of excalibur switch this off. This feature ensures that
* the currently running browser meets the minimum requirements for running excalibur. This can be useful if running on non-standard
* browsers or if there is a bug in excalibur preventing execution.
*/
suppressMinimumBrowserFeatureDetection?: boolean;
/**
* Suppress HiDPI auto detection and scaling, it is not recommended users of excalibur switch off this feature. This feature detects
* and scales the drawing canvas appropriately to accommodate HiDPI screens.
*/
suppressHiDPIScaling?: boolean;
/**
* Suppress play button, it is not recommended users of excalibur switch this feature. Some browsers require a user gesture (like a click)
* for certain browser features to work like web audio.
*/
suppressPlayButton?: boolean;
/**
* Scroll prevention method.
*/
scrollPreventionMode?: ScrollPreventionMode;
/**
* Optionally set the background color
*/
backgroundColor?: Color;
/**
* Optionally set the maximum fps if not set Excalibur will go as fast as the device allows.
*
* You may want to constrain max fps if your game cannot maintain fps consistently, it can look and feel better to have a 30fps game than
* one that bounces between 30fps and 60fps
*/
maxFps?: number;
/**
* Optionally configure a fixed update fps, this can be desireable if you need the physics simulation to be very stable. When set
* the update step and physics will use the same elapsed time for each tick even if the graphical framerate drops. In order for the
* simulation to be correct, excalibur will run multiple updates in a row (at the configured update elapsed) to catch up, for example
* there could be X updates and 1 draw each clock step.
*
* **NOTE:** This does come at a potential perf cost because each catch-up update will need to be run if the fixed rate is greater than
* the current instantaneous framerate, or perf gain if the fixed rate is less than the current framerate.
*
* By default is unset and updates will use the current instantaneous framerate with 1 update and 1 draw each clock step.
*/
fixedUpdateFps?: number
/**
* Default `true`, optionally configure excalibur to use optimal draw call sorting, to opt out set this to `false`.
*
* Excalibur will automatically sort draw calls by z and priority into renderer batches for maximal draw performance,
* this can disrupt a specific desired painter order.
*/
useDrawSorting?: boolean;
/**
* Optionally configure how excalibur handles poor performance on a player's browser
*/
configurePerformanceCanvas2DFallback?: {
/**
* By default `true`, this will switch the internal graphics context to Canvas2D which can improve performance on non hardware
* accelerated browsers.
*/
allow: boolean;
/**
* By default `false`, if set to `true` a dialogue will be presented to the player about their browser and how to potentially
* address any issues.
*/
showPlayerMessage?: boolean;
/**
* Default `{ numberOfFrames: 100, fps: 20 }`, optionally configure excalibur to fallback to the 2D Canvas renderer
* if bad performance is detected.
*
* In this example of the default if excalibur is running at 20fps or less for 100 frames it will trigger the fallback to the 2D
* Canvas renderer.
*/
threshold?: { numberOfFrames: number, fps: number };
}
}
/**
* The Excalibur Engine
*
* The [[Engine]] is the main driver for a game. It is responsible for
* starting/stopping the game, maintaining state, transmitting events,
* loading resources, and managing the scene.
*/
export class Engine extends Class implements CanInitialize, CanUpdate, CanDraw {
/**
* Excalibur browser events abstraction used for wiring to native browser events safely
*/
public browser: BrowserEvents;
/**
* Screen abstraction
*/
public screen: Screen;
/**
* Direct access to the engine's canvas element
*/
public canvas: HTMLCanvasElement;
/**
* Direct access to the ExcaliburGraphicsContext used for drawing things to the screen
*/
public graphicsContext: ExcaliburGraphicsContext;
/**
* Direct access to the canvas element ID, if an ID exists
*/
public canvasElementId: string;
/**
* Optionally set the maximum fps if not set Excalibur will go as fast as the device allows.
*
* You may want to constrain max fps if your game cannot maintain fps consistently, it can look and feel better to have a 30fps game than
* one that bounces between 30fps and 60fps
*/
public maxFps: number = Number.POSITIVE_INFINITY;
/**
* Optionally configure a fixed update fps, this can be desireable if you need the physics simulation to be very stable. When set
* the update step and physics will use the same elapsed time for each tick even if the graphical framerate drops. In order for the
* simulation to be correct, excalibur will run multiple updates in a row (at the configured update elapsed) to catch up, for example
* there could be X updates and 1 draw each clock step.
*
* **NOTE:** This does come at a potential perf cost because each catch-up update will need to be run if the fixed rate is greater than
* the current instantaneous framerate, or perf gain if the fixed rate is less than the current framerate.
*
* By default is unset and updates will use the current instantaneous framerate with 1 update and 1 draw each clock step.
*/
public fixedUpdateFps?: number;
/**
* Direct access to the excalibur clock
*/
public clock: Clock;
/**
* The width of the game canvas in pixels (physical width component of the
* resolution of the canvas element)
*/
public get canvasWidth(): number {
return this.screen.canvasWidth;
}
/**
* Returns half width of the game canvas in pixels (half physical width component)
*/
public get halfCanvasWidth(): number {
return this.screen.halfCanvasWidth;
}
/**
* The height of the game canvas in pixels, (physical height component of
* the resolution of the canvas element)
*/
public get canvasHeight(): number {
return this.screen.canvasHeight;
}
/**
* Returns half height of the game canvas in pixels (half physical height component)
*/
public get halfCanvasHeight(): number {
return this.screen.halfCanvasHeight;
}
/**
* Returns the width of the engine's visible drawing surface in pixels including zoom and device pixel ratio.
*/
public get drawWidth(): number {
return this.screen.drawWidth;
}
/**
* Returns half the width of the engine's visible drawing surface in pixels including zoom and device pixel ratio.
*/
public get halfDrawWidth(): number {
return this.screen.halfDrawWidth;
}
/**
* Returns the height of the engine's visible drawing surface in pixels including zoom and device pixel ratio.
*/
public get drawHeight(): number {
return this.screen.drawHeight;
}
/**
* Returns half the height of the engine's visible drawing surface in pixels including zoom and device pixel ratio.
*/
public get halfDrawHeight(): number {
return this.screen.halfDrawHeight;
}
/**
* Returns whether excalibur detects the current screen to be HiDPI
*/
public get isHiDpi(): boolean {
return this.screen.isHiDpi;
}
/**
* Access engine input like pointer, keyboard, or gamepad
*/
public input: Input.EngineInput;
/**
* Access Excalibur debugging functionality.
*
* Useful when you want to debug different aspects of built in engine features like
* * Transform
* * Graphics
* * Colliders
*/
public debug: Debug;
/**
* Access [[stats]] that holds frame statistics.
*/
public get stats(): DebugStats {
return this.debug.stats;
}
/**
* The current [[Scene]] being drawn and updated on screen
*/
public currentScene: Scene;
/**
* The default [[Scene]] of the game, use [[Engine.goToScene]] to transition to different scenes.
*/
public readonly rootScene: Scene;
/**
* Contains all the scenes currently registered with Excalibur
*/
public readonly scenes: { [key: string]: Scene } = {};
/**
* Indicates whether the engine is set to fullscreen or not
*/
public get isFullscreen(): boolean {
return this.screen.isFullScreen;
}
/**
* Indicates the current [[DisplayMode]] of the engine.
*/
public get displayMode(): DisplayMode {
return this.screen.displayMode;
}
private _suppressPlayButton: boolean = false;
/**
* Returns the calculated pixel ration for use in rendering
*/
public get pixelRatio(): number {
return this.screen.pixelRatio;
}
/**
* Indicates whether audio should be paused when the game is no longer visible.
*/
public pauseAudioWhenHidden: boolean = true;
/**
* Indicates whether the engine should draw with debug information
*/
private _isDebug: boolean = false;
public get isDebug(): boolean {
return this._isDebug;
}
/**
* Sets the background color for the engine.
*/
public backgroundColor: Color;
/**
* Sets the Transparency for the engine.
*/
public enableCanvasTransparency: boolean = true;
/**
* Hints the graphics context to truncate fractional world space coordinates
*/
public get snapToPixel(): boolean {
return this.graphicsContext.snapToPixel;
};
public set snapToPixel(shouldSnapToPixel: boolean) {
this.graphicsContext.snapToPixel = shouldSnapToPixel;
};
/**
* The action to take when a fatal exception is thrown
*/
public onFatalException = (e: any) => {
Logger.getInstance().fatal(e);
};
/**
* The mouse wheel scroll prevention mode
*/
public pageScrollPreventionMode: ScrollPreventionMode;
private _logger: Logger;
private _toaster: Toaster = new Toaster();
// this determines whether excalibur is compatible with your browser
private _compatible: boolean;
private _timescale: number = 1.0;
// loading
private _loader: Loader;
private _isInitialized: boolean = false;
private _deferredGoTo: string = null;
public on(eventName: 'fallbackgraphicscontext', handler: (event: ExcaliburGraphicsContext2DCanvas) => void): void;
public on(eventName: Events.initialize, handler: (event: Events.InitializeEvent<Engine>) => void): void;
public on(eventName: Events.visible, handler: (event: VisibleEvent) => void): void;
public on(eventName: Events.hidden, handler: (event: HiddenEvent) => void): void;
public on(eventName: Events.start, handler: (event: GameStartEvent) => void): void;
public on(eventName: Events.stop, handler: (event: GameStopEvent) => void): void;
public on(eventName: Events.preupdate, handler: (event: PreUpdateEvent<Engine>) => void): void;
public on(eventName: Events.postupdate, handler: (event: PostUpdateEvent<Engine>) => void): void;
public on(eventName: Events.preframe, handler: (event: PreFrameEvent) => void): void;
public on(eventName: Events.postframe, handler: (event: PostFrameEvent) => void): void;
public on(eventName: Events.predraw, handler: (event: PreDrawEvent) => void): void;
public on(eventName: Events.postdraw, handler: (event: PostDrawEvent) => void): void;
public on(eventName: string, handler: (event: GameEvent<any>) => void): void;
public on(eventName: string, handler: (event: any) => void): void {
super.on(eventName, handler);
}
public once(eventName: 'fallbackgraphicscontext', handler: (event: ExcaliburGraphicsContext2DCanvas) => void): void;
public once(eventName: Events.initialize, handler: (event: Events.InitializeEvent<Engine>) => void): void;
public once(eventName: Events.visible, handler: (event: VisibleEvent) => void): void;
public once(eventName: Events.hidden, handler: (event: HiddenEvent) => void): void;
public once(eventName: Events.start, handler: (event: GameStartEvent) => void): void;
public once(eventName: Events.stop, handler: (event: GameStopEvent) => void): void;
public once(eventName: Events.preupdate, handler: (event: PreUpdateEvent<Engine>) => void): void;
public once(eventName: Events.postupdate, handler: (event: PostUpdateEvent<Engine>) => void): void;
public once(eventName: Events.preframe, handler: (event: PreFrameEvent) => void): void;
public once(eventName: Events.postframe, handler: (event: PostFrameEvent) => void): void;
public once(eventName: Events.predraw, handler: (event: PreDrawEvent) => void): void;
public once(eventName: Events.postdraw, handler: (event: PostDrawEvent) => void): void;
public once(eventName: string, handler: (event: GameEvent<any>) => void): void;
public once(eventName: string, handler: (event: any) => void): void {
super.once(eventName, handler);
}
public off(eventName: 'fallbackgraphicscontext', handler?: (event: ExcaliburGraphicsContext2DCanvas) => void): void;
public off(eventName: Events.initialize, handler?: (event: Events.InitializeEvent<Engine>) => void): void;
public off(eventName: Events.visible, handler?: (event: VisibleEvent) => void): void;
public off(eventName: Events.hidden, handler?: (event: HiddenEvent) => void): void;
public off(eventName: Events.start, handler?: (event: GameStartEvent) => void): void;
public off(eventName: Events.stop, handler?: (event: GameStopEvent) => void): void;
public off(eventName: Events.preupdate, handler?: (event: PreUpdateEvent<Engine>) => void): void;
public off(eventName: Events.postupdate, handler?: (event: PostUpdateEvent<Engine>) => void): void;
public off(eventName: Events.preframe, handler?: (event: PreFrameEvent) => void): void;
public off(eventName: Events.postframe, handler?: (event: PostFrameEvent) => void): void;
public off(eventName: Events.predraw, handler?: (event: PreDrawEvent) => void): void;
public off(eventName: Events.postdraw, handler?: (event: PostDrawEvent) => void): void;
public off(eventName: string, handler?: (event: GameEvent<any>) => void): void;
public off(eventName: string, handler?: (event: any) => void): void {
super.off(eventName, handler);
}
/**
* Default [[EngineOptions]]
*/
private static _DEFAULT_ENGINE_OPTIONS: EngineOptions = {
width: 0,
height: 0,
enableCanvasTransparency: true,
useDrawSorting: true,
configurePerformanceCanvas2DFallback: {
allow: true,
showPlayerMessage: false,
threshold: { fps: 20, numberOfFrames: 100 }
},
canvasElementId: '',
canvasElement: undefined,
snapToPixel: false,
pointerScope: Input.PointerScope.Canvas,
suppressConsoleBootMessage: null,
suppressMinimumBrowserFeatureDetection: null,
suppressHiDPIScaling: null,
suppressPlayButton: null,
scrollPreventionMode: ScrollPreventionMode.Canvas,
backgroundColor: Color.fromHex('#2185d0') // Excalibur blue
};
private _originalOptions: EngineOptions = {};
public readonly _originalDisplayMode: DisplayMode;
/**
* Creates a new game using the given [[EngineOptions]]. By default, if no options are provided,
* the game will be rendered full screen (taking up all available browser window space).
* You can customize the game rendering through [[EngineOptions]].
*
* Example:
*
* ```js
* var game = new ex.Engine({
* width: 0, // the width of the canvas
* height: 0, // the height of the canvas
* enableCanvasTransparency: true, // the transparencySection of the canvas
* canvasElementId: '', // the DOM canvas element ID, if you are providing your own
* displayMode: ex.DisplayMode.FullScreen, // the display mode
* pointerScope: ex.Input.PointerScope.Document, // the scope of capturing pointer (mouse/touch) events
* backgroundColor: ex.Color.fromHex('#2185d0') // background color of the engine
* });
*
* // call game.start, which is a Promise
* game.start().then(function () {
* // ready, set, go!
* });
* ```
*/
constructor(options?: EngineOptions) {
super();
options = { ...Engine._DEFAULT_ENGINE_OPTIONS, ...options };
this._originalOptions = options;
Flags.freeze();
// Initialize browser events facade
this.browser = new BrowserEvents(window, document);
// Check compatibility
const detector = new Detector();
if (!options.suppressMinimumBrowserFeatureDetection && !(this._compatible = detector.test())) {
const message = document.createElement('div');
message.innerText = 'Sorry, your browser does not support all the features needed for Excalibur';
document.body.appendChild(message);
detector.failedTests.forEach(function (test) {
const testMessage = document.createElement('div');
testMessage.innerText = 'Browser feature missing ' + test;
document.body.appendChild(testMessage);
});
if (options.canvasElementId) {
const canvas = document.getElementById(options.canvasElementId);
if (canvas) {
canvas.parentElement.removeChild(canvas);
}
}
return;
} else {
this._compatible = true;
}
// Use native console API for color fun
// eslint-disable-next-line no-console
if (console.log && !options.suppressConsoleBootMessage) {
// eslint-disable-next-line no-console
console.log(
`%cPowered by Excalibur.js (v${EX_VERSION})`,
'background: #176BAA; color: white; border-radius: 5px; padding: 15px; font-size: 1.5em; line-height: 80px;'
);
// eslint-disable-next-line no-console
console.log('\n\
/| ________________\n\
O|===|* >________________>\n\
\\|');
// eslint-disable-next-line no-console
console.log('Visit', 'http://excaliburjs.com', 'for more information');
}
// Suppress play button
if (options.suppressPlayButton) {
this._suppressPlayButton = true;
}
this._logger = Logger.getInstance();
// If debug is enabled, let's log browser features to the console.
if (this._logger.defaultLevel === LogLevel.Debug) {
detector.logBrowserFeatures();
}
this._logger.debug('Building engine...');
this.canvasElementId = options.canvasElementId;
if (options.canvasElementId) {
this._logger.debug('Using Canvas element specified: ' + options.canvasElementId);
this.canvas = <HTMLCanvasElement>document.getElementById(options.canvasElementId);
} else if (options.canvasElement) {
this._logger.debug('Using Canvas element specified:', options.canvasElement);
this.canvas = options.canvasElement;
} else {
this._logger.debug('Using generated canvas element');
this.canvas = <HTMLCanvasElement>document.createElement('canvas');
}
let displayMode = options.displayMode ?? DisplayMode.Fixed;
if ((options.width && options.height) || options.viewport) {
if (options.displayMode === undefined) {
displayMode = DisplayMode.Fixed;
}
this._logger.debug('Engine viewport is size ' + options.width + ' x ' + options.height);
} else if (!options.displayMode) {
this._logger.debug('Engine viewport is fit');
displayMode = DisplayMode.FitScreen;
}
this._originalDisplayMode = displayMode;
// Canvas 2D fallback can be flagged on
let useCanvasGraphicsContext = Flags.isEnabled('use-canvas-context');
if (!useCanvasGraphicsContext) {
// Attempt webgl first
try {
this.graphicsContext = new ExcaliburGraphicsContextWebGL({
canvasElement: this.canvas,
enableTransparency: this.enableCanvasTransparency,
smoothing: options.antialiasing,
backgroundColor: options.backgroundColor,
snapToPixel: options.snapToPixel,
useDrawSorting: options.useDrawSorting
});
} catch (e) {
this._logger.warn(
`Excalibur could not load webgl for some reason (${(e as Error).message}) and loaded a Canvas 2D fallback. ` +
`Some features of Excalibur will not work in this mode. \n\n` +
'Read more about this issue at https://excaliburjs.com/docs/webgl'
);
// fallback to canvas in case of failure
useCanvasGraphicsContext = true;
}
}
if (useCanvasGraphicsContext) {
this.graphicsContext = new ExcaliburGraphicsContext2DCanvas({
canvasElement: this.canvas,
enableTransparency: this.enableCanvasTransparency,
smoothing: options.antialiasing,
backgroundColor: options.backgroundColor,
snapToPixel: options.snapToPixel,
useDrawSorting: options.useDrawSorting
});
}
this.screen = new Screen({
canvas: this.canvas,
context: this.graphicsContext,
antialiasing: options.antialiasing ?? true,
browser: this.browser,
viewport: options.viewport ?? (options.width && options.height ? { width: options.width, height: options.height } : Resolution.SVGA),
resolution: options.resolution,
displayMode,
pixelRatio: options.suppressHiDPIScaling ? 1 : (options.pixelRatio ?? null)
});
// Set default filtering based on antialiasing
TextureLoader.filtering = options.antialiasing ? ImageFiltering.Blended : ImageFiltering.Pixel;
if (options.backgroundColor) {
this.backgroundColor = options.backgroundColor.clone();
}
this.maxFps = options.maxFps ?? this.maxFps;
this.fixedUpdateFps = options.fixedUpdateFps ?? this.fixedUpdateFps;
this.clock = new StandardClock({
maxFps: this.maxFps,
tick: this._mainloop.bind(this),
onFatalException: (e) => this.onFatalException(e)
});
this.enableCanvasTransparency = options.enableCanvasTransparency;
this._loader = new Loader();
this._loader.wireEngine(this);
this.debug = new Debug(this);
this._initialize(options);
this.rootScene = this.currentScene = new Scene();
this.addScene('root', this.rootScene);
(window as any).___EXCALIBUR_DEVTOOL = this;
}
private _performanceThresholdTriggered = false;
private _fpsSamples: number[] = [];
private _monitorPerformanceThresholdAndTriggerFallback() {
const { allow } = this._originalOptions.configurePerformanceCanvas2DFallback;
let { threshold, showPlayerMessage } = this._originalOptions.configurePerformanceCanvas2DFallback;
if (threshold === undefined) {
threshold = Engine._DEFAULT_ENGINE_OPTIONS.configurePerformanceCanvas2DFallback.threshold;
}
if (showPlayerMessage === undefined) {
showPlayerMessage = Engine._DEFAULT_ENGINE_OPTIONS.configurePerformanceCanvas2DFallback.showPlayerMessage;
}
if (!Flags.isEnabled('use-canvas-context') && allow && this.ready && !this._performanceThresholdTriggered) {
// Calculate Average fps for last X number of frames after start
if (this._fpsSamples.length === threshold.numberOfFrames) {
this._fpsSamples.splice(0, 1);
}
this._fpsSamples.push(this.clock.fpsSampler.fps);
let total = 0;
for (let i = 0; i < this._fpsSamples.length; i++) {
total += this._fpsSamples[i];
}
const average = total / this._fpsSamples.length;
if (this._fpsSamples.length === threshold.numberOfFrames) {
if (average <= threshold.fps) {
this._performanceThresholdTriggered = true;
this._logger.warn(
`Switching to browser 2D Canvas fallback due to performance. Some features of Excalibur will not work in this mode.\n` +
'this might mean your browser doesn\'t have webgl enabled or hardware acceleration is unavailable.\n\n' +
'If in Chrome:\n' +
' * Visit Settings > Advanced > System, and ensure "Use Hardware Acceleration" is checked.\n'+
' * Visit chrome://flags/#ignore-gpu-blocklist and ensure "Override software rendering list" is "enabled"\n' +
'If in Firefox, visit about:config\n' +
' * Ensure webgl.disabled = false\n' +
' * Ensure webgl.force-enabled = true\n' +
' * Ensure layers.acceleration.force-enabled = true\n\n' +
'Read more about this issue at https://excaliburjs.com/docs/performance'
);
if (showPlayerMessage) {
this._toaster.toast(
'Excalibur is encountering performance issues. '+
'It\'s possible that your browser doesn\'t have hardware acceleration enabled. ' +
'Visit [LINK] for more information and potential solutions.',
'https://excaliburjs.com/docs/performance'
);
}
this.useCanvas2DFallback();
this.emit('fallbackgraphicscontext', this.graphicsContext);
}
}
}
}
/**
* Switches the engine's graphics context to the 2D Canvas.
* @warning Some features of Excalibur will not work in this mode.
*/
public useCanvas2DFallback() {
// Swap out the canvas
const newCanvas = this.canvas.cloneNode(false) as HTMLCanvasElement;
this.canvas.parentNode.replaceChild(newCanvas, this.canvas);
this.canvas = newCanvas;
const options = this._originalOptions;
const displayMode = this._originalDisplayMode;
// New graphics context
this.graphicsContext = new ExcaliburGraphicsContext2DCanvas({
canvasElement: this.canvas,
enableTransparency: this.enableCanvasTransparency,
smoothing: options.antialiasing,
backgroundColor: options.backgroundColor,
snapToPixel: options.snapToPixel,
useDrawSorting: options.useDrawSorting
});
// Reset screen
if (this.screen) {
this.screen.dispose();
}
this.screen = new Screen({
canvas: this.canvas,
context: this.graphicsContext,
antialiasing: options.antialiasing ?? true,
browser: this.browser,
viewport: options.viewport ?? (options.width && options.height ? { width: options.width, height: options.height } : Resolution.SVGA),
resolution: options.resolution,
displayMode,
pixelRatio: options.suppressHiDPIScaling ? 1 : (options.pixelRatio ?? null)
});
this.screen.setCurrentCamera(this.currentScene.camera);
// Reset pointers
this.input.pointers.detach();
const pointerTarget = options && options.pointerScope === Input.PointerScope.Document ? document : this.canvas;
this.input.pointers = this.input.pointers.recreate(pointerTarget, this);
this.input.pointers.init();
}
/**
* Returns a BoundingBox of the top left corner of the screen
* and the bottom right corner of the screen.
*/
public getWorldBounds() {
return this.screen.getWorldBounds();
}
/**
* Gets the current engine timescale factor (default is 1.0 which is 1:1 time)
*/
public get timescale() {
return this._timescale;
}
/**
* Sets the current engine timescale factor. Useful for creating slow-motion effects or fast-forward effects
* when using time-based movement.
*/
public set timescale(value: number) {
if (value <= 0) {
Logger.getInstance().error('Cannot set engine.timescale to a value of 0 or less than 0.');
return;
}
this._timescale = value;
}
/**
* Adds a [[Timer]] to the [[currentScene]].
* @param timer The timer to add to the [[currentScene]].
*/
public addTimer(timer: Timer): Timer {
return this.currentScene.addTimer(timer);
}
/**
* Removes a [[Timer]] from the [[currentScene]].
* @param timer The timer to remove to the [[currentScene]].
*/
public removeTimer(timer: Timer): Timer {
return this.currentScene.removeTimer(timer);
}
/**
* Adds a [[Scene]] to the engine, think of scenes in Excalibur as you
* would levels or menus.
*
* @param key The name of the scene, must be unique
* @param scene The scene to add to the engine
*/
public addScene(key: string, scene: Scene) {
if (this.scenes[key]) {
this._logger.warn('Scene', key, 'already exists overwriting');
}
this.scenes[key] = scene;
}
/**
* Removes a [[Scene]] instance from the engine
* @param scene The scene to remove
*/
public removeScene(scene: Scene): void;
/**
* Removes a scene from the engine by key
* @param key The scene key to remove
*/
public removeScene(key: string): void;
/**
* @internal
*/
public removeScene(entity: any): void {
if (entity instanceof Scene) {
// remove scene
for (const key in this.scenes) {
if (this.scenes.hasOwnProperty(key)) {
if (this.scenes[key] === entity) {
delete this.scenes[key];
}
}
}
}
if (typeof entity === 'string') {
// remove scene
delete this.scenes[entity];
}
}
/**
* Adds a [[Scene]] to the engine, think of scenes in Excalibur as you
* would levels or menus.
* @param sceneKey The key of the scene, must be unique
* @param scene The scene to add to the engine
*/
public add(sceneKey: string, scene: Scene): void;
/**
* Adds a [[Timer]] to the [[currentScene]].
* @param timer The timer to add to the [[currentScene]].
*/
public add(timer: Timer): void;
/**
* Adds a [[TileMap]] to the [[currentScene]], once this is done the TileMap
* will be drawn and updated.
*/
public add(tileMap: TileMap): void;
/**
* Adds an actor to the [[currentScene]] of the game. This is synonymous
* to calling `engine.currentScene.add(actor)`.
*
* Actors can only be drawn if they are a member of a scene, and only
* the [[currentScene]] may be drawn or updated.
*
* @param actor The actor to add to the [[currentScene]]
*/
public add(actor: Actor): void;
public add(entity: Entity): void;
/**
* Adds a [[ScreenElement]] to the [[currentScene]] of the game,
* ScreenElements do not participate in collisions, instead the
* remain in the same place on the screen.
* @param screenElement The ScreenElement to add to the [[currentScene]]
*/
public add(screenElement: ScreenElement): void;
public add(entity: any): void {
if (arguments.length === 2) {
this.addScene(<string>arguments[0], <Scene>arguments[1]);
return;
}
if (this._deferredGoTo && this.scenes[this._deferredGoTo]) {
this.scenes[this._deferredGoTo].add(entity);
} else {
this.currentScene.add(entity);
}
}
/**
* Removes a scene instance from the engine
* @param scene The scene to remove
*/
public remove(scene: Scene): void;
/**
* Removes a scene from the engine by key
* @param sceneKey The scene to remove
*/
public remove(sceneKey: string): void;
/**
* Removes a [[Timer]] from the [[currentScene]].