forked from echamudi/opencv-wasm
-
Notifications
You must be signed in to change notification settings - Fork 1
/
opencv.js
6104 lines (6023 loc) · 328 KB
/
opencv.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
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
(function() {
/* [email protected] */
let opencvWasmBinaryFile = './opencv.wasm';
return (function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(function() {
return (root.cv = factory());
});
} else if (typeof module === 'object' && module.exports) {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory();
} else if (typeof window === 'object') {
// Browser globals
root.cv = factory();
} else if (typeof importScripts === 'function') {
// Web worker
root.cv = factory();
} else {
// Other shells, e.g. d8
root.cv = factory();
}
}(this, function() {
var cv = (() => {
var _scriptName = typeof document != 'undefined' ? document.currentScript?.src : undefined;
if (typeof __filename != 'undefined') _scriptName ||= __filename;
return (
function(moduleArg = {}) {
var moduleRtn;
var Module = moduleArg;
var readyPromiseResolve, readyPromiseReject;
var readyPromise = new Promise((resolve, reject) => {
readyPromiseResolve = resolve;
readyPromiseReject = reject
});
var ENVIRONMENT_IS_WEB = typeof window == "object";
var ENVIRONMENT_IS_WORKER = typeof importScripts == "function";
var ENVIRONMENT_IS_NODE = typeof process == "object" && typeof process.versions == "object" && typeof process.versions.node == "string";
if (ENVIRONMENT_IS_NODE) {}
var moduleOverrides = Object.assign({}, Module);
var arguments_ = [];
var thisProgram = "./this.program";
var quit_ = (status, toThrow) => {
throw toThrow
};
var scriptDirectory = "";
function locateFile(path) {
if (Module["locateFile"]) {
return Module["locateFile"](path, scriptDirectory)
}
return scriptDirectory + path
}
var read_, readAsync, readBinary;
if (ENVIRONMENT_IS_NODE) {
var fs = require("fs");
var nodePath = require("path");
scriptDirectory = __dirname + "/";
read_ = (filename, binary) => {
filename = isFileURI(filename) ? new URL(filename) : nodePath.normalize(filename);
return fs.readFileSync(filename, binary ? undefined : "utf8")
};
readBinary = filename => {
var ret = read_(filename, true);
if (!ret.buffer) {
ret = new Uint8Array(ret)
}
return ret
};
readAsync = (filename, onload, onerror, binary = true) => {
filename = isFileURI(filename) ? new URL(filename) : nodePath.normalize(filename);
fs.readFile(filename, binary ? undefined : "utf8", (err, data) => {
if (err) onerror(err);
else onload(binary ? data.buffer : data)
})
};
if (!Module["thisProgram"] && process.argv.length > 1) {
thisProgram = process.argv[1].replace(/\\/g, "/")
}
arguments_ = process.argv.slice(2);
quit_ = (status, toThrow) => {
process.exitCode = status;
throw toThrow
}
} else if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) {
if (ENVIRONMENT_IS_WORKER) {
scriptDirectory = self.location.href
} else if (typeof document != "undefined" && document.currentScript) {
scriptDirectory = document.currentScript.src
}
if (_scriptName) {
scriptDirectory = _scriptName
}
if (scriptDirectory.startsWith("blob:")) {
scriptDirectory = ""
} else {
scriptDirectory = scriptDirectory.substr(0, scriptDirectory.replace(/[?#].*/, "").lastIndexOf("/") + 1)
} {
read_ = url => {
var xhr = new XMLHttpRequest;
xhr.open("GET", url, false);
xhr.send(null);
return xhr.responseText
};
if (ENVIRONMENT_IS_WORKER) {
readBinary = url => {
var xhr = new XMLHttpRequest;
xhr.open("GET", url, false);
xhr.responseType = "arraybuffer";
xhr.send(null);
return new Uint8Array(xhr.response)
}
}
readAsync = (url, onload, onerror) => {
if (isFileURI(url)) {
var xhr = new XMLHttpRequest;
xhr.open("GET", url, true);
xhr.responseType = "arraybuffer";
xhr.onload = () => {
if (xhr.status == 200 || xhr.status == 0 && xhr.response) {
onload(xhr.response);
return
}
onerror()
};
xhr.onerror = onerror;
xhr.send(null);
return
}
fetch(url, {
credentials: "same-origin"
}).then(response => {
if (response.ok) {
return response.arrayBuffer()
}
return Promise.reject(new Error(response.status + " : " + response.url))
}).then(onload, onerror)
}
}
} else {}
var out = Module["print"] || console.log.bind(console);
var err = Module["printErr"] || console.error.bind(console);
Object.assign(Module, moduleOverrides);
moduleOverrides = null;
if (Module["arguments"]) arguments_ = Module["arguments"];
if (Module["thisProgram"]) thisProgram = Module["thisProgram"];
if (Module["quit"]) quit_ = Module["quit"];
var wasmBinary;
if (Module["wasmBinary"]) wasmBinary = Module["wasmBinary"];
var wasmMemory;
var ABORT = false;
var EXITSTATUS;
var HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAPF64;
function updateMemoryViews() {
var b = wasmMemory.buffer;
Module["HEAP8"] = HEAP8 = new Int8Array(b);
Module["HEAP16"] = HEAP16 = new Int16Array(b);
Module["HEAPU8"] = HEAPU8 = new Uint8Array(b);
Module["HEAPU16"] = HEAPU16 = new Uint16Array(b);
Module["HEAP32"] = HEAP32 = new Int32Array(b);
Module["HEAPU32"] = HEAPU32 = new Uint32Array(b);
Module["HEAPF32"] = HEAPF32 = new Float32Array(b);
Module["HEAPF64"] = HEAPF64 = new Float64Array(b)
}
var __ATPRERUN__ = [];
var __ATINIT__ = [];
var __ATPOSTRUN__ = [];
var runtimeInitialized = false;
function preRun() {
if (Module["preRun"]) {
if (typeof Module["preRun"] == "function") Module["preRun"] = [Module["preRun"]];
while (Module["preRun"].length) {
addOnPreRun(Module["preRun"].shift())
}
}
callRuntimeCallbacks(__ATPRERUN__)
}
function initRuntime() {
runtimeInitialized = true;
if (!Module["noFSInit"] && !FS.init.initialized) FS.init();
FS.ignorePermissions = false;
TTY.init();
callRuntimeCallbacks(__ATINIT__)
}
function postRun() {
if (Module["postRun"]) {
if (typeof Module["postRun"] == "function") Module["postRun"] = [Module["postRun"]];
while (Module["postRun"].length) {
addOnPostRun(Module["postRun"].shift())
}
}
callRuntimeCallbacks(__ATPOSTRUN__)
}
function addOnPreRun(cb) {
__ATPRERUN__.unshift(cb)
}
function addOnInit(cb) {
__ATINIT__.unshift(cb)
}
function addOnPostRun(cb) {
__ATPOSTRUN__.unshift(cb)
}
var runDependencies = 0;
var runDependencyWatcher = null;
var dependenciesFulfilled = null;
function getUniqueRunDependency(id) {
return id
}
function addRunDependency(id) {
runDependencies++;
Module["monitorRunDependencies"]?.(runDependencies)
}
function removeRunDependency(id) {
runDependencies--;
Module["monitorRunDependencies"]?.(runDependencies);
if (runDependencies == 0) {
if (runDependencyWatcher !== null) {
clearInterval(runDependencyWatcher);
runDependencyWatcher = null
}
if (dependenciesFulfilled) {
var callback = dependenciesFulfilled;
dependenciesFulfilled = null;
callback()
}
}
}
function abort(what) {
Module["onAbort"]?.(what);
what = "Aborted(" + what + ")";
err(what);
ABORT = true;
EXITSTATUS = 1;
what += ". Build with -sASSERTIONS for more info.";
var e = new WebAssembly.RuntimeError(what);
readyPromiseReject(e);
throw e
}
var dataURIPrefix = "data:application/octet-stream;base64,";
var isDataURI = filename => filename.startsWith(dataURIPrefix);
var isFileURI = filename => filename.startsWith("file://");
function findWasmBinary() {
var f = "opencv_js.wasm";
if (!isDataURI(f)) {
return locateFile(f)
}
return f
}
var wasmBinaryFile;
function getBinarySync(file) {
if (file == wasmBinaryFile && wasmBinary) {
return new Uint8Array(wasmBinary)
}
if (readBinary) {
return readBinary(file)
}
throw 'sync fetching of the wasm failed: you can preload it to Module["wasmBinary"] manually, or emcc.py will do that for you when generating HTML (but not JS)'
}
function instantiateSync(file, info) {
var module;
var binary = getBinarySync(file);
module = new WebAssembly.Module(binary);
var instance = new WebAssembly.Instance(module, info);
return [instance, module]
}
function getWasmImports() {
return {
a: wasmImports
}
}
function createWasm() {
var info = getWasmImports();
function receiveInstance(instance, module) {
wasmExports = instance.exports;
wasmMemory = wasmExports["Z"];
updateMemoryViews();
wasmTable = wasmExports["ba"];
addOnInit(wasmExports["_"]);
removeRunDependency("wasm-instantiate");
return wasmExports
}
addRunDependency("wasm-instantiate");
if (Module["instantiateWasm"]) {
try {
return Module["instantiateWasm"](info, receiveInstance)
} catch (e) {
err(`Module.instantiateWasm callback failed with error: ${e}`);
readyPromiseReject(e)
}
}
if (!wasmBinaryFile) wasmBinaryFile = findWasmBinary();
var result = instantiateSync(wasmBinaryFile, info);
return receiveInstance(result[0])
}
var tempDouble;
var tempI64;
var _emscripten_set_main_loop_timing = (mode, value) => {
Browser.mainLoop.timingMode = mode;
Browser.mainLoop.timingValue = value;
if (!Browser.mainLoop.func) {
return 1
}
if (!Browser.mainLoop.running) {
Browser.mainLoop.running = true
}
if (mode == 0) {
Browser.mainLoop.scheduler = function Browser_mainLoop_scheduler_setTimeout() {
var timeUntilNextTick = Math.max(0, Browser.mainLoop.tickStartTime + value - _emscripten_get_now()) | 0;
setTimeout(Browser.mainLoop.runner, timeUntilNextTick)
};
Browser.mainLoop.method = "timeout"
} else if (mode == 1) {
Browser.mainLoop.scheduler = function Browser_mainLoop_scheduler_rAF() {
Browser.requestAnimationFrame(Browser.mainLoop.runner)
};
Browser.mainLoop.method = "rAF"
} else if (mode == 2) {
if (typeof Browser.setImmediate == "undefined") {
if (typeof setImmediate == "undefined") {
var setImmediates = [];
var emscriptenMainLoopMessageId = "setimmediate";
var Browser_setImmediate_messageHandler = event => {
if (event.data === emscriptenMainLoopMessageId || event.data.target === emscriptenMainLoopMessageId) {
event.stopPropagation();
setImmediates.shift()()
}
};
addEventListener("message", Browser_setImmediate_messageHandler, true);
Browser.setImmediate = function Browser_emulated_setImmediate(func) {
setImmediates.push(func);
if (ENVIRONMENT_IS_WORKER) {
if (Module["setImmediates"] === undefined) Module["setImmediates"] = [];
Module["setImmediates"].push(func);
postMessage({
target: emscriptenMainLoopMessageId
})
} else postMessage(emscriptenMainLoopMessageId, "*")
}
} else {
Browser.setImmediate = setImmediate
}
}
Browser.mainLoop.scheduler = function Browser_mainLoop_scheduler_setImmediate() {
Browser.setImmediate(Browser.mainLoop.runner)
};
Browser.mainLoop.method = "immediate"
}
return 0
};
var _emscripten_get_now;
_emscripten_get_now = () => performance.now();
var setMainLoop = (browserIterationFunc, fps, simulateInfiniteLoop, arg, noSetTiming) => {
Browser.mainLoop.func = browserIterationFunc;
Browser.mainLoop.arg = arg;
var thisMainLoopId = Browser.mainLoop.currentlyRunningMainloop;
function checkIsRunning() {
if (thisMainLoopId < Browser.mainLoop.currentlyRunningMainloop) {
return false
}
return true
}
Browser.mainLoop.running = false;
Browser.mainLoop.runner = function Browser_mainLoop_runner() {
if (ABORT) return;
if (Browser.mainLoop.queue.length > 0) {
var start = Date.now();
var blocker = Browser.mainLoop.queue.shift();
blocker.func(blocker.arg);
if (Browser.mainLoop.remainingBlockers) {
var remaining = Browser.mainLoop.remainingBlockers;
var next = remaining % 1 == 0 ? remaining - 1 : Math.floor(remaining);
if (blocker.counted) {
Browser.mainLoop.remainingBlockers = next
} else {
next = next + .5;
Browser.mainLoop.remainingBlockers = (8 * remaining + next) / 9
}
}
Browser.mainLoop.updateStatus();
if (!checkIsRunning()) return;
setTimeout(Browser.mainLoop.runner, 0);
return
}
if (!checkIsRunning()) return;
Browser.mainLoop.currentFrameNumber = Browser.mainLoop.currentFrameNumber + 1 | 0;
if (Browser.mainLoop.timingMode == 1 && Browser.mainLoop.timingValue > 1 && Browser.mainLoop.currentFrameNumber % Browser.mainLoop.timingValue != 0) {
Browser.mainLoop.scheduler();
return
} else if (Browser.mainLoop.timingMode == 0) {
Browser.mainLoop.tickStartTime = _emscripten_get_now()
}
Browser.mainLoop.runIter(browserIterationFunc);
if (!checkIsRunning()) return;
if (typeof SDL == "object") SDL.audio?.queueNewAudioData?.();
Browser.mainLoop.scheduler()
};
if (!noSetTiming) {
if (fps && fps > 0) {
_emscripten_set_main_loop_timing(0, 1e3 / fps)
} else {
_emscripten_set_main_loop_timing(1, 1)
}
Browser.mainLoop.scheduler()
}
if (simulateInfiniteLoop) {
throw "unwind"
}
};
var handleException = e => {
if (e instanceof ExitStatus || e == "unwind") {
return EXITSTATUS
}
quit_(1, e)
};
function ExitStatus(status) {
this.name = "ExitStatus";
this.message = `Program terminated with exit(${status})`;
this.status = status
}
var runtimeKeepaliveCounter = 0;
var keepRuntimeAlive = () => noExitRuntime || runtimeKeepaliveCounter > 0;
var _proc_exit = code => {
EXITSTATUS = code;
if (!keepRuntimeAlive()) {
Module["onExit"]?.(code);
ABORT = true
}
quit_(code, new ExitStatus(code))
};
var exitJS = (status, implicit) => {
EXITSTATUS = status;
_proc_exit(status)
};
var _exit = exitJS;
var maybeExit = () => {
if (!keepRuntimeAlive()) {
try {
_exit(EXITSTATUS)
} catch (e) {
handleException(e)
}
}
};
var callUserCallback = func => {
if (ABORT) {
return
}
try {
func();
maybeExit()
} catch (e) {
handleException(e)
}
};
var safeSetTimeout = (func, timeout) => setTimeout(() => {
callUserCallback(func)
}, timeout);
var warnOnce = text => {
warnOnce.shown ||= {};
if (!warnOnce.shown[text]) {
warnOnce.shown[text] = 1;
if (ENVIRONMENT_IS_NODE) text = "warning: " + text;
err(text)
}
};
var preloadPlugins = Module["preloadPlugins"] || [];
var Browser = {
mainLoop: {
running: false,
scheduler: null,
method: "",
currentlyRunningMainloop: 0,
func: null,
arg: 0,
timingMode: 0,
timingValue: 0,
currentFrameNumber: 0,
queue: [],
pause() {
Browser.mainLoop.scheduler = null;
Browser.mainLoop.currentlyRunningMainloop++
},
resume() {
Browser.mainLoop.currentlyRunningMainloop++;
var timingMode = Browser.mainLoop.timingMode;
var timingValue = Browser.mainLoop.timingValue;
var func = Browser.mainLoop.func;
Browser.mainLoop.func = null;
setMainLoop(func, 0, false, Browser.mainLoop.arg, true);
_emscripten_set_main_loop_timing(timingMode, timingValue);
Browser.mainLoop.scheduler()
},
updateStatus() {
if (Module["setStatus"]) {
var message = Module["statusMessage"] || "Please wait...";
var remaining = Browser.mainLoop.remainingBlockers;
var expected = Browser.mainLoop.expectedBlockers;
if (remaining) {
if (remaining < expected) {
Module["setStatus"](`{message} ({expected - remaining}/{expected})`)
} else {
Module["setStatus"](message)
}
} else {
Module["setStatus"]("")
}
}
},
runIter(func) {
if (ABORT) return;
if (Module["preMainLoop"]) {
var preRet = Module["preMainLoop"]();
if (preRet === false) {
return
}
}
callUserCallback(func);
Module["postMainLoop"]?.()
}
},
isFullscreen: false,
pointerLock: false,
moduleContextCreatedCallbacks: [],
workers: [],
init() {
if (Browser.initted) return;
Browser.initted = true;
var imagePlugin = {};
imagePlugin["canHandle"] = function imagePlugin_canHandle(name) {
return !Module.noImageDecoding && /\.(jpg|jpeg|png|bmp)$/i.test(name)
};
imagePlugin["handle"] = function imagePlugin_handle(byteArray, name, onload, onerror) {
var b = new Blob([byteArray], {
type: Browser.getMimetype(name)
});
if (b.size !== byteArray.length) {
b = new Blob([new Uint8Array(byteArray).buffer], {
type: Browser.getMimetype(name)
})
}
var url = URL.createObjectURL(b);
var img = new Image;
img.onload = () => {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
preloadedImages[name] = canvas;
URL.revokeObjectURL(url);
onload?.(byteArray)
};
img.onerror = event => {
err(`Image ${url} could not be decoded`);
onerror?.()
};
img.src = url
};
preloadPlugins.push(imagePlugin);
var audioPlugin = {};
audioPlugin["canHandle"] = function audioPlugin_canHandle(name) {
return !Module.noAudioDecoding && name.substr(-4) in {
".ogg": 1,
".wav": 1,
".mp3": 1
}
};
audioPlugin["handle"] = function audioPlugin_handle(byteArray, name, onload, onerror) {
var done = false;
function finish(audio) {
if (done) return;
done = true;
preloadedAudios[name] = audio;
onload?.(byteArray)
}
var b = new Blob([byteArray], {
type: Browser.getMimetype(name)
});
var url = URL.createObjectURL(b);
var audio = new Audio;
audio.addEventListener("canplaythrough", () => finish(audio), false);
audio.onerror = function audio_onerror(event) {
if (done) return;
err(`warning: browser could not fully decode audio ${name}, trying slower base64 approach`);
function encode64(data) {
var BASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var PAD = "=";
var ret = "";
var leftchar = 0;
var leftbits = 0;
for (var i = 0; i < data.length; i++) {
leftchar = leftchar << 8 | data[i];
leftbits += 8;
while (leftbits >= 6) {
var curr = leftchar >> leftbits - 6 & 63;
leftbits -= 6;
ret += BASE[curr]
}
}
if (leftbits == 2) {
ret += BASE[(leftchar & 3) << 4];
ret += PAD + PAD
} else if (leftbits == 4) {
ret += BASE[(leftchar & 15) << 2];
ret += PAD
}
return ret
}
audio.src = "data:audio/x-" + name.substr(-3) + ";base64," + encode64(byteArray);
finish(audio)
};
audio.src = url;
safeSetTimeout(() => {
finish(audio)
}, 1e4)
};
preloadPlugins.push(audioPlugin);
function pointerLockChange() {
Browser.pointerLock = document["pointerLockElement"] === Module["canvas"] || document["mozPointerLockElement"] === Module["canvas"] || document["webkitPointerLockElement"] === Module["canvas"] || document["msPointerLockElement"] === Module["canvas"]
}
var canvas = Module["canvas"];
if (canvas) {
canvas.requestPointerLock = canvas["requestPointerLock"] || canvas["mozRequestPointerLock"] || canvas["webkitRequestPointerLock"] || canvas["msRequestPointerLock"] || (() => {});
canvas.exitPointerLock = document["exitPointerLock"] || document["mozExitPointerLock"] || document["webkitExitPointerLock"] || document["msExitPointerLock"] || (() => {});
canvas.exitPointerLock = canvas.exitPointerLock.bind(document);
document.addEventListener("pointerlockchange", pointerLockChange, false);
document.addEventListener("mozpointerlockchange", pointerLockChange, false);
document.addEventListener("webkitpointerlockchange", pointerLockChange, false);
document.addEventListener("mspointerlockchange", pointerLockChange, false);
if (Module["elementPointerLock"]) {
canvas.addEventListener("click", ev => {
if (!Browser.pointerLock && Module["canvas"].requestPointerLock) {
Module["canvas"].requestPointerLock();
ev.preventDefault()
}
}, false)
}
}
},
createContext(canvas, useWebGL, setInModule, webGLContextAttributes) {
if (useWebGL && Module.ctx && canvas == Module.canvas) return Module.ctx;
var ctx;
var contextHandle;
if (useWebGL) {
var contextAttributes = {
antialias: false,
alpha: false,
majorVersion: 1
};
if (webGLContextAttributes) {
for (var attribute in webGLContextAttributes) {
contextAttributes[attribute] = webGLContextAttributes[attribute]
}
}
if (typeof GL != "undefined") {
contextHandle = GL.createContext(canvas, contextAttributes);
if (contextHandle) {
ctx = GL.getContext(contextHandle).GLctx
}
}
} else {
ctx = canvas.getContext("2d")
}
if (!ctx) return null;
if (setInModule) {
Module.ctx = ctx;
if (useWebGL) GL.makeContextCurrent(contextHandle);
Module.useWebGL = useWebGL;
Browser.moduleContextCreatedCallbacks.forEach(callback => callback());
Browser.init()
}
return ctx
},
destroyContext(canvas, useWebGL, setInModule) {},
fullscreenHandlersInstalled: false,
lockPointer: undefined,
resizeCanvas: undefined,
requestFullscreen(lockPointer, resizeCanvas) {
Browser.lockPointer = lockPointer;
Browser.resizeCanvas = resizeCanvas;
if (typeof Browser.lockPointer == "undefined") Browser.lockPointer = true;
if (typeof Browser.resizeCanvas == "undefined") Browser.resizeCanvas = false;
var canvas = Module["canvas"];
function fullscreenChange() {
Browser.isFullscreen = false;
var canvasContainer = canvas.parentNode;
if ((document["fullscreenElement"] || document["mozFullScreenElement"] || document["msFullscreenElement"] || document["webkitFullscreenElement"] || document["webkitCurrentFullScreenElement"]) === canvasContainer) {
canvas.exitFullscreen = Browser.exitFullscreen;
if (Browser.lockPointer) canvas.requestPointerLock();
Browser.isFullscreen = true;
if (Browser.resizeCanvas) {
Browser.setFullscreenCanvasSize()
} else {
Browser.updateCanvasDimensions(canvas)
}
} else {
canvasContainer.parentNode.insertBefore(canvas, canvasContainer);
canvasContainer.parentNode.removeChild(canvasContainer);
if (Browser.resizeCanvas) {
Browser.setWindowedCanvasSize()
} else {
Browser.updateCanvasDimensions(canvas)
}
}
Module["onFullScreen"]?.(Browser.isFullscreen);
Module["onFullscreen"]?.(Browser.isFullscreen)
}
if (!Browser.fullscreenHandlersInstalled) {
Browser.fullscreenHandlersInstalled = true;
document.addEventListener("fullscreenchange", fullscreenChange, false);
document.addEventListener("mozfullscreenchange", fullscreenChange, false);
document.addEventListener("webkitfullscreenchange", fullscreenChange, false);
document.addEventListener("MSFullscreenChange", fullscreenChange, false)
}
var canvasContainer = document.createElement("div");
canvas.parentNode.insertBefore(canvasContainer, canvas);
canvasContainer.appendChild(canvas);
canvasContainer.requestFullscreen = canvasContainer["requestFullscreen"] || canvasContainer["mozRequestFullScreen"] || canvasContainer["msRequestFullscreen"] || (canvasContainer["webkitRequestFullscreen"] ? () => canvasContainer["webkitRequestFullscreen"](Element["ALLOW_KEYBOARD_INPUT"]) : null) || (canvasContainer["webkitRequestFullScreen"] ? () => canvasContainer["webkitRequestFullScreen"](Element["ALLOW_KEYBOARD_INPUT"]) : null);
canvasContainer.requestFullscreen()
},
exitFullscreen() {
if (!Browser.isFullscreen) {
return false
}
var CFS = document["exitFullscreen"] || document["cancelFullScreen"] || document["mozCancelFullScreen"] || document["msExitFullscreen"] || document["webkitCancelFullScreen"] || (() => {});
CFS.apply(document, []);
return true
},
nextRAF: 0,
fakeRequestAnimationFrame(func) {
var now = Date.now();
if (Browser.nextRAF === 0) {
Browser.nextRAF = now + 1e3 / 60
} else {
while (now + 2 >= Browser.nextRAF) {
Browser.nextRAF += 1e3 / 60
}
}
var delay = Math.max(Browser.nextRAF - now, 0);
setTimeout(func, delay)
},
requestAnimationFrame(func) {
if (typeof requestAnimationFrame == "function") {
requestAnimationFrame(func);
return
}
var RAF = Browser.fakeRequestAnimationFrame;
RAF(func)
},
safeSetTimeout(func, timeout) {
return safeSetTimeout(func, timeout)
},
safeRequestAnimationFrame(func) {
return Browser.requestAnimationFrame(() => {
callUserCallback(func)
})
},
getMimetype(name) {
return {
jpg: "image/jpeg",
jpeg: "image/jpeg",
png: "image/png",
bmp: "image/bmp",
ogg: "audio/ogg",
wav: "audio/wav",
mp3: "audio/mpeg"
} [name.substr(name.lastIndexOf(".") + 1)]
},
getUserMedia(func) {
window.getUserMedia ||= navigator["getUserMedia"] || navigator["mozGetUserMedia"];
window.getUserMedia(func)
},
getMovementX(event) {
return event["movementX"] || event["mozMovementX"] || event["webkitMovementX"] || 0
},
getMovementY(event) {
return event["movementY"] || event["mozMovementY"] || event["webkitMovementY"] || 0
},
getMouseWheelDelta(event) {
var delta = 0;
switch (event.type) {
case "DOMMouseScroll":
delta = event.detail / 3;
break;
case "mousewheel":
delta = event.wheelDelta / 120;
break;
case "wheel":
delta = event.deltaY;
switch (event.deltaMode) {
case 0:
delta /= 100;
break;
case 1:
delta /= 3;
break;
case 2:
delta *= 80;
break;
default:
throw "unrecognized mouse wheel delta mode: " + event.deltaMode
}
break;
default:
throw "unrecognized mouse wheel event: " + event.type
}
return delta
},
mouseX: 0,
mouseY: 0,
mouseMovementX: 0,
mouseMovementY: 0,
touches: {},
lastTouches: {},
calculateMouseCoords(pageX, pageY) {
var rect = Module["canvas"].getBoundingClientRect();
var cw = Module["canvas"].width;
var ch = Module["canvas"].height;
var scrollX = typeof window.scrollX != "undefined" ? window.scrollX : window.pageXOffset;
var scrollY = typeof window.scrollY != "undefined" ? window.scrollY : window.pageYOffset;
var adjustedX = pageX - (scrollX + rect.left);
var adjustedY = pageY - (scrollY + rect.top);
adjustedX = adjustedX * (cw / rect.width);
adjustedY = adjustedY * (ch / rect.height);
return {
x: adjustedX,
y: adjustedY
}
},
setMouseCoords(pageX, pageY) {
const {
x: x,
y: y
} = Browser.calculateMouseCoords(pageX, pageY);
Browser.mouseMovementX = x - Browser.mouseX;
Browser.mouseMovementY = y - Browser.mouseY;
Browser.mouseX = x;
Browser.mouseY = y
},
calculateMouseEvent(event) {
if (Browser.pointerLock) {
if (event.type != "mousemove" && "mozMovementX" in event) {
Browser.mouseMovementX = Browser.mouseMovementY = 0
} else {
Browser.mouseMovementX = Browser.getMovementX(event);
Browser.mouseMovementY = Browser.getMovementY(event)
}
Browser.mouseX += Browser.mouseMovementX;
Browser.mouseY += Browser.mouseMovementY
} else {
if (event.type === "touchstart" || event.type === "touchend" || event.type === "touchmove") {
var touch = event.touch;
if (touch === undefined) {
return
}
var coords = Browser.calculateMouseCoords(touch.pageX, touch.pageY);
if (event.type === "touchstart") {
Browser.lastTouches[touch.identifier] = coords;
Browser.touches[touch.identifier] = coords
} else if (event.type === "touchend" || event.type === "touchmove") {
var last = Browser.touches[touch.identifier];
last ||= coords;
Browser.lastTouches[touch.identifier] = last;
Browser.touches[touch.identifier] = coords
}
return
}
Browser.setMouseCoords(event.pageX, event.pageY)
}
},
resizeListeners: [],
updateResizeListeners() {
var canvas = Module["canvas"];
Browser.resizeListeners.forEach(listener => listener(canvas.width, canvas.height))
},
setCanvasSize(width, height, noUpdates) {
var canvas = Module["canvas"];
Browser.updateCanvasDimensions(canvas, width, height);
if (!noUpdates) Browser.updateResizeListeners()
},
windowedWidth: 0,
windowedHeight: 0,
setFullscreenCanvasSize() {
if (typeof SDL != "undefined") {
var flags = HEAPU32[SDL.screen >> 2];
flags = flags | 8388608;
HEAP32[SDL.screen >> 2] = flags
}
Browser.updateCanvasDimensions(Module["canvas"]);
Browser.updateResizeListeners()
},
setWindowedCanvasSize() {
if (typeof SDL != "undefined") {
var flags = HEAPU32[SDL.screen >> 2];
flags = flags & ~8388608;
HEAP32[SDL.screen >> 2] = flags
}
Browser.updateCanvasDimensions(Module["canvas"]);
Browser.updateResizeListeners()
},
updateCanvasDimensions(canvas, wNative, hNative) {
if (wNative && hNative) {
canvas.widthNative = wNative;
canvas.heightNative = hNative
} else {
wNative = canvas.widthNative;
hNative = canvas.heightNative
}
var w = wNative;
var h = hNative;
if (Module["forcedAspectRatio"] && Module["forcedAspectRatio"] > 0) {
if (w / h < Module["forcedAspectRatio"]) {
w = Math.round(h * Module["forcedAspectRatio"])
} else {
h = Math.round(w / Module["forcedAspectRatio"])
}
}
if ((document["fullscreenElement"] || document["mozFullScreenElement"] || document["msFullscreenElement"] || document["webkitFullscreenElement"] || document["webkitCurrentFullScreenElement"]) === canvas.parentNode && typeof screen != "undefined") {
var factor = Math.min(screen.width / w, screen.height / h);
w = Math.round(w * factor);
h = Math.round(h * factor)
}
if (Browser.resizeCanvas) {
if (canvas.width != w) canvas.width = w;
if (canvas.height != h) canvas.height = h;
if (typeof canvas.style != "undefined") {
canvas.style.removeProperty("width");
canvas.style.removeProperty("height")
}
} else {
if (canvas.width != wNative) canvas.width = wNative;
if (canvas.height != hNative) canvas.height = hNative;
if (typeof canvas.style != "undefined") {
if (w != wNative || h != hNative) {
canvas.style.setProperty("width", w + "px", "important");
canvas.style.setProperty("height", h + "px", "important")
} else {
canvas.style.removeProperty("width");
canvas.style.removeProperty("height")
}
}
}
}
};
var callRuntimeCallbacks = callbacks => {
while (callbacks.length > 0) {
callbacks.shift()(Module)
}
};
var stackSave = () => _emscripten_stack_get_current();
var stackRestore = val => __emscripten_stack_restore(val);
var withStackSave = f => {
var stack = stackSave();
var ret = f();
stackRestore(stack);
return ret
};
var lengthBytesUTF8 = str => {
var len = 0;
for (var i = 0; i < str.length; ++i) {
var c = str.charCodeAt(i);
if (c <= 127) {
len++
} else if (c <= 2047) {
len += 2
} else if (c >= 55296 && c <= 57343) {
len += 4;
++i
} else {
len += 3
}
}