-
Notifications
You must be signed in to change notification settings - Fork 0
/
SaveTheDay.html
1215 lines (1079 loc) · 54.6 KB
/
SaveTheDay.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<title>SaveTheDay</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script>
// THIS IS TEMP -- to be removed when the following has been removed as well
// .../Engine/Source/Runtime/Engine/Private/ActiveSound.cpp
// // for velocity-based effects like doppler
// ParseParams.Velocity = (ParseParams.Transform.GetTranslation() - LastLocation) / DeltaTime;
window.AudioContext = ( window.AudioContext || window.webkitAudioContext || null );
if ( AudioContext ) {
var ue4_hacks = {}; // making this obvious...
ue4_hacks.ctx = new AudioContext();
ue4_hacks.panner = ue4_hacks.ctx.createPanner();
ue4_hacks.panner.__proto__.setVelocity = ( ue4_hacks.panner.__proto__.setVelocity || function(){} );
}
</script>
<script>
// Minimum WebGL version that the page needs in order to run. UE4 will attempt to use WebGL 2 if available.
// Set this to 1 to run with a WebGL 1 fallback if the graphical features required by your UE4 project are
// low enough that they do not strictly require WebGL 2.
const requiredWebGLVersion = 1;
// Add ?webgl1 GET param to explicitly test the WebGL 1 fallback version even if browser does support WebGL 2.
const explicitlyUseWebGL1 = (location.search.indexOf('webgl1') != -1);
// Deduce which version to load up.
var supportsWasm = (typeof WebAssembly === 'object' && typeof WebAssembly.Memory === 'function');
// By default, Shipping builds serve out compressed assets, and Development builds serve uncompressed assets.
// Change the following line to customize. When hosting UE4 builds live on a production CDN, compression
// should always be enabled, since uncompressed files are too huge to be downloaded over the web.
const serveCompressedAssets = false;
// For the large .data file, there's two ways to manage compression: either UE4 UnrealPak tool can compress it in engine, or
// it can be gzip compressed on disk like other assets. Compressing via UnrealPak has the advantage of storing a smaller data
// file to IndexedDB, whereas gzip compressing to disk has the advantage of starting up the page slightly faster.
// If true, serve out 'UE4Game.data.gz', if false, serve out 'UE4Game.data'.
// const dataFileIsGzipCompressed = false;
var Module = {
// state management
infoPrinted: false,
lastcurrentDownloadedSize: 0,
totalDependencies: 0,
dataBytesStoredInIndexedDB: 0, // Track how much data is currently stored in IndexedDB.
assetDownloadProgress: {}, // Track how many bytes of each needed asset has been downloaded so far.
UE4_indexedDBName: 'UE4_assetDatabase_SaveTheDay', // TODO Nick: this should be an ascii ID string without special characters that is unique to the project that is being packaged
UE4_indexedDBVersion: 201901111436, // Bump this number to invalidate existing IDB storages in browsers.
};
// Tests if type === 'browser' or type === 'os' is 64-bit or not.
function heuristicIs64Bit(type) {
function contains(str, substrList) { for(var i in substrList) if (str.indexOf(substrList[i]) != -1) return true; return false; }
var ua = (navigator.userAgent + ' ' + navigator.oscpu + ' ' + navigator.platform).toLowerCase();
if (contains(ua, ['wow64'])) return type === 'os'; // 32bit browser on 64bit OS
if (contains(ua, ['x86_64', 'amd64', 'ia64', 'win64', 'x64', 'arm64', 'irix64', 'mips64', 'ppc64', 'sparc64'])) return true;
if (contains(ua, ['i386', 'i486', 'i586', 'i686', 'x86', 'arm7', 'android', 'mobile', 'win32'])) return false;
if (contains(ua, ['intel mac os'])) return true;
return false;
}
// For best stability on 32-bit browsers, allocate asm.js/WebAssembly heap up front before proceeding
// to load any other page content. This mitigates the chances that loading up page assets first would
// fragment the memory area of the browser process.
var pageSize = 64 * 1024;
var heuristic64BitBrowser = heuristicIs64Bit('browser');
function alignPageUp(size) { return pageSize * Math.ceil(size / pageSize); }
// The application should not be able to allocate more than MAX bytes of memory. If the application
// attempts to allocate any more, it will be forbidden. Use this field to defensively impose a
// strict limit to an application to keep it from going rogue with its memory usage beyond some
// undesired limit. The absolute maximum that is possible is one memory page short of 2GB.
var MAX_MEMORY_64BIT = Infinity;
var MAX_MEMORY_32BIT = 512*1024*1024;
var MAX_MEMORY = Math.min(alignPageUp(heuristic64BitBrowser ? MAX_MEMORY_64BIT : MAX_MEMORY_32BIT), 2048 * 1024 * 1024 - pageSize);
// The application needs at least this much memory to run. If the browser can't provide this,
// the page startup should be aborted in an out-of-memory exception.
var MIN_MEMORY = Math.min(alignPageUp(32 * 1024 * 1024), MAX_MEMORY);
// As a hint to the implementation, the application would prefer to reserve this much address
// space at startup, and the browser will attempt its best to satisfy this. If this is not
// possible, the browser will attempt to allocate anything as close to this IDEAL amount as
// possible, but at least MIN bytes.
var IDEAL_MEMORY_64BIT = 1024 * 1024 * 1024;
var IDEAL_MEMORY_32BIT = 1024 * 1024 * 1024;
var IDEAL_MEMORY = Math.min(Math.max(alignPageUp(heuristic64BitBrowser ? IDEAL_MEMORY_64BIT : IDEAL_MEMORY_32BIT), MIN_MEMORY), MAX_MEMORY);
// If true, assume the application will have most of its memory allocation pressure inside the
// application heap, so reserve address space there up front. If false, assume that the memory
// allocation pressure is outside the heap, so avoid reserving memory up front, until needed.
var RESERVE_MAX_64BIT = true;
var RESERVE_MAX_32BIT = false;
var RESERVE_MAX = heuristic64BitBrowser ? RESERVE_MAX_64BIT : RESERVE_MAX_32BIT;
function MB(x) { return (x/1024/1024) + 'MB'; }
function allocateHeap() {
// Try to get as much memory close to IDEAL, but at least MIN.
for(var mem = IDEAL_MEMORY; mem >= MIN_MEMORY; mem -= pageSize) {
try {
if (RESERVE_MAX)
Module['wasmMemory'] = new WebAssembly.Memory({ initial: mem / pageSize, maximum: MAX_MEMORY / pageSize });
else
Module['wasmMemory'] = new WebAssembly.Memory({ initial: mem / pageSize });
Module['buffer'] = Module['wasmMemory'].buffer;
if (Module['buffer'].byteLength != mem) throw 'Out of memory';
break;
} catch(e) { /*nop*/ }
}
if (!Module['buffer'] || !(Module['buffer'].byteLength >= MIN_MEMORY)) {
delete Module['buffer'];
throw 'Out of memory';
}
Module['TOTAL_MEMORY'] = Module['buffer'].byteLength;
}
allocateHeap();
Module['MAX_MEMORY'] = MAX_MEMORY;
console.log('Initial memory size: ' + MB(Module['TOTAL_MEMORY']) + ' (MIN_MEMORY: ' + MB(MIN_MEMORY) + ', IDEAL_MEMORY: ' + MB(IDEAL_MEMORY) + ', MAX_MEMORY: ' + MB(MAX_MEMORY) + ', RESERVE_MAX: ' + RESERVE_MAX + ', heuristic64BitBrowser: ' + heuristic64BitBrowser + ', heuristic64BitOS: ' + heuristicIs64Bit('os') + ')');
</script>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<style type="text/css">
html, body, .container {
height: 100%;
font-family: "Helvetica Neue", "HelveticaNeue", Helvetica, Arial, sans-serif;
}
.h4, h4 {
margin-top: 1pt;
margin-bottom: 1pt;
font-size: 10pt;
}
.container {
display: table;
vertical-align: middle;
border: 0px;
border-spacing: 0px;
}
.glyphicon-spin {
animation: spin 2000ms infinite linear;
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(359deg);
}
}
@-webkit-keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(359deg);
}
}
.wrapper {
position: relative;
margin: 1em auto 10px auto;
text-align: center;
min-width: 640px;
width: 100%;
height: 480px; /* initial height, will be dynamically adjusted at runtime */
max-width: 95%;
display: block;
align-items: center;
position: relative;
text-align: center;
justify-content: center;
}
.emscripten {
padding-right: 0;
margin-left: auto;
margin-right: auto;
display: block;
display: -webkit-box;
display: -moz-box;
display: box;
-webkit-box-align: center;
-moz-box-align: center;
box-align: center;
-webkit-box-pack: center;
-moz-box-pack: center;
box-pack: center;
}
#canvas:not([fullscreen]) {
padding-right: 0;
margin-left: auto;
margin-right: auto;
width: 100%;
}
.texthalf {
height: 37%;
border: 0px;
padding: 0px;
overflow-y: scroll;
font-size: 2em;
}
.buttonarea {
min-height: 3%;
border-top: 0px;
border-bottom: 0px;
padding: 0px;
margin-right: 0px;
margin-top: 0px;
margin-bottom: 0px;
}
.btn { padding: 0px; text-align: center; min-width: 150px }
.progress { background: rgba(245, 245, 245, 1); border: 0px solid rgba(245, 245, 245, 1); border-radius: 0px; height: 4px; }
.progress-bar-custom { background: rgba(153, 153, 153, 1); }
.centered-axis-xy {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
</style>
<div class="wrapper" id="mainarea">
<div class="alert alert-warning centered-axis-xy" style="min-height: 20px; display:none;" role="alert" id="compilingmessage">
<div id='loadTasks'> </div>
</div>
<canvas id="canvas" class="emscripten" oncontextmenu="event.preventDefault()" style="display:none;">
</div>
<div class="row buttonarea text-center" id="buttonrow">
<div class="col-sm-2 text-center"></div>
<div class="col-sm-2 text-center"><button type="button" class="btn btn-primary" onclick="Module['pauseMainLoop']();">Pause</button></div>
<div class="col-sm-2 text-center"><button type="button" class="btn btn-primary" onclick="Module['resumeMainLoop']();">Resume</button></div>
<div class="col-sm-2 text-center"></div>
<div class="col-sm-2 text-center"><button type="button" class="btn btn-primary" id='clear_indexeddb' onclick="deleteIndexedDBStorage();">Clear IndexedDB</button></div>
<div class="col-sm-2 text-center"><button type="button" class="btn btn-primary" id="fullscreen_request">FullScreen</button></div>
<div class="col-sm-2 text-center"></div>
<div class="col-sm-2 text-center"></div>
</div>
<div class="texthalf text-normal jumbotron " id="logwindow" style='display:none'></div>
<script type="text/javascript">
// combine all parallel downloads into one progress bar.
var totalDownloadSize = 0;
var currentDownloadedSize = 0;
// helper functions.
// http://stackoverflow.com/questions/4750015/regular-expression-to-find-urls-within-a-string
function getHTMLGetParam(name) {
if (name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search))
return decodeURIComponent(name[1]);
}
var UE4 = {
on_fatal: function() {
try {
UE4.on_fatal = Module.cwrap('on_fatal', null, ['string', 'string']);
} catch(e) {
UE4.on_fatal = function() {};
}
},
};
Module['preinitializedWebGLContext'] = null;
function getGpuInfo() {
var gl = Module['preinitializedWebGLContext'];
if (!gl) return '(no GL: ' + Module['webGLErrorReason'] + ')';
var glInfo = '';
var debugInfo = gl.getExtension('WEBGL_debug_renderer_info');
if (debugInfo) glInfo += gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL) + ' ' + gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL) + '/';
glInfo += gl.getParameter(gl.VENDOR) + ' ' + gl.getParameter(gl.RENDERER);
glInfo += ' ' + gl.getParameter(gl.VERSION);
glInfo += ', ' + gl.getParameter(gl.SHADING_LANGUAGE_VERSION);
if (Module['softwareWebGL']) glInfo += ' (software)';
return glInfo;
}
function detectWebGL() {
var canvas = Module['canvas'] || document.createElement("canvas");
// If you run into problems with WebGL 2, or for quick testing purposes, you can disable UE4
// from using WebGL 2 and revert back to WebGL 1 by setting the following flag to true.
var disableWebGL2 = false;
if (explicitlyUseWebGL1) {
disableWebGL2 = true;
console.log('Disabled WebGL 2 as requested by ?webgl1 GET param.');
}
var names = ["webgl", "experimental-webgl"];
if (disableWebGL2) {
WebGL2RenderingContext = undefined;
} else {
names = ["webgl2"].concat(names);
}
function testError(e) { Module['webGLErrorReason'] = e.statusMessage; };
canvas.addEventListener("webglcontextcreationerror", testError, false);
try {
for(var failIfMajorPerformanceCaveat = 1; failIfMajorPerformanceCaveat >= 0; --failIfMajorPerformanceCaveat) {
for(var i in names) {
try {
var context = canvas.getContext(names[i], {antialias:false,alpha:false,depth:true,stencil:true,failIfMajorPerformanceCaveat:!!failIfMajorPerformanceCaveat});
Module['preinitializedWebGLContext'] = context;
Module['softwareWebGL'] = !failIfMajorPerformanceCaveat;
if (context && typeof context.getParameter == "function") {
if (typeof WebGL2RenderingContext !== 'undefined' && context instanceof WebGL2RenderingContext && names[i] == 'webgl2') {
return 2;
} else {
// We were able to precreate only a WebGL 1 context, remove support for WebGL 2 from the rest of the page execution.
WebGL2RenderingContext = undefined;
return 1;
}
}
} catch(e) { Module['webGLErrorReason'] = e.toString(); }
}
}
} finally {
canvas.removeEventListener("webglcontextcreationerror", testError, false);
}
return 0;
}
Module['canvas'] = document.getElementById('canvas');
// Canvas scaling mode should be set to one of: 1=STRETCH, 2=ASPECT, or 3=FIXED.
// This dictates how the canvas size changes when the browser window is resized
// by dragging from the corner.
var canvasWindowedScaleMode = 2 /*ASPECT*/;
// High DPI setting configures whether to match the canvas size 1:1 with
// the physical pixels on the screen.
// For background, see https://www.khronos.org/webgl/wiki/HandlingHighDPI
var canvasWindowedUseHighDpi = true;
// Stores the initial size of the canvas in physical pixel units.
// If canvasWindowedScaleMode == 3 (FIXED), this size defines the fixed resolution
// that the app will render to.
// If canvasWindowedScaleMode == 2 (ASPECT), this size defines only the aspect ratio
// that the canvas will be constrained to.
// If canvasWindowedScaleMode == 1 (STRETCH), these size values are ignored.
var canvasAspectRatioWidth = 1366;
var canvasAspectRatioHeight = 768;
// Fullscreen scaling mode behavior (export these to Module object for the engine to read)
// This value is one of:
// 0=NONE: The same canvas size is kept when entering fullscreen without change.
// 1=STRETCH: The canvas is resized to the size of the whole screen, potentially changing aspect ratio.
// 2=ASPECT: The canvas is resized to the size of the whole screen, but retaining current aspect ratio.
// 3=FIXED: The canvas is centered on screen with a fixed resolution.
Module['UE4_fullscreenScaleMode'] = 1;//canvasWindowedScaleMode; // BUG: if using FIXED, fullscreen gets some strange padding on margin...
// When entering fullscreen mode, should UE4 engine resize the canvas?
// 0=No resizing (do it manually in resizeCanvas()), 1=Resize to standard DPI, 2=Resize to highDPI
Module['UE4_fullscreenCanvasResizeMode'] = canvasWindowedUseHighDpi ? 2/*HIDPI*/ : 1/*Standard DPI*/;
// Specifies how canvas is scaled to fullscreen, if not rendering in 1:1 pixel perfect mode.
// One of 0=Default, 1=Nearest, 2=Bilinear
Module['UE4_fullscreenFilteringMode'] = 0;
document.addEventListener('error', function(){document.getElementById('clear_indexeddb').style.display = 'inline-block';}, false);
// Startup task which is run after UE4 engine has launched.
function postRunEmscripten() {
taskFinished(TASK_MAIN);
$("#compilingmessage").remove();
// The default Emscripten provided canvas resizing behavior is not needed,
// since we are controlling the canvas sizes here, so stub those functions out.
Browser.updateCanvasDimensions = function() {};
Browser.setCanvasSize = function() {};
// If you'd like to configure the initial canvas size to render using the resolution
// defined in UE4 DefaultEngine.ini [SystemSettings] r.setRes=WidthxHeight,
// uncomment the following two lines before calling resizeCanvas() below:
// canvasAspectRatioWidth = UE_JSlib.UE_GSystemResolution_ResX();
// canvasAspectRatioHeight = UE_JSlib.UE_GSystemResolution_ResY();
// Configure the size of the canvas and display it.
resizeCanvas();
Module['canvas'].style.display = 'block';
// Whenever the browser window size changes, relayout the canvas size on the page.
window.addEventListener('resize', resizeCanvas, false);
window.addEventListener('orientationchange', resizeCanvas, false);
// The following is needed if game is within an iframe - main window already has focus...
window.focus();
}
Module.postRun = [postRunEmscripten];
// The resizeCanvas() function recomputes the canvas size on the page as the user changes
// the browser window size.
function resizeCanvas(aboutToEnterFullscreen) {
// Configuration variables, feel free to play around with these to tweak.
var minimumCanvasHeightCssPixels = 480; // the visible size of the canvas should always be at least this high (in CSS pixels)
var minimumCanvasHeightFractionOfBrowserWindowHeight = 0.65; // and also vertically take up this much % of the total browser client area height.
if (aboutToEnterFullscreen && !aboutToEnterFullscreen.type) { // UE4 engine is calling this function right before entering fullscreen?
// If you want to perform specific resolution setup here, do so by setting Module['canvas'].width x Module['canvas'].height now,
// and configure Module['UE4_fullscreenXXX'] fields above. Most of the time, the defaults are good, so no need to resize here.
// Return true here if you want to abort entering fullscreen mode altogether.
return;
}
// The browser called resizeCanvas() to notify that we just entered fullscreen? In that case, we never react, since the strategy is
// to always set the canvas size right before entering fullscreen.
if (document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement || document.msFullscreenElement) {
return;
}
var mainArea = document.getElementById('mainarea');
var canvasRect = mainArea.getBoundingClientRect();
// Compute the unconstrained size for the div that encloses the canvas, in CSS pixel units.
var cssWidth = canvasRect.right - canvasRect.left;
var cssHeight = Math.max(minimumCanvasHeightCssPixels, canvasRect.bottom - canvasRect.top, window.innerHeight * minimumCanvasHeightFractionOfBrowserWindowHeight);
if (canvasWindowedScaleMode == 3/*NONE*/) {
// In fixed display mode, render to a statically determined WebGL render target size.
var newRenderTargetWidth = canvasAspectRatioWidth;
var newRenderTargetHeight = canvasAspectRatioHeight;
} else {
// Convert unconstrained render target size from CSS to physical pixel units.
var newRenderTargetWidth = canvasWindowedUseHighDpi ? (cssWidth * window.devicePixelRatio) : cssWidth;
var newRenderTargetHeight = canvasWindowedUseHighDpi ? (cssHeight * window.devicePixelRatio) : cssHeight;
// Apply aspect ratio constraints, if desired.
if (canvasWindowedScaleMode == 2/*ASPECT*/) {
if (cssWidth * canvasAspectRatioHeight > canvasAspectRatioWidth * cssHeight) {
newRenderTargetWidth = newRenderTargetHeight * canvasAspectRatioWidth / canvasAspectRatioHeight;
} else {
newRenderTargetHeight = newRenderTargetWidth * canvasAspectRatioHeight / canvasAspectRatioWidth;
}
}
// WebGL render target sizes are always full integer pixels in size, so rounding is critical for CSS size computations below.
newRenderTargetWidth = Math.round(newRenderTargetWidth);
newRenderTargetHeight = Math.round(newRenderTargetHeight);
}
// Very subtle but important behavior is that the size of a DOM element on a web page in CSS pixel units can be a fraction, e.g. on
// high DPI scaling displays (CSS pixel units are "virtual" pixels). If the CSS size and physical pixel size of the WebGL canvas do
// not correspond to each other 1:1 after window.devicePixelRatio scaling has been applied, the result can look blurry. Therefore always
// first compute the WebGL render target size first in physical pixels, and convert that back to CSS pixels so that the CSS pixel size
// will perfectly align up and the result look clear without scaling applied.
cssWidth = canvasWindowedUseHighDpi ? (newRenderTargetWidth / window.devicePixelRatio) : newRenderTargetWidth;
cssHeight = canvasWindowedUseHighDpi ? (newRenderTargetHeight / window.devicePixelRatio) : newRenderTargetHeight;
Module['canvas'].width = newRenderTargetWidth;
Module['canvas'].height = newRenderTargetHeight;
Module['canvas'].style.width = cssWidth + 'px';
Module['canvas'].style.height = mainArea.style.height = cssHeight + 'px';
// Tell the engine that the web page has changed the size of the WebGL render target on the canvas (Module['canvas'].width/height).
// This will update the GL viewport and propagate the change throughout the engine.
// If the CSS style size is changed, this function doesn't need to be called.
if (UE_JSlib.UE_CanvasSizeChanged) UE_JSlib.UE_CanvasSizeChanged();
}
Module['UE4_resizeCanvas'] = resizeCanvas;
Module.arguments = ['../../../SaveTheDay/SaveTheDay.uproject','-stdout',];
// we are serving via a server and it is unreal file server?
if (location.host != "" && getHTMLGetParam("cookonthefly") == "true") {
Module.arguments.push("'-filehostIp=" + location.protocol + "//" + location.host + "'");
}
function addLog(info, color) {
$("#logwindow").append("<h4><small>" + info + " </small></h4>");
}
Module.print = addLog;
Module.printErr = function(text) {
console.error(text);
};
// Module.locateFile() routes asset downloads to either gzip compressed or uncompressed assets.
Module.locateFile = function(name) {
var serveGzipped = serveCompressedAssets;
// When serving from file:// URLs, don't read .gz compressed files, because these files can't be transparently uncompressed.
var isFileProtocol = name.indexOf('file://') != -1 || location.protocol.indexOf('file') != -1;
if (isFileProtocol) {
if (!Module['shownFileProtocolWarning']) {
showWarningRibbon('Attempting to load the page via the "file://" protocol. This only works in Firefox, and even there only when not using compression, so attempting to load uncompressed assets. Please host the page on a web server and visit it via a "http://" URL.');
Module['shownFileProtocolWarning'] = true;
}
serveGzipped = false;
}
// uncompressing very large gzip files may slow down startup times.
// if (!dataFileIsGzipCompressed && name.split('.').slice(-1)[0] == 'data') serveGzipped = false;
return serveGzipped ? (name + 'gz') : name;
};
Module.getPreloadedPackage = function(remotePackageName, remotePackageSize) {
return Module['preloadedPackages'] ? Module['preloadedPackages'][remotePackageName] : null;
}
// Asynchronously appends the given script code to DOM. This is to ensure that
// browsers parse and compile the JS code parallel to all other execution.
function addScriptToDom(scriptCode) {
return new Promise(function(resolve, reject) {
var script = document.createElement('script');
var blob = (scriptCode instanceof Blob) ? scriptCode : new Blob([scriptCode], { type: 'text/javascript' });
var objectUrl = URL.createObjectURL(blob);
script.src = objectUrl;
script.onload = function() {
script.onload = script.onerror = null; // Remove these onload and onerror handlers, because these capture the inputs to the Promise and the input function, which would leak a lot of memory!
URL.revokeObjectURL(objectUrl); // Free up the blob. Note that for debugging purposes, this can be useful to comment out to be able to read the sources in debugger.
resolve();
}
script.onerror = function(e) {
script.onload = script.onerror = null; // Remove these onload and onerror handlers, because these capture the inputs to the Promise and the input function, which would leak a lot of memory!
URL.revokeObjectURL(objectUrl);
console.error('script failed to add to dom: ' + e);
console.error(scriptCode);
console.error(e);
// The onerror event sends a DOM Level 3 event error object, which does not seem to have any kind of human readable error reason (https://developer.mozilla.org/en-US/docs/Web/Events/error)
// There is another error event object at https://developer.mozilla.org/en-US/docs/Web/API/ErrorEvent, which would have an error reason. Perhaps that error event might sometimes be fired,
// but if not, guess that the error reason was an OOM, since we are dealing with large .js files.
reject(e.message || "(out of memory?)");
}
document.body.appendChild(script);
});
}
var TASK_DOWNLOADING = 0;
var TASK_COMPILING = 1;
var TASK_SHADERS = 2;
var TASK_MAIN = 3;
var loadTasks = [ 'Downloading', 'Compiling WebAssembly', 'Building shaders', 'Launching engine'];
function taskProgress(taskId, progress) {
var c = document.getElementById('compilingmessage');
if (c) c.style.display = 'block';
else return;
var l = document.getElementById('load_' + taskId);
if (!l) {
var tasks = document.getElementById('loadTasks');
if (!tasks) return;
l = document.createElement('div');
l.innerHTML = '<span id="icon_' + taskId + '" class="glyphicon glyphicon-refresh glyphicon-spin"></span> <span id="load_' + taskId + '"></span>';
tasks.appendChild(l);
l = document.getElementById('load_' + taskId);
}
if (!l.startTime) l.startTime = performance.now();
var text = loadTasks[taskId];
if (progress && progress.total) {
text += ': ' + (progress.currentShow || progress.current) + '/' + (progress.totalShow || progress.total) + ' (' + (progress.current * 100 / progress.total).toFixed(0) + '%)';
} else {
text += '...';
}
l.innerHTML = text;
}
function showErrorDialog(errorText) {
if ( errorText.indexOf('SyntaxError: ') != -1 ) { // this may be due to caching issue -- otherwise, compile time would have caught this
errorText = "NOTE: attempting to flush cache and force reload...<br>Please standby...";
setTimeout(function() {
location.reload(true);
}, 2000); // 2 seconds
}
console.error('error: ' + errorText);
var existingErrorDialog = document.getElementById('errorDialog');
if (existingErrorDialog) {
existingErrorDialog.innerHTML += '<br>' + errorText;
} else {
$('#mainarea').empty();
$('#mainarea').append('<div class="alert alert-danger centered-axis-xy" style ="min-height: 10pt" role="alert" id="errorDialog">' + errorText + '</div></div>');
}
}
function showWarningRibbon(warningText) {
var existingWarningDialog = document.getElementById('warningDialog');
if (existingWarningDialog) {
existingWarningDialog.innerHTML += '<br>' + warningText;
} else {
$('#buttonrow').prepend('<div class="alert alert-warning centered-axis-x" role="warning" id="warningDialog" style="padding-top:5px; padding-bottom: 5px">' + warningText + '</div></div>');
}
}
function taskFinished(taskId, error) {
var l = document.getElementById('load_' + taskId);
var icon = document.getElementById('icon_' + taskId);
if (l && icon) {
var totalTime = performance.now() - l.startTime;
if (!error) {
l.innerHTML = loadTasks[taskId] + ' (' + (totalTime/1000).toFixed(2) + 's)';
icon.className = 'glyphicon glyphicon-ok';
}
else {
l.innerHTML = loadTasks[taskId] + ': FAILED! ' + error;
icon.className = 'glyphicon glyphicon-remove';
showErrorDialog(loadTasks[taskId] + ' failed: <br> ' + error);
}
}
}
window.onerror = function(e) {
e = e.toString();
if (e.toLowerCase().indexOf('memory') != -1) {
e += '<br>';
if (!heuristic64BitBrowser) e += ' Try running in a 64-bit browser to resolve.';
}
showErrorDialog(e);
}
function formatBytes(bytes) {
if (bytes >= 1024*1024*1024) return (bytes / (1024*1024*1024)).toFixed(1) + ' GB';
if (bytes >= 1024*1024) return (bytes / (1024*1024)).toFixed(0) + ' MB';
if (bytes >= 1024) return (bytes / 1024).toFixed(1) + ' KB';
return bytes + ' B';
}
function reportDataBytesStoredInIndexedDB(deltaBytes) {
if (deltaBytes === null) Module['dataBytesStoredInIndexedDB'] = 0; // call with deltaBytes == null to report that DB was cleared.
else Module['dataBytesStoredInIndexedDB'] += deltaBytes;
document.getElementById('clear_indexeddb').innerText = 'Clear IndexedDB (' + formatBytes(Module['dataBytesStoredInIndexedDB']) + ')';
}
function reportDownloadProgress(url, downloadedBytes, totalBytes, finished) {
Module['assetDownloadProgress'][url] = {
current: downloadedBytes,
total: totalBytes,
finished: finished
};
var aggregated = {
current: 0,
total: 0,
finished: true
};
for(var i in Module['assetDownloadProgress']) {
aggregated.current += Module['assetDownloadProgress'][i].current;
aggregated.total += Module['assetDownloadProgress'][i].total;
aggregated.finished = aggregated.finished && Module['assetDownloadProgress'][i].finished;
}
aggregated.currentShow = formatBytes(aggregated.current);
aggregated.totalShow = formatBytes(aggregated.total);
if (aggregated.finished) taskFinished(TASK_DOWNLOADING);
else taskProgress(TASK_DOWNLOADING, aggregated);
}
function download(url, responseType) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = responseType || 'blob';
reportDownloadProgress(url, 0, 1);
xhr.onload = function() {
if (xhr.status == 0 || (xhr.status >= 200 && xhr.status < 300)) {
var len = xhr.response.size || xhr.response.byteLength;
reportDownloadProgress(url, len, len, true);
resolve(xhr.response);
} else {
taskFinished(TASK_DOWNLOADING, 'HTTP error ' + (xhr.status || 404) + ' ' + xhr.statusText + ' on file ' + url);
reject({
status: xhr.status,
statusText: xhr.statusText
});
}
};
xhr.onprogress = function(p) {
if (p.lengthComputable) reportDownloadProgress(url, p.loaded, p.total);
};
xhr.onerror = function(e) {
var isFileProtocol = url.indexOf('file://') == 0 || location.protocol.indexOf('file') != -1;
if (isFileProtocol) taskFinished(TASK_DOWNLOADING, 'HTTP error ' + (xhr.status || 404) + ' ' + xhr.statusText + ' on file ' + url +'<br>Try using a web server to avoid loading via a "file://" URL.'); // Convert the most common source of errors to a more friendly message format.
else taskFinished(TASK_DOWNLOADING, 'HTTP error ' + (xhr.status || 404) + ' ' + xhr.statusText + ' on file ' + url);
reject({
status: xhr.status || 404,
statusText: xhr.statusText
});
};
xhr.onreadystatechange = function() {
if (xhr.readyState >= xhr.HEADERS_RECEIVED) {
if (url.endsWith('gz') && (xhr.status == 0 || xhr.status == 200)) {
if (xhr.getResponseHeader('Content-Encoding') != 'gzip') {
// A fallback is to set serveCompressedAssets = false to serve uncompressed assets instead, but that is not really recommended for production use, since gzip compression shrinks
// download sizes so dramatically that omitting it for production is not a good idea.
taskFinished(TASK_DOWNLOADING, 'Downloaded a compressed file ' + url + ' without the necessary HTTP response header "Content-Encoding: gzip" specified!<br>Please configure gzip compression on this asset on the web server to serve gzipped assets!');
xhr.onload = xhr.onprogress = xhr.onerror = xhr.onreadystatechange = null; // Abandon tracking events from this XHR further.
xhr.abort();
return reject({
status: 406,
statusText: 'Not Acceptable'
});
}
// After enabling Content-Encoding: gzip, make sure that the appropriate MIME type is being used for the asset, i.e. the MIME
// type should be that of the uncompressed asset, and not the MIME type of the compression method that was used.
if (xhr.getResponseHeader('Content-Type').toLowerCase().indexOf('zip') != -1) {
function expectedMimeType(url) {
if (url.indexOf('.wasm') != -1) return 'application/wasm';
if (url.indexOf('.js') != -1) return 'application/javascript';
return 'application/octet-stream';
}
taskFinished(TASK_DOWNLOADING, 'Downloaded a compressed file ' + url + ' with incorrect HTTP response header "Content-Type: ' + xhr.getResponseHeader('Content-Type') + '"!<br>Please set the MIME type of the asset to "' + expectedMimeType(url) + '".');
xhr.onload = xhr.onprogress = xhr.onerror = xhr.onreadystatechange = null; // Abandon tracking events from this XHR further.
xhr.abort();
return reject({
status: 406,
statusText: 'Not Acceptable'
});
}
}
}
}
xhr.send(null);
});
}
function getIDBRequestErrorString(req) {
try { return req.error ? ('IndexedDB ' + req.error.name + ': ' + req.error.message) : req.result;
} catch(ex) { return null; }
}
function deleteIndexedDBStorage(dbName, onsuccess, onerror, onblocked) {
var idb = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
if (Module['dbInstance']) Module['dbInstance'].close();
if (!dbName) dbName = Module['UE4_indexedDBName'];
var req = idb.deleteDatabase(dbName);
req.onsuccess = function() { console.log('Deleted IndexedDB storage ' + dbName + '!'); reportDataBytesStoredInIndexedDB(null); if (onsuccess) onsuccess(); }
req.onerror = function(evt) {
var errorString = getIDBRequestErrorString(req);
console.error('Failed to delete IndexedDB storage ' + dbName + ', ' + errorString);
evt.preventDefault();
if (onerror) onerror(errorString);
};
req.onblocked = function(evt) {
var errorString = getIDBRequestErrorString(req);
console.error('Failed to delete IndexedDB storage ' + dbName + ', DB was blocked! ' + errorString);
evt.preventDefault();
if (onblocked) onblocked(errorString);
}
}
var enableReadFromIndexedDB = (location.search.indexOf('noidbread') == -1);
var enableWriteToIndexedDB = enableReadFromIndexedDB && (location.search.indexOf('noidbwrite') == -1);
enableReadFromIndexedDB = false;
enableWriteToIndexedDB = false;
if (!enableReadFromIndexedDB) showWarningRibbon('Running with IndexedDB access disabled.');
else if (!enableWriteToIndexedDB) showWarningRibbon('Running in read-only IndexedDB access mode.');
function storeToIndexedDB(db, key, value) {
return new Promise(function(resolve, reject) {
if (!enableWriteToIndexedDB) return reject('storeToIndexedDB: IndexedDB writes disabled by "?noidbwrite" option');
function fail(e) {
console.error('Failed to store file ' + key + ' to IndexedDB storage! error: ' + e);
if (!Module['idberrorShown']) {
showWarningRibbon('Failed to store file ' + key + ' to IndexedDB, error: ' + e);
Module['idberrorShown'] = true;
}
return reject(e);
}
if (!db) return fail('IndexedDB not available!');
if (location.protocol.indexOf('file') != -1) return reject('Loading via file://, skipping caching to IndexedDB');
try {
var transaction = db.transaction(['FILES'], 'readwrite');
var packages = transaction.objectStore('FILES');
var putRequest = packages.put(value, "file/" + Module.key + '/' + key);
putRequest.onsuccess = function(evt) {
if (value.byteLength || value.length) reportDataBytesStoredInIndexedDB(value.size || value.byteLength || value.length);
resolve(key);
};
putRequest.onerror = function(evt) {
var errorString = getIDBRequestErrorString(putRequest) || ('IndexedDB request error: ' + evt);
evt.preventDefault();
fail(errorString);
};
} catch(e) {
fail(e);
}
});
}
function fetchFromIndexedDB(db, key) {
return new Promise(function(resolve, reject) {
if (!enableReadFromIndexedDB) return reject('fetchFromIndexedDB: IndexedDB reads disabled by "?noidbread" option');
function fail(e) {
console.error('Failed to read file ' + key + ' from IndexedDB storage! error:');
console.error(e);
if (!Module['idberrorShown']) {
showWarningRibbon('Failed to read file ' + key + ' from IndexedDB, error: ' + e);
Module['idberrorShown'] = true;
}
return reject(e);
}
if (!db) return fail('IndexedDB not available!');
try {
var transaction = db.transaction(['FILES'], 'readonly');
var packages = transaction.objectStore('FILES');
var getRequest = packages.get("file/" + Module.key + '/' + key);
getRequest.onsuccess = function(evt) {
if (evt.target.result) {
var len = evt.target.result.size || evt.target.result.byteLength || evt.target.result.length;
if (len) reportDataBytesStoredInIndexedDB(len);
resolve(evt.target.result);
} else {
// Succeeded to load, but the load came back with the value of undefined, treat that as an error since we never store undefined in db.
reject();
}
};
getRequest.onerror = function(evt) {
var errorString = getIDBRequestErrorString(getRequest) || ('IndexedDB.get request error: ' + evt);
evt.preventDefault();
fail(errorString);
};
} catch(e) {
fail(e);
}
});
}
function fetchOrDownloadAndStore(db, url, responseType) {
return new Promise(function(resolve, reject) {
fetchFromIndexedDB(db, url)
.then(function(data) { return resolve(data); })
.catch(function(error) {
return download(url, responseType)
.then(function(data) {
// Treat IDB store as separate operation that's not part of the Promise chain.
/*return*/ storeToIndexedDB(db, url, data)
.then(function() { return resolve(data); })
.catch(function(error) {
console.error('Failed to store download to IndexedDB! ' + error);
return resolve(data); // succeeded download, but failed to store - ignore failure in that case and just proceed to run by calling the success handler.
})
})
.catch(function(error) { return reject(error); })
});
});
}
function openIndexedDB(dbName, dbVersion) {
return new Promise(function(resolve, reject) {
if (!enableReadFromIndexedDB) return reject('openIndexedDB: IndexedDB disabled by "?noidbread" option');
try {
var idb = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
var openRequest = idb.open(dbName, dbVersion);
} catch(e) { return reject(e); }
openRequest.onupgradeneeded = function(evt) {
var db = evt.target.result;
if (db.objectStoreNames.contains('FILES')) db.deleteObjectStore('FILES');
db.createObjectStore('FILES');
};
openRequest.onsuccess = function(evt) {
resolve(evt.target.result);
};
openRequest.onerror = function(evt) {
var errorString = getIDBRequestErrorString(openRequest) || ('IndexedDB request error: ' + evt);
evt.preventDefault();
reject(errorString);
};
});
}
Module['instantiateWasm'] = function(info, receiveInstance) {
Module['wasmDownloadAction'].then(function(downloadResults) {
taskProgress(TASK_COMPILING);
var wasmInstantiate = WebAssembly.instantiate(downloadResults.wasmModule || new Uint8Array(downloadResults.wasmBytes), info);
return wasmInstantiate.then(function(output) {
var instance = output.instance || output;
var module = output.module;
taskFinished(TASK_COMPILING);
Module['wasmInstantiateActionResolve'](instance);
receiveInstance(instance);
// After a successful instantiation, attempt to save the compiled Wasm Module object to IndexedDB.
if (!downloadResults.fromIndexedDB) {
storeToIndexedDB(downloadResults.db, 'wasmModule', module).catch(function() {
// If the browser did not support storing Wasm Modules to IndexedDB, try to store the Wasm instance instead.
return storeToIndexedDB(downloadResults.db, 'wasmBytes', downloadResults.wasmBytes);
});
}
});
}).catch(function(error) {
$ ('#mainarea').empty();
$ ('#mainarea').append('<div class="alert alert-danger centered-axis-xy" style ="min-height: 10pt" role="alert">WebAssembly instantiation failed: <br> ' + error + '</div></div>');
});
return {};
}
// Given a blob, asynchronously reads the byte contents of that blob to an arraybuffer and returns it as a Promise.
function readBlobToArrayBuffer(blob) {
return new Promise(function(resolve, reject) {
var fileReader = new FileReader();
fileReader.onload = function() { resolve(this.result); }
fileReader.onerror = function(e) { reject(e); }
fileReader.readAsArrayBuffer(blob);
});
}
function compileShadersFromJson(jsonData) {
var shaderPrograms = [];
if (jsonData instanceof ArrayBuffer) jsonData = new TextDecoder('utf-8').decode(new DataView(jsonData));
var programsDict = JSON.parse(jsonData);
for(var i in programsDict) {
shaderPrograms.push(programsDict[i]);
}
var gl = Module['preinitializedWebGLContext'];
Module['precompiledShaders'] = [];
Module['precompiledPrograms'] = [];
Module['glIDCounter'] = 1;
Module['precompiledUniforms'] = [null];
var promise = new Promise(function(resolve, reject) {
var nextProgramToBuild = 0;
function buildProgram() {
if (nextProgramToBuild >= shaderPrograms.length) {
taskFinished(TASK_SHADERS);
return resolve();
}
var p = shaderPrograms[nextProgramToBuild++];
taskProgress(TASK_SHADERS, {current: nextProgramToBuild, total: shaderPrograms.length });
var program = gl.createProgram();
function lineNumberize(str) {
str = str.split('\n');
for(var i = 0; i < str.length; ++i) str[i] = (i<9?' ':'') + (i<99?' ':'') + (i+1) + ': ' + str[i];
return str.join('\n');
}
var vs = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vs, p.vs);
gl.compileShader(vs);
var success = gl.getShaderParameter(vs, gl.COMPILE_STATUS);
var compileLog = gl.getShaderInfoLog(vs);
if (compileLog) compileLog = compileLog.trim();
if (compileLog) console.error('Compiling vertex shader: ' + lineNumberize(p.vs));
if (!success) console.error('Vertex shader compilation failed!');
if (compileLog) console.error('Compilation log: ' + compileLog);
if (!success) return reject('Vertex shader compilation failed: ' + compileLog);
gl.attachShader(program, vs);
Module['precompiledShaders'].push({
vs: p.vs,
shader: vs,
program: program
});
var fs = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fs, p.fs);
gl.compileShader(fs);
var success = gl.getShaderParameter(fs, gl.COMPILE_STATUS);
var compileLog = gl.getShaderInfoLog(fs);
if (compileLog) compileLog = compileLog.trim();
if (compileLog) console.error('Compiling fragment shader: ' + lineNumberize(p.fs));
if (!success) console.error('Fragment shader compilation failed!');
if (compileLog) console.error('Compilation log: ' + compileLog);
if (!success) return reject('Fragment shader compilation failed: ' + compileLog);
gl.attachShader(program, fs);
Module['precompiledShaders'].push({
fs: p.fs,
shader: fs,
program: program
});
for(var name in p.attribs) {
gl.bindAttribLocation(program, p.attribs[name], name);
}
gl.linkProgram(program);
var success = gl.getProgramParameter(program, gl.LINK_STATUS);
var linkLog = gl.getProgramInfoLog(program);
if (linkLog) linkLog = linkLog.trim();
if (linkLog) console.error('Linking shader program, vs: \n' + lineNumberize(p.vs) + ', \n fs:\n' + lineNumberize(p.fs));
if (!success) console.error('Shader program linking failed!');
if (linkLog) console.error('Link log: ' + linkLog);