-
Notifications
You must be signed in to change notification settings - Fork 0
/
renpy-pre.js
955 lines (742 loc) · 29.4 KB
/
renpy-pre.js
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
/*
Copyright 2019-2021 Sylvain Beucler
Copyright 2022 Teyut <[email protected]>
Copyright 2019-2022 Tom Rothamel <[email protected]>
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
Module = window.Module || { };
Module.preRun = Module.preRun || [ ];
(function () {
/***************************************************************************
* Report messages, errors, and progress.
**************************************************************************/
// The div containing the status and progress bar.
let statusDiv = document.getElementById("statusDiv");
let statusTextDiv = document.getElementById("statusTextDiv");
let statusProgress = document.getElementById("statusProgress");
// The timeout before the status div hides itself.
let statusTimeout = null;
// The status message.
let statusText = "";
// How long before the status div starts hiding, in seconds.
const STATUS_TIMEOUT = 5000;
// The last time the progress was updated.
let lastProgressTime = 0;
// Has an error been reported?
let errorReported = false;
// Should output only go to the console?
let printConsoleOnly = false;
/**
* Hide the status div. Once it's hidden, clears the status text.
*/
function hideStatus() {
if (errorReported) {
return;
}
statusDiv.classList.remove("visible");
statusDiv.classList.add("hidden");
statusTimeout = setTimeout(() => {
statusText = "";
}, 250);
}
/**
* Show the status div.
*/
function showStatus() {
statusDiv.classList.remove("hidden");
statusDiv.classList.add("visible");
statusTextDiv.scrollTop = statusTextDiv.scrollHeight;
statusProgress.style.display = "none";
}
/**
* Cancels the timeout that hides the status div.
*/
function cancelStatusTimeout() {
if (statusTimeout) {
clearTimeout(statusTimeout);
statusTimeout = null;
}
}
/**
* Start the timeout that hides the status div.
*/
function startStatusTimeout() {
cancelStatusTimeout();
statusTimeout = setTimeout(hideStatus, STATUS_TIMEOUT);
}
function printCommon(s) {
cancelStatusTimeout();
lastProgressTime = 0;
if (statusText) {
statusText += "<br>";
}
if (s == "" && !errorReported) {
statusText = "";
return;
}
for (let i of s.split("\n")) {
if (i.length > 0) {
console.log(i);
}
}
if (printConsoleOnly) {
return;
}
s = String(s);
s = s.replace(/&/g, "&");
s = s.replace(/</g, "<");
s = s.replace(/>/g, ">");
s = s.replace('\n', '<br />', 'g');
statusText += s;
statusTextDiv.innerHTML = statusText;
showStatus();
}
/**
* Reports a message that will eventually be hidden.
*/
function printMessage(s) {
if (s.startsWith("warning: ") || s.startsWith("wasm streaming compile failed") || s.startsWith("falling back to ArrayBuffer") ) {
console.log(s);
return;
}
printCommon(s);
startStatusTimeout();
}
function reportError(s, e) {
if (e) {
console.error(e, e.stack);
s += ": " + e.message;
}
s += "\nMore information may be available in the browser console or contained in the log.";
printCommon(s);
errorReported = true;
try {
Module.addRunDependency("error");
} catch (e) {
window.stop();
}
}
/**
* Updates the progress bar.
*/
function progress(done, total) {
if (errorReported) {
return;
}
let now = +Date.now();
if ((now < lastProgressTime + 32) && (done < total) && (done > 1)) {
return
}
lastProgressTime = now;
cancelStatusTimeout();
showStatus();
if (total) {
statusProgress.value = done;
statusProgress.max = total;
statusProgress.style.display = "block";
}
startStatusTimeout();
}
window.progress = progress;
Module.print = printMessage;
Module.printErr = printMessage;
/***************************************************************************
* Browser capability checks.
**************************************************************************/
// Report the lack of WebAssembly support.
if (typeof WebAssembly !== 'object') {
reportError("This browser does not support WebAssembly.");
}
// Report the lack of the fetch function.
if (typeof fetch !== 'function') {
reportError("This browser does not support fetch.");
}
// Clear error when running without a server.
if (location.href.startsWith('file://')) {
reportError("This browser requires the game to be run from a web server (i.e. double-clicking on index.html won't work).");
}
/***************************************************************************
* Emscripten initialization and termination.
**************************************************************************/
/** Set up the canvas. */
let canvas = document.getElementById('canvas');
/** Set when the webGlContext is lost. */
window.webglContextLost = false;
/** Set when the webGlContext is restored. Cleared by Ren'Py in core.py. */
window.webglContextRestored = false;
canvas.addEventListener("webglcontextlost", (e) => {
window.webglContextRestored = false;
window.webglContextLost = true;
e.preventDefault();
}, false);
canvas.addEventListener("webglcontextrestored", (e) => {
window.webglContextLost = false;
window.webglContextRestored = true;
}, false);
canvas.addEventListener('mouseenter', function (e) { window.focus() });
canvas.addEventListener('click', function (e) { window.focus() });
Module.canvas = canvas;
window.presplashEnd = () => {
document.getElementById('presplash').remove();
cancelStatusTimeout();
hideStatus();
};
window.atExit = () => {
canvas.remove();
reportError("The game exited unexpectedly.");
};
Module.onAbort = () => {
canvas.remove();
reportError("The game aborted unexpectedly.");
};
/**
* Initialize the filesystem.
*/
function initFs() {
// Create the save directory, and mount the IDBFS filesystem.
try {
Module.addRunDependency('initFs');
FS.mkdir('/home/web_user/.renpy');
FS.mount(IDBFS, {}, '/home/web_user/.renpy');
FS.syncfs(true, (err) => {
if (err) {
printMessage("Error syncing IDBFS: " + err);
printMessage("The game may not be able to save properly.");
}
Module.removeRunDependency('initFs');
});
} catch (e) {
reportError("Could not create ~/.renpy/", e);
}
}
Module.preRun.push(initFs);
// The size of the data and gamezip files.
let dataSize = 0;
let gameZipSize = 0;
// The number of bytes downloaded.
let dataDownloaded = 0;
let gameZipDownloaded = 0;
// Have we issued the data and gameZip prompts?
let dataPrompt = false;
let gameZipPrompt = false;
function updateDownloadProgress() {
if (dataSize == 0) {
return;
}
if (dataDownloaded < dataSize || gameZipSize == 0) {
if (!dataPrompt) {
printMessage("");
printMessage("Downloading engine...");
dataPrompt = true;
}
progress(dataDownloaded, dataSize);
return;
}
if (!gameZipPrompt) {
printMessage("");
printMessage("Downloading game data...");
gameZipPrompt = true;
}
progress(gameZipDownloaded, gameZipSize);
}
Module.setStatus = function (s) {
var m = s.match(/([^(]+)\((\d+(\.\d+)?)\/(\d+)\)/);
if (m) {
dataDownloaded = parseInt(m[2]);
dataSize = parseInt(m[4]);
updateDownloadProgress();
return;
}
console.log(s);
}
async function loadGameZip() {
try {
let response = await fetch('game.zip');
if (!response.ok) {
reportError("Could not load game.zip: " + response.status + " " + response.statusText);
}
gameZipSize = parseInt(response.headers.get('Content-Length'), 10);
if(Number.isNaN(gameZipSize)) gameZipSize = 0;
let reader = await response.body.getReader();
let f = FS.open('/game.zip', 'w');
while (true) {
let { done, value } = await reader.read();
if (done) {
break;
}
FS.write(f, value, 0, value.length);
gameZipDownloaded += value.length;
updateDownloadProgress();
}
FS.close(f);
} catch (e) {
reportError("Could not download game.zip", e);
}
}
function runLoadGameZip() {
Module.addRunDependency('loadGameZip');
loadGameZip().then(() => {
Module.removeRunDependency('loadGameZip');
});
}
Module['preRun'].push(runLoadGameZip);
/***************************************************************************
*
**************************************************************************/
let cmd_queue = [];
let cur_cmd = undefined;
let cmd_debug = false;
function cmd_log(...args) {
if (cmd_debug) console.debug(...args);
}
/** This functions is called by the wrapper script at the end of script execution. */
function cmd_callback(result) {
cmd_log('cmd_callback', result);
if (cur_cmd === undefined) {
console.error('Unexpected command result', result);
return;
}
try {
if (result.error !== undefined) {
cmd_log('ERROR', result.name, result.error, result.traceback);
const e = new Error(result.error);
e.name = result.name;
e.traceback = result.traceback;
cur_cmd.reject(e);
} else {
cmd_log('SUCCESS', result.data);
cur_cmd.resolve(result.data);
}
} finally {
cur_cmd = undefined;
send_next_cmd();
}
}
window._renpy_cmd_callback = cmd_callback;
/** Prepare and send the next command to be executed if any. */
function send_next_cmd() {
if (cmd_queue.length == 0) return
cur_cmd = cmd_queue.shift();
cmd_log('send_next_cmd', cur_cmd);
// Convert script to base64 to prevent having to escape
// the script content as a Python string
const script_b64 = btoa(cur_cmd.py_script);
const wrapper = 'import base64, emscripten, json, traceback;\n'
+ 'try:'
+ "result = None;"
+ "exec(base64.b64decode('" + script_b64 + "').decode('utf-8'));"
+ "result = json.dumps(dict(data=result));"
+ "\n"
+ "except Exception as e:"
+ "result = json.dumps(dict(error=str(e), name=e.__class__.__name__, traceback=traceback.format_exc()));"
+ "\n"
+ "emscripten.run_script('_renpy_cmd_callback(%s)' % (result,));";
cmd_log(wrapper);
// Write script to the global variable Ren'Py is monitoring
window._renpy_cmd = wrapper;
}
/** Add a command to the queue and execute it if the queue was empty. */
function add_cmd(py_script, resolve, reject) {
const cmd = { py_script: py_script, resolve: resolve, reject: reject };
cmd_log('add_cmd', cmd);
cmd_queue.push(cmd);
if (cur_cmd === undefined) send_next_cmd();
}
/* Global definitions */
/** Execute Python statements in Ren'Py Python's thread. The statements are executed
* using the renpy.python.py_exec() function, and the value of the "result" variable
* is passed to the resolve callback. In case of error, an Error instance is passed
* to the reject callback, with an extra "traceback" property.
* @param py_script The Python script to execute.
* @return A promise which resolves with the statements result.
*/
renpy_exec = function (py_script) {
return new Promise((resolve, reject) => {
add_cmd(py_script, resolve, reject);
});
};
window.renpy_exec = renpy_exec;
/** Helper function to get the value of a Ren'Py variable.
* @param name The variable name (e.g., "build.name").
* @return A promise which resolves with the variable value.
*/
renpy_get = function (name) {
return new Promise((resolve, reject) => {
renpy_exec('result = ' + name)
.then(resolve).catch(reject);
});
};
window.renpy_get = renpy_get;
/** Helper function to set the value of a Ren'Py variable.
* @param name The variable name (e.g., "build.name").
* @param value The value to set. It should either be a basic JS type that
* will be converted to JSON, or a Python expression. The raw
* parameter must be set to true for the latter case.
* @param raw (optional) If true, value is a valid Python expression.
* Otherwise, it must be a basic JS type.
* @return A promise which resolves with true in case of success
* and fails otherwise.
*/
renpy_set = function (name, value, raw) {
let script;
if (raw) {
script = name + " = " + value + "; result = True";
} else {
// Using base64 as it is unclear if we can use the output
// of JSON.stringify() directly as a Python string
script = 'import base64, json; '
+ name + " = json.loads(base64.b64decode('"
+ btoa(JSON.stringify(value))
+ "').decode('utf-8')); result = True";
}
return new Promise((resolve, reject) => {
renpy_exec(script)
.then(resolve).catch(reject);
});
};
window.renpy_set = renpy_set;
/***************************************************************************
* Context menu.
**************************************************************************/
const menu = document.getElementById('ContextMenu');
const contextContainer = document.getElementById('ContextContainer');
document.getElementById('ContextButton').addEventListener('click', function (e) {
if (menu.style.display == 'none') {
menu.style.display = 'block';
contextContainer.classList.add("shown");
} else {
menu.style.display = 'none';
contextContainer.classList.remove("shown");
}
e.preventDefault();
});
menu.addEventListener('click', function (e) {
if (e.target.tagName == 'A') {
// Close context menu when a menu item is selected
menu.style.display = 'none';
}
});
async function onSavegamesImport(input) {
reader = new FileReader();
reader.onload = function (e) {
FS.writeFile('savegames.zip', new Uint8Array(e.target.result));
renpy_exec('result = renpy.savelocation.unzip_saves()').then((result) => {
FS.syncfs(false, function (err) {
if (err) {
console.trace();
console.log(err, err.message);
printMessage("Warning: cannot import savegames: write error: " + err.message );
} else {
renpy_exec('renpy.loadsave.location.scan()').then(result => {
printMessage("Saves imported successfully.");
}).catch(error => {
console.error('Cannot rescan saves folder:', error);
printMessage("Saves imported - restart game to apply.");
});
}
});
}).catch(error => {
console.error('Cannot import savegames', error);
printMessage("Couldn't import the savegames: " + error.message);
})
}
reader.readAsArrayBuffer(input.files[0])
input.type = ''; input.type = 'file'; // reset field
}
window.onSavegamesImport = onSavegamesImport;
function onSavegamesExport() {
renpy_exec('result = renpy.savelocation.zip_saves()').then((ret) => {
if (ret) {
FSDownload('savegames.zip', 'application/zip');
printMessage("Saves exported successfully.\n");
}
});
}
window.onSavegamesExport = onSavegamesExport;
function FSDownload(filename, mimetype) {
console.log('download', filename);
var a = document.createElement('a');
a.download = filename.replace(/.*\//, '');
try {
a.href = window.URL.createObjectURL(new Blob([FS.readFile(filename)],
{ type: mimetype || '' }));
} catch (e) {
Module.print("Error opening " + filename + "\n");
return;
}
document.body.appendChild(a);
a.click();
// delay clean-up to avoid iOS issue:
// The operation couldn’t be completed. (WebKitBlobResource error 1.)
setTimeout(function () {
window.URL.revokeObjectURL(a.href);
document.body.removeChild(a);
}, 1000);
}
window.FSDownload = FSDownload;
/***************************************************************************
* Precaching.
**************************************************************************/
function loadCache() {
try {
navigator.serviceWorker.controller.postMessage(["loadCache"]);
} catch (e) {
// pass
}
async function loadCacheWorker() {
let response = await fetch("pwa_catalog.json");
let catalog = await response.json();
let cachedCatalog;
try {
let cachedCatalogResponse = await fetch("pwa_catalog.json?cached")
cachedCatalog = await cachedCatalogResponse.json();
} catch (e) {
console.log("No cached catalog found.");
cachedCatalog = { version: -1 };
}
if (cachedCatalog.version == catalog.version) {
return;
}
printMessage("");
printMessage("Preloading game files into browser cache...")
progress(0, catalog.files.length);
for (let i = 0; i < catalog.files.length; i++) {
let response = await fetch(catalog.files[i]);
await response.blob();
progress(i + 1, catalog.files.length);
}
cancelStatusTimeout();
hideStatus();
// This will add the catalog to the cache, such that
// fetch("pwa_catalog.json?cached") will return it.
fetch("pwa_catalog.json?uncached");
}
loadCacheWorker();
}
window.loadCache = loadCache;
function clearCache() {
try {
navigator.serviceWorker.controller.postMessage(["clearCache"]);
} catch (e) {
// pass
}
localStorage.cacheVersion = -1;
}
window.clearCache = clearCache;
/***************************************************************************
* Text input.
**************************************************************************/
const inputDiv = document.getElementById("inputDiv");
const inputForm = document.getElementById("inputForm");
const inputPrompt = document.getElementById("inputPrompt");
const inputText = document.getElementById("inputText");
// This stores the input after enter is pressed.
window.inputResult = null;
function submitInput(e) {
e.preventDefault();
window.inputResult = inputText.value;
}
inputForm.addEventListener("submit", submitInput);
inputDiv.addEventListener("keydown", function (e) { e.stopPropagation(); });
inputDiv.addEventListener("keyup", function (e) { e.stopPropagation(); });
inputDiv.addEventListener("keypress", function (e) { e.stopPropagation(); });
inputDiv.addEventListener("mousemove", function (e) { e.stopPropagation(); });
inputDiv.addEventListener("mousedown", function (e) { e.stopPropagation(); });
inputDiv.addEventListener("mouseup", function (e) { e.stopPropagation(); });
inputDiv.addEventListener("touchstart", function (e) { e.stopPropagation(); });
inputDiv.addEventListener("touchend", function (e) { e.stopPropagation(); });
inputDiv.addEventListener("touchcancel", function (e) { e.stopPropagation(); });
inputDiv.addEventListener("touchmove", function (e) { e.stopPropagation(); });
let inputAllow = null;
let inputExclude = null;
inputText.addEventListener("input", (e) => {
let newValue = "";
for (let c of inputText.value) {
if (inputAllow && !inputAllow.includes(c)) {
continue;
}
if (inputExclude && inputExclude.includes(c)) {
continue;
}
newValue += c;
}
if (newValue != inputText.value) {
let end = inputText.selectionEnd;
inputText.value = newValue;
inputText.setSelectionRange(end-1, end-1);
}
});
function startInput(prompt, value, allow, exclude, mask) {
window.inputResult = null;
inputDiv.classList.remove("hidden");
inputDiv.classList.add("visible");
while (inputPrompt.firstChild) {
inputPrompt.removeChild(inputPrompt.firstChild);
}
let promptText = document.createTextNode(prompt);
inputPrompt.appendChild(promptText);
inputText.value = value;
inputText.focus();
inputAllow = allow;
inputExclude = exclude;
if (mask) {
inputText.type = "password";
} else {
inputText.type = "text";
}
}
window.startInput = startInput;
function endInput() {
inputDiv.classList.remove("visible");
inputDiv.classList.add("hidden");
}
window.endInput = endInput;
/***************************************************************************
* Fetch.
***************************************************************************/
let fetchId = 1;
let fetchResult = { };
/**
* Fetch a file from the server.
*
* @param method The HTTP method to use.
* @param url The URL to fetch.
* @param inFile The file to send to the server. A string giving the file name, or null for no file.
* @param outFile The file to write the response to. A string giving the file name, or null for no file.
*
* @return A string giving the result of the fetch. The first word is the status, which is one of "OK", "ERROR", or "PENDING", followed by the HTTP status code and status text.
*/
function fetchFile(method, url, inFile, outFile) {
let id = fetchId++;
fetchResult[id] = "PENDING Fetch in progress.";
async function fetchFileWork() {
try {
let content = ''
let options = { method: method };
if (inFile) {
options.body = FS.readFile(inFile, { encoding: 'binary' });
}
let response = await fetch(url, options);
if (response.ok) {
if (outFile) {
let ab = await response.arrayBuffer();
FS.writeFile(outFile, new Uint8Array(ab));
}
fetchResult[id] = "OK " + response.status + " " + response.statusText;
} else{
fetchResult[id] = "ERROR " + response.status + " " + response.statusText;
}
} catch (err) {
fetchResult[id] = "ERROR " + err;
console.error(err);
}
}
fetchFileWork();
return id;
}
function fetchFileResult(id) {
let result = fetchResult[id];
if (! result.startsWith("PENDING")) {
delete fetchResult[id];
}
return result || "ERROR Fetch ID not found.";
}
window.fetchFile = fetchFile;
window.fetchFileResult = fetchFileResult;
/***************************************************************************
* "Hidden" developer functions.
**************************************************************************/
function downloadBytecode() {
FSDownload('/game/cache/bytecode-311.rpyb', 'application/octet-stream');
}
window.downloadBytecode = downloadBytecode;
function traceSleep() {
printConsoleOnly = true;
renpy_exec('import emscripten; emscripten.TRACE = True')
}
window.traceSleep = traceSleep;
function loseContext() {
let e = canvas.getContext("webgl2").getExtension("WEBGL_lose_context");
e.loseContext();
setTimeout(function () {
e.restoreContext();
}, 1000);
}
window.loseContext = loseContext;
Module.preRun.push(() => {
// Replace doRequestFullscreen() and JSEvents_requestFullscreen() with our own
// implementations to switch to fullscreen faster.
window.doRequestFullscreen = function(target, strategy) {
if (!JSEvents.fullscreenEnabled())
return -1;
target = findEventTarget(target);
if (!target)
return -4;
if (!target.requestFullscreen && !target.webkitRequestFullscreen) {
return -3
}
var canPerformRequests = JSEvents.canPerformEventHandlerRequests();
if (navigator.userActivation && navigator.userActivation.isActive) {
// Use transient activation status for browsers that support it
canPerformRequests = true;
}
if (!canPerformRequests) {
if (strategy.deferUntilInEventHandler) {
if (target.requestFullscreen) {
// Try requesting fullscreen mode now and only defer if the Promise fails
JSEvents_requestFullscreen(target, strategy, true);
return 1
}
JSEvents.deferCall(JSEvents_requestFullscreen, 1, [target, strategy]);
return 1
}
return -2
}
return JSEvents_requestFullscreen(target, strategy)
};
window.JSEvents_requestFullscreen = function(target, strategy, retry) {
if ((strategy.scaleMode != 0 || strategy.canvasResolutionScaleMode != 0) && retry !== 0) {
JSEvents_resizeCanvasForFullscreen(target, strategy)
}
if (target.requestFullscreen) {
target.requestFullscreen()
.catch(() => {
if (retry) {
// Defer to next input event
// (retry is set to 0 to prevent resizing the canvas again as this
// erases the old canvas size with the fullscreen size)
JSEvents.deferCall(JSEvents_requestFullscreen, 1, [target, strategy, 0]);
}
});
} else if (target.webkitRequestFullscreen) {
// No result returned from webkitRequestFullscreen() (old and deprecated API)
target.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT)
} else {
return JSEvents.fullscreenEnabled() ? -3 : -1
}
currentFullscreenStrategy = strategy;
if (strategy.canvasResizedCallback) {
(function(a1, a2, a3) {
return dynCall_iiii.apply(null, [strategy.canvasResizedCallback, a1, a2, a3])
}
)(37, 0, strategy.canvasResizedCallbackUserData)
}
return 0
};
});
})();