-
Notifications
You must be signed in to change notification settings - Fork 964
/
Copy pathruntimegame.ts
1420 lines (1287 loc) · 45.6 KB
/
runtimegame.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
/*
* GDevelop JS Platform
* Copyright 2013-2016 Florian Rival ([email protected]). All rights reserved.
* This project is released under the MIT License.
*/
namespace gdjs {
const logger = new gdjs.Logger('Game manager');
const sleep = (ms: float) =>
new Promise((resolve) => setTimeout(resolve, ms));
/** Identify a script file, with its content hash (useful for hot-reloading). */
export type RuntimeGameOptionsScriptFile = {
/** The path for this script file. */
path: string;
/** The hash of the script file content. */
hash: number;
};
const getGlobalResourceNames = (projectData: ProjectData): Array<string> =>
projectData.usedResources.map((resource) => resource.name);
let supportedCompressionMethods: ('cs:gzip' | 'cs:deflate')[] | null = null;
const getSupportedCompressionMethods = (): ('cs:gzip' | 'cs:deflate')[] => {
if (!!supportedCompressionMethods) {
return supportedCompressionMethods;
}
supportedCompressionMethods = [];
try {
// @ts-ignore - We are checking if the CompressionStream is available.
new CompressionStream('gzip');
supportedCompressionMethods.push('cs:gzip');
} catch (e) {}
try {
// @ts-ignore - We are checking if the CompressionStream is available.
new CompressionStream('deflate');
supportedCompressionMethods.push('cs:deflate');
} catch (e) {}
return supportedCompressionMethods;
};
/** Options given to the game at startup. */
export type RuntimeGameOptions = {
/** if true, force fullscreen. */
forceFullscreen?: boolean;
/** if true, game is run as a preview launched from an editor. */
isPreview?: boolean;
/** The name of the external layout to create in the scene at position 0;0. */
injectExternalLayout?: string;
/** Script files, used for hot-reloading. */
scriptFiles?: Array<RuntimeGameOptionsScriptFile>;
/** if true, export is a partial preview without events. */
projectDataOnlyExport?: boolean;
/** if true, preview is launched from GDevelop native mobile app. */
nativeMobileApp?: boolean;
/** The address of the debugger server, to reach out using WebSocket. */
websocketDebuggerServerAddress?: string;
/** The port of the debugger server, to reach out using WebSocket. */
websocketDebuggerServerPort?: string;
/**
* The path to require `@electron/remote` module.
* This is only useful in a preview, where this can't be required from
* `@electron/remote` directly as previews don't have any node_modules.
* On the contrary, a game packaged with Electron as a standalone app
* has its node_modules.
* This can be removed once there are no more dependencies on
* `@electron/remote` in the game engine and extensions.
*/
electronRemoteRequirePath?: string;
/**
* The token to use by the game engine when requiring any resource stored on
* GDevelop Cloud buckets. Note that this is only useful during previews.
*/
gdevelopResourceToken?: string;
/**
* Check if, in some exceptional cases, we allow authentication
* to be done through a iframe.
* This is usually discouraged as the user can't verify that the authentication
* window is a genuine one. It's only to be used in trusted contexts.
*/
allowAuthenticationUsingIframeForPreview?: boolean;
/** If set, the game will send crash reports to GDevelop APIs. */
crashReportUploadLevel?: 'all' | 'exclude-javascript-code-events' | 'none';
/** Arbitrary string explaining in which context the game is being played. */
previewContext?: string;
/** The GDevelop version used to build the game. */
gdevelopVersionWithHash?: string;
/** The template slug that was used to create the project. */
projectTemplateSlug?: string;
/** The source game id that was used to create the project. */
sourceGameId?: string;
/** Any capture that should be done during the preview. */
captureOptions?: CaptureOptions;
/** Message to display to the user during an in-app tutorial. */
inAppTutorialMessageInPreview?: string;
inAppTutorialMessagePositionInPreview?: string;
/**
* If set, this data is used to authenticate automatically when launching the game.
* This is only useful during previews.
*/
playerUsername?: string;
playerId?: string;
playerToken?: string;
/**
* If set, the game should use the specified environment for making calls
* to GDevelop APIs ("dev" = development APIs).
*/
environment?: 'dev';
};
/**
* Represents a game being played.
*/
export class RuntimeGame {
_resourcesLoader: gdjs.ResourceLoader;
_variables: VariablesContainer;
_variablesByExtensionName: Map<string, gdjs.VariablesContainer>;
_data: ProjectData;
_sceneAndExtensionsData: Array<SceneAndExtensionsData> = [];
_eventsBasedObjectDatas: Map<String, EventsBasedObjectData>;
_effectsManager: EffectsManager;
_maxFPS: integer;
_minFPS: integer;
_gameResolutionWidth: integer;
_gameResolutionHeight: integer;
_originalWidth: float;
_originalHeight: float;
_resizeMode: 'adaptWidth' | 'adaptHeight' | string;
_adaptGameResolutionAtRuntime: boolean;
_scaleMode: 'linear' | 'nearest';
_pixelsRounding: boolean;
_antialiasingMode: 'none' | 'MSAA';
_isAntialisingEnabledOnMobile: boolean;
/**
* Game loop management (see startGameLoop method)
*/
_renderer: RuntimeGameRenderer;
_sessionId: string | null;
_playerId: string | null;
_watermark: watermark.RuntimeWatermark;
_sceneStack: SceneStack;
/**
* When set to true, the scenes are notified that game resolution size changed.
*/
_notifyScenesForGameResolutionResize: boolean = false;
/**
* When paused, the game won't step and will be freezed. Useful for debugging.
*/
_paused: boolean = false;
/**
* True during the first frame the game is back from being hidden.
* This has nothing to do with `_paused`.
*/
_hasJustResumed: boolean = false;
//Inputs :
_inputManager: InputManager;
/**
* Allow to specify an external layout to insert in the first scene.
*/
_injectExternalLayout: any;
_options: RuntimeGameOptions;
/**
* The mappings for embedded resources
*/
_embeddedResourcesMappings: Map<string, Record<string, string>>;
/**
* Optional client to connect to a debugger server.
*/
_debuggerClient: gdjs.AbstractDebuggerClient | null;
_sessionMetricsInitialized: boolean = false;
_disableMetrics: boolean = false;
_isPreview: boolean;
/**
* The capture manager, used to manage captures (screenshots, videos, etc...).
*/
_captureManager: CaptureManager | null;
/** True if the RuntimeGame has been disposed and should not be used anymore. */
_wasDisposed: boolean = false;
/**
* @param data The object (usually stored in data.json) containing the full project data
* @param options The game options
*/
constructor(data: ProjectData, options?: RuntimeGameOptions) {
this._options = options || {};
this._variables = new gdjs.VariablesContainer(data.variables);
this._variablesByExtensionName = new Map<
string,
gdjs.VariablesContainer
>();
for (const extensionData of data.eventsFunctionsExtensions) {
if (extensionData.globalVariables.length > 0) {
this._variablesByExtensionName.set(
extensionData.name,
new gdjs.VariablesContainer(extensionData.globalVariables)
);
}
}
this._eventsBasedObjectDatas = new Map<String, EventsBasedObjectData>();
this._data = data;
this._updateSceneAndExtensionsData();
this._resourcesLoader = new gdjs.ResourceLoader(
this,
data.resources.resources,
getGlobalResourceNames(data),
data.layouts
);
this._effectsManager = new gdjs.EffectsManager();
this._maxFPS = this._data.properties.maxFPS;
this._minFPS = this._data.properties.minFPS;
this._gameResolutionWidth = this._data.properties.windowWidth;
this._gameResolutionHeight = this._data.properties.windowHeight;
this._originalWidth = this._gameResolutionWidth;
this._originalHeight = this._gameResolutionHeight;
this._resizeMode = this._data.properties.sizeOnStartupMode;
this._adaptGameResolutionAtRuntime =
this._data.properties.adaptGameResolutionAtRuntime;
this._scaleMode = data.properties.scaleMode || 'linear';
this._pixelsRounding = this._data.properties.pixelsRounding;
this._antialiasingMode = this._data.properties.antialiasingMode;
this._isAntialisingEnabledOnMobile =
this._data.properties.antialisingEnabledOnMobile;
this._renderer = new gdjs.RuntimeGameRenderer(
this,
this._options.forceFullscreen || false
);
this._watermark = new gdjs.watermark.RuntimeWatermark(
this,
data.properties.authorUsernames,
this._data.properties.watermark
);
this._sceneStack = new gdjs.SceneStack(this);
this._inputManager = new gdjs.InputManager();
this._injectExternalLayout = this._options.injectExternalLayout || '';
this._debuggerClient = gdjs.DebuggerClient
? new gdjs.DebuggerClient(this)
: null;
this._captureManager = gdjs.CaptureManager
? new gdjs.CaptureManager(
this._renderer,
this._options.captureOptions || {}
)
: null;
this._isPreview = this._options.isPreview || false;
this._sessionId = null;
this._playerId = null;
this._embeddedResourcesMappings = new Map();
for (const resource of this._data.resources.resources) {
if (resource.metadata) {
try {
const metadata = JSON.parse(resource.metadata);
if (metadata?.embeddedResourcesMapping) {
this._embeddedResourcesMappings.set(
resource.name,
metadata.embeddedResourcesMapping
);
}
} catch {
logger.error(
'Some metadata of resources can not be successfully parsed.'
);
}
}
}
if (this.isUsingGDevelopDevelopmentEnvironment()) {
logger.info(
'This game will run on the development version of GDevelop APIs.'
);
}
}
/**
* Update the project data. Useful for hot-reloading, should not be used otherwise.
*
* @param projectData The object (usually stored in data.json) containing the full project data
*/
setProjectData(projectData: ProjectData): void {
this._data = projectData;
this._updateSceneAndExtensionsData();
this._resourcesLoader.setResources(
projectData.resources.resources,
getGlobalResourceNames(projectData),
projectData.layouts
);
}
private _updateSceneAndExtensionsData(): void {
const usedExtensionsWithVariablesData =
this._data.eventsFunctionsExtensions.filter(
(extensionData) => extensionData.sceneVariables.length > 0
);
this._sceneAndExtensionsData = this._data.layouts.map((sceneData) => ({
sceneData,
usedExtensionsWithVariablesData,
}));
this._eventsBasedObjectDatas.clear();
if (this._data.eventsFunctionsExtensions) {
for (const extension of this._data.eventsFunctionsExtensions) {
for (const eventsBasedObject of extension.eventsBasedObjects) {
this._eventsBasedObjectDatas.set(
extension.name + '::' + eventsBasedObject.name,
eventsBasedObject
);
}
}
}
}
/**
* Return the additional options passed to the RuntimeGame when created.
* @returns The additional options, if any.
*/
getAdditionalOptions(): RuntimeGameOptions {
return this._options;
}
getRenderer(): gdjs.RuntimeGameRenderer {
return this._renderer;
}
/**
* Get the variables of the RuntimeGame.
* @return The global variables
*/
getVariables(): gdjs.VariablesContainer {
return this._variables;
}
/**
* Get the extension's global variables.
* @param extensionName The extension name.
* @returns The extension's global variables.
*/
getVariablesForExtension(extensionName: string) {
return this._variablesByExtensionName.get(extensionName) || null;
}
/**
* Get the gdjs.SoundManager of the RuntimeGame.
* @return The sound manager.
*/
getSoundManager(): gdjs.HowlerSoundManager {
return this._resourcesLoader.getSoundManager();
}
/**
* Get the gdjs.ImageManager of the RuntimeGame.
* @return The image manager.
*/
getImageManager(): gdjs.PixiImageManager {
return this._resourcesLoader.getImageManager();
}
/**
* Get the gdjs.FontManager of the RuntimeGame.
* @return The font manager.
*/
getFontManager(): gdjs.FontFaceObserverFontManager {
return this._resourcesLoader.getFontManager();
}
/**
* Get the gdjs.BitmapFontManager of the RuntimeGame.
* @return The bitmap font manager.
*/
getBitmapFontManager(): gdjs.BitmapFontManager {
return this._resourcesLoader.getBitmapFontManager();
}
/**
* Get the JSON manager of the game, used to load JSON from game
* resources.
* @return The json manager for the game
*/
getJsonManager(): gdjs.JsonManager {
return this._resourcesLoader.getJsonManager();
}
/**
* Get the 3D model manager of the game, used to load 3D model from game
* resources.
* @return The 3D model manager for the game
*/
getModel3DManager(): gdjs.Model3DManager {
return this._resourcesLoader.getModel3DManager();
}
/**
* Get the Spine manager of the game, used to load and construct spine skeletons from game
* resources.
* @return The Spine manager for the game
*/
getSpineManager(): gdjs.SpineManager | null {
return this._resourcesLoader.getSpineManager();
}
/**
* Get the Spine Atlas manager of the game, used to load atlases from game
* resources.
* @return The Spine Atlas manager for the game
*/
getSpineAtlasManager(): gdjs.SpineAtlasManager | null {
return this._resourcesLoader.getSpineAtlasManager();
}
/**
* Get the input manager of the game, storing mouse, keyboard
* and touches states.
* @return The input manager owned by the game
*/
getInputManager(): gdjs.InputManager {
return this._inputManager;
}
/**
* Get the effects manager of the game, which allows to manage
* effects on runtime objects or runtime layers.
* @return The effects manager for the game
*/
getEffectsManager(): gdjs.EffectsManager {
return this._effectsManager;
}
/**
* Get the object containing the game data
* @return The object associated to the game.
*/
getGameData(): ProjectData {
return this._data;
}
getEventsBasedObjectData(type: string): EventsBasedObjectData | null {
const eventsBasedObjectData = this._eventsBasedObjectDatas.get(type);
if (!eventsBasedObjectData) {
logger.error(
'The game has no events-based object of the type "' + type + '"'
);
return null;
}
return eventsBasedObjectData;
}
/**
* Get the data associated to a scene.
*
* @param sceneName The name of the scene. If not defined, the first scene will be returned.
* @return The data associated to the scene.
*/
getSceneAndExtensionsData(
sceneName?: string
): SceneAndExtensionsData | null {
for (let i = 0, len = this._sceneAndExtensionsData.length; i < len; ++i) {
const sceneAndExtensionsData = this._sceneAndExtensionsData[i];
if (
sceneName === undefined ||
sceneAndExtensionsData.sceneData.name === sceneName
) {
return sceneAndExtensionsData;
}
}
logger.error('The game has no scene called "' + sceneName + '"');
return null;
}
/**
* Check if a scene exists
*
* @param sceneName The name of the scene to search.
* @return true if the scene exists. If sceneName is undefined, true if the game has a scene.
*/
hasScene(sceneName?: string): boolean {
for (let i = 0, len = this._data.layouts.length; i < len; ++i) {
const sceneData = this._data.layouts[i];
if (sceneName === undefined || sceneData.name == sceneName) {
return true;
}
}
return false;
}
/**
* Get the data associated to an external layout.
*
* @param name The name of the external layout.
* @return The data associated to the external layout or null if not found.
*/
getExternalLayoutData(name: string): ExternalLayoutData | null {
let externalLayout: ExternalLayoutData | null = null;
for (let i = 0, len = this._data.externalLayouts.length; i < len; ++i) {
const layoutData = this._data.externalLayouts[i];
if (layoutData.name === name) {
externalLayout = layoutData;
break;
}
}
return externalLayout;
}
/**
* Get the data representing all the global objects of the game.
* @return The data associated to the global objects.
*/
getInitialObjectsData(): ObjectData[] {
return this._data.objects || [];
}
/**
* Get the original width of the game, as set on the startup of the game.
*
* This is guaranteed to never change, even if the size of the game is changed afterwards.
*/
getOriginalWidth(): float {
return this._originalWidth;
}
/**
* Get the original height of the game, as set on the startup of the game.
*
* This is guaranteed to never change, even if the size of the game is changed afterwards.
*/
getOriginalHeight(): float {
return this._originalHeight;
}
/**
* Get the game resolution (the size at which the game is played and rendered) width.
* @returns The game resolution width, in pixels.
*/
getGameResolutionWidth(): float {
return this._gameResolutionWidth;
}
/**
* Get the game resolution (the size at which the game is played and rendered) height.
* @returns The game resolution height, in pixels.
*/
getGameResolutionHeight(): float {
return this._gameResolutionHeight;
}
/**
* Change the game resolution.
*
* @param width The new width
* @param height The new height
*/
setGameResolutionSize(width: float, height: float): void {
this._throwIfDisposed();
this._gameResolutionWidth = width;
this._gameResolutionHeight = height;
if (this._adaptGameResolutionAtRuntime) {
if (
gdjs.RuntimeGameRenderer &&
gdjs.RuntimeGameRenderer.getWindowInnerWidth &&
gdjs.RuntimeGameRenderer.getWindowInnerHeight
) {
const windowInnerWidth =
gdjs.RuntimeGameRenderer.getWindowInnerWidth();
const windowInnerHeight =
gdjs.RuntimeGameRenderer.getWindowInnerHeight();
// Enlarge either the width or the eight to fill the inner window space.
if (this._resizeMode === 'adaptWidth') {
this._gameResolutionWidth =
(this._gameResolutionHeight * windowInnerWidth) /
windowInnerHeight;
} else if (this._resizeMode === 'adaptHeight') {
this._gameResolutionHeight =
(this._gameResolutionWidth * windowInnerHeight) /
windowInnerWidth;
} else if (this._resizeMode === 'scaleOuter') {
const widthFactor = windowInnerWidth / this._originalWidth;
const heightFactor = windowInnerHeight / this._originalHeight;
if (widthFactor < heightFactor) {
this._gameResolutionWidth = this._originalWidth;
this._gameResolutionHeight = Math.floor(
windowInnerHeight / widthFactor
);
} else {
this._gameResolutionWidth = Math.floor(
windowInnerWidth / heightFactor
);
this._gameResolutionHeight = this._originalHeight;
}
}
}
}
// Don't alter the game resolution. The renderer
// will maybe adapt the size of the canvas or whatever is used to render the
// game in the window, but this does not change the "game resolution".
// Notify the renderer that game resolution changed (so that the renderer size
// can be updated, and maybe other things like the canvas size), and let the
// scenes know too.
this._renderer.updateRendererSize();
this._notifyScenesForGameResolutionResize = true;
}
/**
* Set if the width or the height of the game resolution
* should be changed to fit the game window - or if the game
* resolution should not be updated automatically.
*
* @param resizeMode Either "" (don't change game resolution), "adaptWidth" or "adaptHeight".
*/
setGameResolutionResizeMode(resizeMode: string): void {
this._resizeMode = resizeMode;
this._forceGameResolutionUpdate();
}
/**
* Returns if the width or the height of the game resolution
* should be changed to fit the game window - or if the game
* resolution should not be updated automatically (empty string).
*
* @returns Either "" (don't change game resolution), "adaptWidth" or "adaptHeight".
*/
getGameResolutionResizeMode(): string {
return this._resizeMode;
}
/**
* Set if the game resolution should be automatically adapted
* when the game window or screen size change. This will only
* be the case if the game resolution resize mode is
* configured to adapt the width or the height of the game.
* @param enable true to change the game resolution according to the window/screen size.
*/
setAdaptGameResolutionAtRuntime(enable: boolean): void {
this._adaptGameResolutionAtRuntime = enable;
this._forceGameResolutionUpdate();
}
/**
* Returns if the game resolution should be automatically adapted
* when the game window or screen size change. This will only
* be the case if the game resolution resize mode is
* configured to adapt the width or the height of the game.
* @returns true if the game resolution is automatically changed according to the window/screen size.
*/
getAdaptGameResolutionAtRuntime(): boolean {
return this._adaptGameResolutionAtRuntime;
}
/**
* Return the minimal fps that must be guaranteed by the game
* (otherwise, game is slowed down).
*/
getMinimalFramerate(): integer {
return this._minFPS;
}
/**
* Return the scale mode of the game ("linear" or "nearest").
*/
getScaleMode(): 'linear' | 'nearest' {
return this._scaleMode;
}
/**
* Return if the game is rounding pixels when rendering.
*/
getPixelsRounding(): boolean {
return this._pixelsRounding;
}
/**
* Return the antialiasing mode used by the game ("none" or "MSAA").
*/
getAntialiasingMode(): 'none' | 'MSAA' {
return this._antialiasingMode;
}
/**
* Return true if antialising is enabled on mobiles.
*/
isAntialisingEnabledOnMobile(): boolean {
return this._isAntialisingEnabledOnMobile;
}
/**
* Set or unset the game as paused.
* When paused, the game won't step and will be freezed. Useful for debugging.
* @param enable true to pause the game, false to unpause
*/
pause(enable: boolean) {
if (this._paused === enable) return;
this._paused = enable;
if (this._debuggerClient) {
if (this._paused) this._debuggerClient.sendGamePaused();
else this._debuggerClient.sendGameResumed();
}
}
/**
* @returns true during the first frame the game is back from being hidden.
* This has nothing to do with `_paused`.
*/
hasJustResumed() {
return this._hasJustResumed;
}
/**
* Preload a scene assets as soon as possible in background.
*/
prioritizeLoadingOfScene(sceneName: string) {
// Don't await the scene assets to be loaded.
this._resourcesLoader.loadSceneResources(sceneName);
}
/**
* @return The progress of assets loading in background for a scene
* (between 0 and 1).
*/
getSceneLoadingProgress(sceneName: string): number {
return this._resourcesLoader.getSceneLoadingProgress(sceneName);
}
/**
* @returns true when all the resources of the given scene are loaded
* (but maybe not parsed).
*/
areSceneAssetsLoaded(sceneName: string): boolean {
return this._resourcesLoader.areSceneAssetsLoaded(sceneName);
}
/**
* @returns true when all the resources of the given scene are loaded and
* parsed.
*/
areSceneAssetsReady(sceneName: string): boolean {
return this._resourcesLoader.areSceneAssetsReady(sceneName);
}
/**
* Load all assets needed to display the 1st scene, displaying progress in
* renderer.
*/
loadAllAssets(
callback: () => void,
progressCallback?: (progress: float) => void
) {
this._throwIfDisposed();
this.loadFirstAssetsAndStartBackgroundLoading(
this._getFirstSceneName(),
progressCallback
).then(callback);
}
/**
* Load all assets needed to display the 1st scene, displaying progress in
* renderer.
*
* When a game is hot-reload, this method can be called with the current
* scene.
*/
async loadFirstAssetsAndStartBackgroundLoading(
firstSceneName: string,
progressCallback?: (progress: float) => void
): Promise<void> {
try {
// Download the loading screen background image first to be able to
// display the loading screen as soon as possible.
const backgroundImageResourceName =
this._data.properties.loadingScreen.backgroundImageResourceName;
if (backgroundImageResourceName) {
await this._resourcesLoader
.getImageManager()
.loadResource(backgroundImageResourceName);
}
await Promise.all([
this._loadAssetsWithLoadingScreen(
/* isFirstScene = */ true,
async (onProgress) => {
// TODO Is a setting needed?
if (false) {
await this._resourcesLoader.loadAllResources(onProgress);
} else {
await this._resourcesLoader.loadGlobalAndFirstSceneResources(
firstSceneName,
onProgress
);
// Don't await as it must not block the first scene from starting.
this._resourcesLoader.loadAllSceneInBackground();
}
},
progressCallback
),
// TODO This is probably not necessary in case of hot reload.
gdjs.getAllAsynchronouslyLoadingLibraryPromise(),
]);
} catch (e) {
if (this._debuggerClient) this._debuggerClient.onUncaughtException(e);
throw e;
}
}
/**
* Load all assets for a given scene, displaying progress in renderer.
*/
async loadSceneAssets(
sceneName: string,
progressCallback?: (progress: float) => void
): Promise<void> {
await this._loadAssetsWithLoadingScreen(
/* isFirstLayout = */ false,
async (onProgress) => {
await this._resourcesLoader.loadAndProcessSceneResources(
sceneName,
onProgress
);
},
progressCallback
);
}
/**
* Load assets, displaying progress in renderer.
*/
private async _loadAssetsWithLoadingScreen(
isFirstScene: boolean,
loadAssets: (
onProgress: (count: integer, total: integer) => Promise<void>
) => Promise<void>,
progressCallback?: (progress: float) => void
): Promise<void> {
this.pause(true);
const loadingScreen = new gdjs.LoadingScreenRenderer(
this.getRenderer(),
this._resourcesLoader.getImageManager(),
this._data.properties.loadingScreen,
this._data.properties.watermark.showWatermark,
isFirstScene
);
const onProgress = async (count: integer, total: integer) => {
const percent = Math.floor((100 * count) / total);
loadingScreen.setPercent(percent);
if (progressCallback) {
progressCallback(percent);
}
const hasRendered = loadingScreen.renderIfNeeded();
if (hasRendered) {
// Give a chance to draw calls from the renderer to be handled.
await sleep(1);
}
};
await loadAssets(onProgress);
await loadingScreen.unload();
this.pause(false);
}
private _getFirstSceneName(): string {
const firstSceneName = this._data.firstLayout;
return this.hasScene(firstSceneName)
? firstSceneName
: // There is always at least a scene
this.getSceneAndExtensionsData()!.sceneData.name;
}
/**
* Start the game loop, to be called once assets are loaded.
*/
startGameLoop() {
this._throwIfDisposed();
try {
if (!this.hasScene()) {
logger.error('The game has no scene.');
return;
}
this._forceGameResolutionUpdate();
// Load the first scene
this._sceneStack.push(
this._getFirstSceneName(),
this._injectExternalLayout
);
this._watermark.displayAtStartup();
//Uncomment to profile the first x frames of the game.
// var x = 500;
// var startTime = Date.now();
// console.profile("Stepping for " + x + " frames")
// for(var i = 0; i < x; ++i) {
// this._sceneStack.step(16);
// }
// console.profileEnd();
// var time = Date.now() - startTime;
// logger.log("Took", time, "ms");
// return;
this._setupGameVisibilityEvents();
if (gdjs.inAppTutorialMessage) {
gdjs.inAppTutorialMessage.displayInAppTutorialMessage(
this,
this._options.inAppTutorialMessageInPreview,
this._options.inAppTutorialMessagePositionInPreview || ''
);
}
// The standard game loop
let accumulatedElapsedTime = 0;
this._hasJustResumed = false;
this._renderer.startGameLoop((lastCallElapsedTime) => {
try {
if (this._paused) {
return true;
}
// Skip the frame if we rendering frames too fast
accumulatedElapsedTime += lastCallElapsedTime;
if (
this._maxFPS > 0 &&
1000.0 / accumulatedElapsedTime > this._maxFPS + 7
) {
// Only skip frame if the framerate is 7 frames above the maximum framerate.
// Most browser/engines will try to run at slightly more than 60 frames per second.
// If game is set to have a maximum FPS to 60, then one out of two frames will be dropped.
// Hence, we use a 7 frames margin to ensure that we're not skipping frames too much.
return true;
}
const elapsedTime = accumulatedElapsedTime;
accumulatedElapsedTime = 0;
// Manage resize events.
if (this._notifyScenesForGameResolutionResize) {
this._sceneStack.onGameResolutionResized();
this._notifyScenesForGameResolutionResize = false;
}
// Render and step the scene.
if (this._sceneStack.step(elapsedTime)) {
this.getInputManager().onFrameEnded();
this._hasJustResumed = false;
return true;
}
return false;
} catch (e) {
if (this._debuggerClient)
this._debuggerClient.onUncaughtException(e);
throw e;
}
});
setTimeout(() => {
this._setupSessionMetrics();
}, 4000);
if (this._captureManager) {
this._captureManager.setupCaptureOptions(this._isPreview);
}
} catch (e) {
if (this._debuggerClient) this._debuggerClient.onUncaughtException(e);
throw e;
}
}
/**
* Stop game loop, unload all scenes, dispose renderer and resources.
* After calling this method, the RuntimeGame should not be used anymore.
* @param removeCanvas If true, the canvas will be removed from the DOM.
*/
dispose(removeCanvas?: boolean): void {
this._renderer.stopGameLoop();
this._sceneStack.dispose();