-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy path_GameMaker.js
More file actions
2477 lines (2127 loc) · 79 KB
/
_GameMaker.js
File metadata and controls
2477 lines (2127 loc) · 79 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
// **********************************************************************************************************************
//
// Copyright (c)2011, YoYo Games Ltd. All Rights reserved.
//
// File: _GameMaker.js
// Created: 09/07/2011
// Author: Mike
// Project: HTML5
// Description: GameMaker HTML5 "Aboyne" runtime engine.
//
// Date Version BY Comment
// ----------------------------------------------------------------------------------------------------------------------
// 09/07/2011
//
// **********************************************************************************************************************
//var image = new Image();
//image.src = "smiley.png";
//var image2 = new Image();
//image2.src = "html5game/onClick_test_texture_0.png";
//image2.width = 128;
//image2.height = 128;
//image2.src = image.src;
//var testpng = new Image();
//testpng.src = "html5game/test.png";
var div_a = 0;
var xxx=100;
var canvas = null;
var g_Canvas_OriginalPosition, g_Canvas_OriginalLeft, g_Canvas_OriginalTop, g_Canvas_Style, g_Canvas_Original_Parent, g_Canvas_Original_Next, g_Canvas_InRoot, g_Canvas_Original_Margin;
var g_ChromeStore = false;
var graphics = null;
var g_CurrentGraphics;
var g_LoadGraphics = null;
var GlobalGraphicsHandle = null;
var g_StartUpState=0;
var g_LoadingCanvasCreated=false;
// Run steps for the game
var lastfpstime = 0;
var newfps = 0;
var Fps = 60;
if (!Date.now) Date.now = function() { return new Date().getTime(); };
var g_StartDateTime = Date.now();
var g_CurrentTime = g_StartDateTime;
var g_FrameStartTime = g_StartDateTime;
var g_HttpRequestCrossOriginType = "anonymous";
var g_HttpConnectTimeoutMs = 60000;
//application surface...
var g_ApplicationSurface =-1;
var g_ApplicationWidth =-1;
var g_ApplicationHeight =-1;
var g_Application_Surface_Autodraw = true;
var g_AppSurfaceEnabled = true;
var g_bUsingAppSurface = true; //using app surface this frame
var g_OldApplicationWidth = -1;
var g_OldApplicationHeight = -1;
var g_NewApplicationWidth = -1;
var g_NewApplicationHeight = -1;
var g_NewApplicationSize = false;
var g_KeepAspectRatio = true;
var g_AppSurfaceRect = { x:0, y:0, w:0, h:0 };
var g_InGUI_Zone = false;
var g_SentLicense = false;
var g_DevicePixelRatio = 1;
var g_CanvasBackingScorePixelRatio = 1;
var g_CanvasPixelScale = 1;
var g_FirstTimeIn = 0;
var g_60_fps_counter = 0;
var g_Master_60_fps_counter = 0;
// Chrome store package?
if (window.chrome && window.chrome.app) {
g_ChromeStore = true;
try {
if( window && window['localStorage'] ){
g_ChromeStore = false;
}
} catch (e) {
}
}
window.addEventListener(
"message",
(event) => {
if(!g_ActiveMaps)
{
console.log("Event received before GameMaker initialised, ignoring");
if(event.origin!==undefined)
console.log("Event received from:" + event.origin);
if(typeof event.data === 'string')
console.log("Event data:" + event.data);
return;
}
//console.log("Event received from " + event.origin);
//console.log("Event data " + event.data);
const map = ds_map_create();
g_pBuiltIn.async_load = map;
ds_map_add(map, "origin", event.origin);
ds_map_add(map, "event_type", "post_message_received");
if (typeof event.data === 'string' || event.data instanceof String)
{
ds_map_add(map, "data", event.data);
}
else
{
ds_map_add(map, "data", JSON.stringify(event.data));
}
g_pObjectManager.ThrowEvent(EVENT_OTHER_SYSTEM_EVENT, 0);
ds_map_destroy(map);
}
);
// IE11 doesn't support Number.isNaN (since it's only in the draft spec for ECMAScript 6)
// so we define our own version here within Number.
if(Number.isNaN === undefined)
{
Number.isNaN = function(o) { return typeof(o) === 'number' && isNaN(o); };
}
// On load now help in the index.html file so sites can more easily add their own APIs
//window.onload = GameMaker_Init;
window.yyRequestAnimationFrame =
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame;
if (!window.yyRequestAnimationFrame) {
// if RAF is somehow amiss but we need short timeouts, register a message handler
// https://dbaron.org/log/20100309-faster-timeouts
window.addEventListener("message", function(e) {
if (e.source == window && e.data == "yyRequestAnimationFrame") {
e.stopPropagation();
animate();
}
}, true);
}
// shim layer with setTimeout fallback
window.requestAnimFrame = (function(){
return window.yyRequestAnimationFrame ||
function(callback){
window.setTimeout(callback, 1000 / 60);
};
} )();
var g_GMLUnhandledExceptionHandler = undefined;
function IsFeatureEnabled( _flag )
{
return (g_pGMFile.FeatureFlags !== undefined) && (g_pGMFile.FeatureFlags[ _flag ] !== undefined);
} // end IsFeatureEnabled
function exception_unhandled_handler( func )
{
var ret = g_GMLUnhandledExceptionHandler;
if ((func instanceof Function) || (func == undefined))
{
g_GMLUnhandledExceptionHandler = func;
}
else if(typeof func == "number")
{
var script = script_get(func);
if(script != null)
{
g_GMLUnhandledExceptionHandler = script;
}
else
{
yyError( "exception_unhandled_handler : argument should be a function" );
}
}
else
{
yyError( "exception_unhandled_handler : argument should be a function" );
}
return ret;
}
function yyUnhandledExceptionHandler( event )
{
if ((g_GMLUnhandledExceptionHandler == undefined) || !(g_GMLUnhandledExceptionHandler instanceof Function)) {
var string = "Unhandled Exception - " + event.message + " in file " + event.filename + " at line " + event.lineno ;
print( string );
//alert( string );
game_end(-1);
} // end if
else {
let error = event.error;
// Construct a GML struct to encapsulate the error details.
let errorStruct = { };
errorStruct.__type = "___struct___";
errorStruct.__yyIsGMLObject = true;
// Add error details to the struct with a "gml" prefix for each member.
errorStruct.gmlmessage = error.message;
errorStruct.gmlstacktrace = error.stack;
// Pass the error struct to the custom error handler
var ret = g_GMLUnhandledExceptionHandler( undefined, undefined, errorStruct );
game_end( ret );
}
debugger;
return false;
}
function yyUnhandledRejectionHandler( error )
{
var string = "Unhandled Rejection - " + error.message;
print( string );
if (error && error['promise']) {
error['promise'].catch(function(err){
var _endGame = true;
try {
if (!err['stack']) {
// We have no way to determine the source of the error.
_endGame = false;
}
else {
var _urlPos = err['stack'].indexOf("https://");
if (_urlPos < 0) _urlPos = err['stack'].indexOf("http://");
if (_urlPos >= 0) {
var reg_line_split = new RegExp("\\r\\n|\\r|\\n", "g");
var _rows = err['stack'].slice(_urlPos).split(reg_line_split);
if (_rows.length > 0) {
var _url = _rows[0];
_urlPos = _url.lastIndexOf("/");
if (_urlPos > 0) {
var _errUrl = new URL(_url.slice(0, _urlPos + 1));
if ((_errUrl['hostname'] != window['location']['hostname']) ||
(_errUrl['pathname'].indexOf(g_pGMFile.Options.GameDir) < 0)){
// The error is caused by an external resource.
_endGame = false;
}
}
}
}
}
}
catch (e) {
console.error("Unhandled Rejection | Promise Processing Error - " + e.message);
}
if (_endGame) {
game_end(-2);
debugger;
}
});
}
else {
game_end(-2);
debugger;
}
return false;
}
window.addEventListener( "error", yyUnhandledExceptionHandler );
window.addEventListener( "unhandledrejection", yyUnhandledRejectionHandler );
//external access for js extensions
// @if feature("extension_api")
var GMS_API = {
"debug_msg": show_debug_message,
"ds_list_size": ds_list_size,
"ds_list_find_value": ds_list_find_value,
"json_encode": json_encode,
"json_decode": json_decode,
"extension_get_option_value": extension_get_option_value,
"send_async_event_social": YYSendAsyncEvent_Social,
"get_facebook_app_id": YYGetFacebookAppId,
"get_app_version_string": YYGetAppVersionString
};
// @endif
function YYGetFacebookAppId() {
return g_pGMFile.Options.Facebook;
}
function YYGetAppVersionString()
{
var appVersion = g_pGMFile.Options.MajorVersion + "." +
g_pGMFile.Options.MinorVersion + "." +
g_pGMFile.Options.BuildVersion + " r" +
g_pGMFile.Options.RevisionVersion;
return appVersion;
}
function YYSendAsyncEvent_Social(_mapobj) {
// var dsmap = ds_map_create();
var jsonString = JSON.stringify(_mapobj);
var dsMap = json_decode(jsonString);
//TODO-handle json_decode fail...?
g_pBuiltIn.async_load = dsMap;
g_pObjectManager.ThrowEvent(EVENT_OTHER_SOCIAL, 0);
ds_map_destroy(dsMap);
}
//-------------------------------
var g_debug_window = null;
// #############################################################################################
/// Function:<summary>
///
/// </summary>
///
/// Out: <returns>
///
/// </returns>
// #############################################################################################
function ClearConsoleCallback()
{
if (g_debug_window)
{
g_debug_window.document.getElementById("debug_console").value = "";
}
}
// #############################################################################################
/// Function:<summary>
///
/// </summary>
///
/// Out: <returns>
///
/// </returns>
// #############################################################################################
function ToggleDebugPause() {
if (g_debug_window) {
if (Run_Paused) {
Run_Paused = false;
} else {
Run_Paused = true;
}
}
}
// #############################################################################################
/// Function:<summary>
/// Create our debug console, but hide it.
/// </summary>
///
/// In: <param name="_canvas">The canvcas handle</param>
/// Out: <returns>
///
/// </returns>
// #############################################################################################
// @if feature("debug")
function CreateDebugConsole() {
try
{
g_debug_window = window.open('', 'gamemakerstudio_debugconsole_window', 'width=990,height=600,titlebar=yes,scrollbars,resizable'); //bletoolbar=no,menubar=no'); //,scrollbars,resizable,toolbar,status');
// Did it open?
if (g_debug_window)
{
// Is the debug_console already there from a previous run?
if (!g_debug_window.document.getElementById("debug_console"))
{
//with (g_debug_window.document)
{
g_debug_window.document.write('<!DOCTYPE html><html>' +
'<header>'+
'<title>GameMaker - DEBUG console</title>'+
'</header>'+
'<body>'+
'<table border="0"><tr>' +
'<td>Debug Output</td><td>Instances</td><td>InstanceData</td></tr>'+
'<tr><td><textarea id="debug_console" wrap="off" style="width: 450px; height:500px; display: block;" cols="70"></textarea></td>' +
'<td>'+
'<select id="debug_instances" size=31 style="width: 120px; height: 500px; font-family: monospace;" > ' +
/*'<option value="CA" >California</option>'+
'<option value="CO" >Colorado</option>'+
'<option value="CN" >Connecticut</option>'+*/
'</select>'+
'</td>'+
'<td ALIGN="left" VALIGN="top" style="min-width:350px; width:300px; height:500px; font-family: monospace; border:solid 1px #666"><div id="debug_Instance_Data" style="width:100%; height:500px;overflow: auto;"></div></td>' +
'</tr></table>' +
'<br><button type="button" id="clear_console_button" onclick="ClearConsoleCallback()">Clear Console</button>' +
'<button type="button" id="gm_pause_button" onclick="ToggleDebugPause()">Pause/Resume</button>' +
'</body>' +
'</html>');
}
var but = g_debug_window.document.getElementById("clear_console_button");
but.onclick = function() { ClearConsoleCallback(); };
but = g_debug_window.document.getElementById("gm_pause_button");
but.onclick = function() { ToggleDebugPause(); };
}
}
// '<td>Instance Data<br><textarea id="debug_Instance_Data" style="display: block;" rows="31" cols="25" style="font-family: san-serif;"></textarea></td>'+
// Create a debug console.
/* var c = document.getElementById(g_CanvasName);
var y = document.createElement('textarea');
y.setAttribute("id","debug_console");
y.setAttribute("cols","100");
y.setAttribute("rows","20");
y.style.display = "none";
var obj = c.parentNode;
obj.insertBefore(y, c.nextSibling);
*/
g_GameMakerIdentifier = 0x71562;
}
catch (e) {
debug(e.message);
}
}
// @endif
// #############################################################################################
/// Function:<summary>
/// Create a canvas for loading from
/// </summary>
///
/// In: <param name="_canvas">The canvcas handle</param>
/// Out: <returns>
///
/// </returns>
// #############################################################################################
function CreateLoadingCanvas()
{
var c = document.getElementById(g_CanvasName);
var obj = c.parentNode;
// Create a loading screen canvas the same size and shape of the primary one, and place it over the top of the MAIN screen.
var load = document.createElement('canvas');
// position where the game canvas is - will update every frame to adjust for centering
CalcCanvasLocation(canvas, g_CanvasRect);
load.style.position = "absolute";
load.style.left = g_CanvasRect.left + "px";
load.style.top = g_CanvasRect.top + "px";
load.width = c.width;
load.height = c.height;
load.setAttribute("id","loading_screen");
obj.insertBefore(load, c.nextSibling);
g_LoadGraphics = load.getContext('2d');
Graphics_AddCanvasFunctions(g_LoadGraphics);
}
// #############################################################################################
/// Function:<summary>
/// Decode a string
/// </summary>
///
/// In: <param name="_str">String to decode</param>
/// Out: <returns>
/// resulting string
/// </returns>
// #############################################################################################
function DecodeString(_str)
{
var s = "";
var l = _str.length;
for (var i=0; i < l; i++) {
s = s + String.fromCharCode(_str.charCodeAt(i)^0x1a);
}
return s;
}
// #############################################################################################
/// Function:<summary>
/// Delete the loading screen canvas
/// </summary>
// #############################################################################################
function DeleteLoadingCanvas()
{
var c = document.getElementById(g_CanvasName);
var l = document.getElementById("loading_screen");
//BETA
var obj = c.parentNode;
if (l != null)
{
obj.removeChild(l);
}
g_LoadGraphics = null;
g_LoadingCanvasCreated = false;
}
// #############################################################################################
/// Function:<summary>
/// Get the location of the canvas on the web page.
/// </summary>
///
/// Out: <returns>
/// canvasMinX,canvasMinY hold the base of the canvas.
/// canvasMaxX,canvasMaxY hold the top end.
/// </returns>
// #############################################################################################
function CalcCanvasLocation(_canvas,_rect)
{
//
var rect = _canvas.getBoundingClientRect();
_rect.left = rect.left;
_rect.top = rect.top;
//
_rect.right = _rect.left + DISPLAY_WIDTH;
_rect.bottom= _rect.top + DISPLAY_HEIGHT;
//
_rect.scaleX = (_canvas.clientWidth / _canvas.width) || 1;
_rect.scaleY = (_canvas.clientHeight / _canvas.height) || 1;
}
// #############################################################################################
/// Function:<summary>
/// Given the text the address bar, parse it and get the
/// </summary>
///
/// In: <param name="_url"></param>
/// Out: <returns>
///
/// </returns>
// #############################################################################################
function ParseURL(_url) {
g_Arguments = [];
g_ArgumentIndex = [];
g_ArgumentValue = [];
g_ArgumentCount = 0;
var params = _url.search;
var url = _url.protocol + "//" + _url.host + _url.pathname;
g_ArgumentIndex[0] = url;
g_ArgumentValue[0] = null;
if (params[0] == "?") params = params.substring(1, params.length);
var index = 0;
var start = 0;
var arg = "";
var val = null;
while (index < params.length)
{
var c = params[index];
// end of paramater?
if (c == "&")
{
if (arg != "")
{
if( start!=index) val = params.substring(start, index);
g_ArgumentIndex[g_ArgumentIndex.length] = arg;
g_ArgumentValue[g_ArgumentValue.length] = val;
g_Arguments[arg] = val;
g_ArgumentCount++;
arg = "";
val = null;
}
start = index + 1;
} else if (c == "=")
{
arg = params.substring(start, index);
val = null;
start = index + 1;
}
index++;
}
// Probably no "&" at the end of the string... so finsih off.
if (arg != "")
{
if (start != index) val = params.substring(start, index);
g_ArgumentIndex[g_ArgumentIndex.length] = arg;
g_ArgumentValue[g_ArgumentValue.length] = val;
g_Arguments[arg] = val;
g_ArgumentCount++;
arg = val = "";
}
}
function RememberCanvasSettings() {
g_Canvas_OriginalPosition = canvas.style.position;
g_Canvas_OriginalLeft = canvas.style.left;
g_Canvas_OriginalTop = canvas.style.top;
g_Canvas_Style = canvas.style.cssText;
g_Canvas_Original_Parent = canvas.parentNode;
g_Canvas_Original_Next = canvas.nextSibling;
g_Canvas_InRoot = false;
g_Canvas_Original_Margin = canvas.margin;
if( (g_Canvas_Original_Parent == document.body) || (canvas.mozRequestFullScreen) || (canvas.webkitRequestFullScreen))
{
g_Canvas_InRoot = true;
}
}
//------------------------------------------------------------------------------
// #############################################################################################
/// Function:<summary>
///
/// </summary>
///
/// Out: <returns>
///
/// </returns>
// #############################################################################################
window['GameMaker_Init'] = GameMaker_Init; //Keeps this as an entry point for Google Closure Compiler
var g_obf2var = undefined;
function GameMaker_Init()
{
debug('------- GameMaker_Init -------------');
if (!document.getElementById || !document.createElement) return;
canvas = document.getElementById(g_CanvasName);
graphics = null;
if( !canvas) return;
// @if function("parameter_*")
ParseURL( window.location );
// @endif
g_pGMFile = JSON_game;
// initialise the map of obfuscated names to var
if (typeof g_var2obf !== "undefined") {
g_obf2var = Object.getOwnPropertyNames(g_var2obf).reduce((acc, prop) => {
acc[g_var2obf[prop]] = prop;
return acc;
}, {});
} // end if
if (g_pGMFile.Options.outputDebugToDiv) {
var logOutput = document.createElement('div');
logOutput.id = "yyDebugDiv";
logOutput.style.display = "none";
document.body.appendChild(logOutput);
}
DetectBrowser();
if ((g_pGMFile.Options && g_pGMFile.Options.debugMode) || (g_pGMFile.Options && g_pGMFile.Options.debugMode == undefined))
{
g_DebugMode = true; // if in DEBUG mode, allow console output.
//hideshow(g_debug_window.document.getElementById('debug_console'));
}
if((g_pGMFile.Options!= undefined) && (g_pGMFile.Options.AssetCompilerMajorVersion !=undefined) && (g_pGMFile.Options.AssetCompilerMajorVersion>1) )
{
g_isZeus = true;
if(g_pGMFile.Options.GameSpeed!=undefined)
{
g_GameTimer.SetFrameRate(g_pGMFile.Options.GameSpeed);
}
}
RegisterPauseEvents();
// Initialise WebGL OR Canvas as needed
g_OpenGLRequired = false;
//Shifted out here as non-webgl will now use these
g_Matrix = [];
g_Matrix[MATRIX_PROJECTION] = new Matrix();
g_Matrix[MATRIX_VIEW] = new Matrix();
g_Matrix[MATRIX_WORLD] = new Matrix();
if ((g_pGMFile.Options.WebGL) && (g_pGMFile.Options.WebGL != 0))
{
g_InterpolatePixels = g_pGMFile.Options.interpolatePixels;
var glinit = undefined;
glinit = InitWebGL(canvas);
if (glinit) {
graphics = g_webGL;
}
else {
// If we REQUIRE WebGL, then Don't play this game.
if (g_pGMFile.Options.WebGL == 1)
{
g_OpenGLRequired = true;
}
graphics = canvas.getContext('2d');
}
}
else {
graphics = canvas.getContext('2d');
}
g_CurrentGraphics = graphics;
g_Collision_Compatibility_Mode = g_pGMFile.Options.CollisionCompatibility;
g_Legacy_Primitive_Drawing = g_pGMFile.Options.LegacyPrimitiveDrawing;
if (g_Legacy_Primitive_Drawing == false)
{
offsethackD3D = 0.0;
}
g_LastCanvasWidth = canvas.width;
g_LastCanvasHeight = canvas.height;
// @if feature("audio")
if ((g_pGMFile.Options.UseNewAudio == true) || g_isZeus) {
g_AudioModel = Audio_WebAudio;
}
// @endif audio
document.body.style.overflow = "hidden";
GlobalGraphicsHandle = graphics;
g_OriginalWidth = canvas.width;
g_OriginalHeight = canvas.height;
// get width, height and canvas bounds... this must happen before the first CalcCanvasLocation
DISPLAY_WIDTH = g_OriginalWidth;
DISPLAY_HEIGHT = g_OriginalHeight;
//initial application surface = canvas size (=room size/view bounds)
g_ApplicationWidth = DISPLAY_WIDTH;
g_ApplicationHeight = DISPLAY_HEIGHT;
g_KeepAspectRatio = (g_pGMFile.Options.scale != 0);
g_DevicePixelRatio = window.devicePixelRatio || 1;
g_CanvasBackingScorePixelRatio = (graphics.webkitBackingStorePixelRatio || graphics.mozBackingStorePixelRatio || graphics.msBackingStorePixelRatio ||
graphics.oBackingStorePixelRatio || graphics.backingStorePixelRatio || 1);
g_CanvasPixelScale = g_DevicePixelRatio / g_CanvasBackingScorePixelRatio;
g_CanvasRect = new YYRECT();
CalcCanvasLocation(canvas,g_CanvasRect);
canvasMinY = g_CanvasRect.top;
canvasMinX = g_CanvasRect.left;
canvasMaxX = g_CanvasRect.right;
canvasMaxY = g_CanvasRect.bottom;
//if facebook is enabled, initialise it now, and defer creating the debug console ( as it interferes with fbAsyncInit callback )
if (g_pGMFile.Options.Facebook && !g_pGMFile.Options.UseFBExtension)
{
console.log("using internal runtime facebook");
YoYoFBInit(g_pGMFile.Options.Facebook);
}
// @if feature("debug")
else if (g_pGMFile.Options && g_pGMFile.Options.debugMode)
{
CreateDebugConsole();
}
// @endif
// Remember these settings, as FULLSCREEN will mess them up.
RememberCanvasSettings();
// Update the canvas to use OUR functions. This helps obfuscation, and will shrink the code base.
Graphics_AddCanvasFunctions(graphics);
//document.body.appendChild( canvas );
document.body.oncontextmenu = function() { return false; };
bindTouchEvents();
// If we have a loading screen... find it.
g_LoadingScreen = document.getElementById('GM4HTML5_loadingscreen');
//requestAnimationFrame
//setInterval(GameMaker_Tick, 1000 / (60));
//if( (g_pGMFile.Options && g_pGMFile.Options.debugMode) || ( g_pGMFile.Options && g_pGMFile.Options.debugMode==undefined) )
//{
// g_DebugMode = true; // if in DEBUG mode, allow console output.
// //hideshow(g_debug_window.document.getElementById('debug_console'));
//}
if (g_webGL && g_DebugMode)
{
debug("WebGL Enabled!");
debug("Max Texture Size=" + g_webGL.GetMaxTextureSize());
}
InitAboyne(); // Init the "runtime" engine
YoYo_Init(); // Init the YoYo GML functions
// IF we required WebGL and it's not available, ignore everything and abort.
if (g_OpenGLRequired)
{
g_StartUpState = -2;
} else
{
if (g_DebugMode) g_pBuiltIn.debug_mode = g_pGMFile.Options.debugMode;
g_LoadingBarCallback = "";
g_CustomLoadingBarCallback = "";
g_LoadingCompleteCallback = function () { };
LoadGame_PreLoadAssets(g_pGMFile);
g_StartUpState = 0;
}
/* Focus our window (or iframe) now... */
window.focus();
/* ...and whenever the canvas is clicked. */
canvas.addEventListener("click", function (e) {
window.focus();
});
/* ...this helps with eliminating stutter on mobile */
canvas.addEventListener("touchstart", (e) => e.preventDefault(), {
passive: false,
});
canvas.addEventListener("touchmove", (e) => e.preventDefault(), {
passive: false,
});
canvas.addEventListener("touchend", (e) => e.preventDefault(), {
passive: false,
});
g_FrameStartTime = Date.now();
window.requestAnimFrame(animate);
}
/*var dv1 = document.getElementById('gamemaker_image');
dv1.style.left=xxx+"px";
var r = "rotate("+div_a+"deg)";
dv1.style.msTransform=r;
dv1.style.MozTransform = r;
dv1.style.WebkitTransform = r;
xxx+=1;
xxx &= 255;
div_a+=1;
if( div_a>360 ) div_a-=360;
*/
// #############################################################################################
/// Function:<summary>
///
/// </summary>
///
/// Out: <returns>
///
/// </returns>
// #############################################################################################
function animate() {
// once in-game, timing is handled by GameMaker_Tick
if (g_StartUpState != 3) window.requestAnimFrame(animate);
if (g_LoadingCanvasCreated) {
// Adjust the location each tick to adjust for centering/moving etc.
CalcCanvasLocation(canvas, g_CanvasRect);
var load = document.getElementById("loading_screen");
load.style.position = "absolute";
load.style.left = g_CanvasRect.left+"px";
load.style.top = g_CanvasRect.top + "px";
}
var done = false;
while(!done)
{
done=true;
switch (g_StartUpState)
{
// Handle error case
case -2:
{
if (g_LoadingCanvasCreated) DeleteLoadingCanvas();
// @if feature("gl")
yyWebGLRequiredError(graphics, DISPLAY_WIDTH, DISPLAY_HEIGHT);
// @endif gl
}
break;
// Handle loading screen (default or custom)
case 0:
{
if (g_LoadingCount >= g_LoadingTotal) {
g_LoadingCount = g_LoadingTotal;
g_StartUpState = 1;
done = false;
}
ProcessFileLoading();
// If there is a custom loading bar callback
if (g_pGMFile.Options.loadingBarCallback)
{
// Wait until the extension is actually loaded (needs a game tick)
if (g_ExtensionCount >= g_ExtensionTotal)
{
// If it is loaded create the canvas (if it doesn't exist) and evaluate the callback
if (!g_LoadingCanvasCreated)
{
CreateLoadingCanvas();
g_LoadingCanvasCreated=true;
// Evaluate the callback
try
{
var _loadingBarCallback = eval(g_pGMFile.Options.loadingBarCallback);
// Update the loading bar global callback
g_LoadingBarCallback = _loadingBarCallback;
}
catch (_err)
{
// Wval failed fallback to using the default one.
console.error('Invalid loading bar extension "' + g_pGMFile.Options.loadingBarCallback + '", using default!');
console.dir(_err);
}
}
// This will either be the custom bar or the default if the eval failed (call the update callback)
g_LoadingBarCallback(g_LoadGraphics, DISPLAY_WIDTH, DISPLAY_HEIGHT, g_LoadingTotal, g_LoadingCount, g_LoadingScreen);
}
}
// Default loading screen
else {
// Create the loading canvas right away
if(!g_LoadingCanvasCreated)
{
CreateLoadingCanvas();
g_LoadingCanvasCreated=true;
}
// This will be the default loading bar callback (see: yyRenderStandardLoadingBar)
g_LoadingBarCallback(g_LoadGraphics, DISPLAY_WIDTH, DISPLAY_HEIGHT, g_LoadingTotal, g_LoadingCount, g_LoadingScreen);
}
}
break;
// Handle loading screen disposal (start load game)
case 1:
{
// We finished loading and extensions should also have loaded (if not wait)
if (g_ExtensionCount >= g_ExtensionTotal)
{
// Delete lading canvas and load the actual game
DeleteLoadingCanvas();
LoadGame(g_pGMFile);
g_StartUpState = 2;
done = false;
}
}
break;
// Handle game loop start
case 2:
{
// Start game loop
g_LoadingCompleteCallback();
debug("Entering main loop...");
StartGame();
g_StartUpState = 3;
g_pBuiltIn.last_time = new Date().getTime();
done = false;
}
break;
case 3:
GameMaker_Tick();
break;
}
}
}
// #############################################################################################
/// Function:<summary>
/// Draw text "centered"
/// </summary>
///
/// In: <param name="x"></param>
/// <param name="y"></param>
/// <param name="colour"></param>
/// <param name="text"></param>
/// Out: <returns>
///
/// </returns>
// #############################################################################################
function yyDrawCenteredText(_graphics, x,y,colour, text)
{
_graphics.fillStyle=colour;
_graphics.lineStyle=colour;