Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
RishiRecon
GitHub Repository: RishiRecon/exploits
Path: blob/main/misc/emulator/n64/sm64/sm64.us.f3dex2e.js
28553 views
1
var moduleOverrides = {};
2
var key;
3
for (key in Module) {
4
if (Module.hasOwnProperty(key)) {
5
moduleOverrides[key] = Module[key];
6
}
7
}
8
9
var arguments_ = [];
10
var thisProgram = './this.program';
11
var quit_ = function(status, toThrow) {
12
throw toThrow;
13
};
14
15
var ENVIRONMENT_IS_WEB = false;
16
var ENVIRONMENT_IS_WORKER = false;
17
var ENVIRONMENT_IS_NODE = false;
18
var ENVIRONMENT_IS_SHELL = false;
19
ENVIRONMENT_IS_WEB = typeof window === 'object';
20
ENVIRONMENT_IS_WORKER = typeof importScripts === 'function';
21
22
ENVIRONMENT_IS_NODE = typeof process === 'object' && typeof process.versions === 'object' && typeof process.versions.node === 'string';
23
ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER;
24
25
if (Module['ENVIRONMENT']) {
26
throw new Error('Module.ENVIRONMENT has been deprecated. To force the environment, use the ENVIRONMENT compile-time option (for example, -s ENVIRONMENT=web or -s ENVIRONMENT=node)');
27
}
28
29
30
31
// `/` should be present at the end if `scriptDirectory` is not empty
32
var scriptDirectory = '';
33
function locateFile(path) {
34
if (Module['locateFile']) {
35
return Module['locateFile'](path, scriptDirectory);
36
}
37
return scriptDirectory + path;
38
}
39
40
// Hooks that are implemented differently in different runtime environments.
41
var read_,
42
readAsync,
43
readBinary,
44
setWindowTitle;
45
46
var nodeFS;
47
var nodePath;
48
49
if (ENVIRONMENT_IS_NODE) {
50
if (ENVIRONMENT_IS_WORKER) {
51
scriptDirectory = require('path').dirname(scriptDirectory) + '/';
52
} else {
53
scriptDirectory = __dirname + '/';
54
}
55
56
57
read_ = function shell_read(filename, binary) {
58
if (!nodeFS) nodeFS = require('fs');
59
if (!nodePath) nodePath = require('path');
60
filename = nodePath['normalize'](filename);
61
return nodeFS['readFileSync'](filename, binary ? null : 'utf8');
62
};
63
64
readBinary = function readBinary(filename) {
65
var ret = read_(filename, true);
66
if (!ret.buffer) {
67
ret = new Uint8Array(ret);
68
}
69
assert(ret.buffer);
70
return ret;
71
};
72
73
74
75
76
if (process['argv'].length > 1) {
77
thisProgram = process['argv'][1].replace(/\\/g, '/');
78
}
79
80
arguments_ = process['argv'].slice(2);
81
82
if (typeof module !== 'undefined') {
83
module['exports'] = Module;
84
}
85
86
process['on']('uncaughtException', function(ex) {
87
// suppress ExitStatus exceptions from showing an error
88
if (!(ex instanceof ExitStatus)) {
89
throw ex;
90
}
91
});
92
93
process['on']('unhandledRejection', abort);
94
95
quit_ = function(status) {
96
process['exit'](status);
97
};
98
99
Module['inspect'] = function () { return '[Emscripten Module object]'; };
100
101
102
103
} else
104
if (ENVIRONMENT_IS_SHELL) {
105
106
107
if (typeof read != 'undefined') {
108
read_ = function shell_read(f) {
109
return read(f);
110
};
111
}
112
113
readBinary = function readBinary(f) {
114
var data;
115
if (typeof readbuffer === 'function') {
116
return new Uint8Array(readbuffer(f));
117
}
118
data = read(f, 'binary');
119
assert(typeof data === 'object');
120
return data;
121
};
122
123
if (typeof scriptArgs != 'undefined') {
124
arguments_ = scriptArgs;
125
} else if (typeof arguments != 'undefined') {
126
arguments_ = arguments;
127
}
128
129
if (typeof quit === 'function') {
130
quit_ = function(status) {
131
quit(status);
132
};
133
}
134
135
if (typeof print !== 'undefined') {
136
// Prefer to use print/printErr where they exist, as they usually work better.
137
if (typeof console === 'undefined') console = /** @type{!Console} */({});
138
console.log = /** @type{!function(this:Console, ...*): undefined} */ (print);
139
console.warn = console.error = /** @type{!function(this:Console, ...*): undefined} */ (typeof printErr !== 'undefined' ? printErr : print);
140
}
141
142
143
} else
144
145
// Note that this includes Node.js workers when relevant (pthreads is enabled).
146
// Node.js workers are detected as a combination of ENVIRONMENT_IS_WORKER and
147
// ENVIRONMENT_IS_NODE.
148
if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) {
149
if (ENVIRONMENT_IS_WORKER) { // Check worker, not web, since window could be polyfilled
150
scriptDirectory = self.location.href;
151
} else if (document.currentScript) { // web
152
scriptDirectory = document.currentScript.src;
153
}
154
// blob urls look like blob:http://site.com/etc/etc and we cannot infer anything from them.
155
// otherwise, slice off the final part of the url to find the script directory.
156
// if scriptDirectory does not contain a slash, lastIndexOf will return -1,
157
// and scriptDirectory will correctly be replaced with an empty string.
158
if (scriptDirectory.indexOf('blob:') !== 0) {
159
scriptDirectory = scriptDirectory.substr(0, scriptDirectory.lastIndexOf('/')+1);
160
} else {
161
scriptDirectory = '';
162
}
163
164
165
// Differentiate the Web Worker from the Node Worker case, as reading must
166
// be done differently.
167
{
168
169
170
read_ = function shell_read(url) {
171
var xhr = new XMLHttpRequest();
172
xhr.open('GET', url, false);
173
xhr.send(null);
174
return xhr.responseText;
175
};
176
177
if (ENVIRONMENT_IS_WORKER) {
178
readBinary = function readBinary(url) {
179
var xhr = new XMLHttpRequest();
180
xhr.open('GET', url, false);
181
xhr.responseType = 'arraybuffer';
182
xhr.send(null);
183
return new Uint8Array(/** @type{!ArrayBuffer} */(xhr.response));
184
};
185
}
186
187
readAsync = function readAsync(url, onload, onerror) {
188
var xhr = new XMLHttpRequest();
189
xhr.open('GET', url, true);
190
xhr.responseType = 'arraybuffer';
191
xhr.onload = function xhr_onload() {
192
if (xhr.status == 200 || (xhr.status == 0 && xhr.response)) { // file URLs can return 0
193
onload(xhr.response);
194
return;
195
}
196
onerror();
197
};
198
xhr.onerror = onerror;
199
xhr.send(null);
200
};
201
202
203
204
205
}
206
207
setWindowTitle = function(title) { document.title = title };
208
} else
209
{
210
throw new Error('environment detection error');
211
}
212
213
214
// Set up the out() and err() hooks, which are how we can print to stdout or
215
// stderr, respectively.
216
var out = Module['print'] || console.log.bind(console);
217
var err = Module['printErr'] || console.warn.bind(console);
218
219
// Merge back in the overrides
220
for (key in moduleOverrides) {
221
if (moduleOverrides.hasOwnProperty(key)) {
222
Module[key] = moduleOverrides[key];
223
}
224
}
225
// Free the object hierarchy contained in the overrides, this lets the GC
226
// reclaim data used e.g. in memoryInitializerRequest, which is a large typed array.
227
moduleOverrides = null;
228
229
// Emit code to handle expected values on the Module object. This applies Module.x
230
// to the proper local x. This has two benefits: first, we only emit it if it is
231
// expected to arrive, and second, by using a local everywhere else that can be
232
// minified.
233
if (Module['arguments']) arguments_ = Module['arguments'];if (!Object.getOwnPropertyDescriptor(Module, 'arguments')) Object.defineProperty(Module, 'arguments', { configurable: true, get: function() { abort('Module.arguments has been replaced with plain arguments_') } });
234
if (Module['thisProgram']) thisProgram = Module['thisProgram'];if (!Object.getOwnPropertyDescriptor(Module, 'thisProgram')) Object.defineProperty(Module, 'thisProgram', { configurable: true, get: function() { abort('Module.thisProgram has been replaced with plain thisProgram') } });
235
if (Module['quit']) quit_ = Module['quit'];if (!Object.getOwnPropertyDescriptor(Module, 'quit')) Object.defineProperty(Module, 'quit', { configurable: true, get: function() { abort('Module.quit has been replaced with plain quit_') } });
236
237
// perform assertions in shell.js after we set up out() and err(), as otherwise if an assertion fails it cannot print the message
238
// Assertions on removed incoming Module JS APIs.
239
assert(typeof Module['memoryInitializerPrefixURL'] === 'undefined', 'Module.memoryInitializerPrefixURL option was removed, use Module.locateFile instead');
240
assert(typeof Module['pthreadMainPrefixURL'] === 'undefined', 'Module.pthreadMainPrefixURL option was removed, use Module.locateFile instead');
241
assert(typeof Module['cdInitializerPrefixURL'] === 'undefined', 'Module.cdInitializerPrefixURL option was removed, use Module.locateFile instead');
242
assert(typeof Module['filePackagePrefixURL'] === 'undefined', 'Module.filePackagePrefixURL option was removed, use Module.locateFile instead');
243
assert(typeof Module['read'] === 'undefined', 'Module.read option was removed (modify read_ in JS)');
244
assert(typeof Module['readAsync'] === 'undefined', 'Module.readAsync option was removed (modify readAsync in JS)');
245
assert(typeof Module['readBinary'] === 'undefined', 'Module.readBinary option was removed (modify readBinary in JS)');
246
assert(typeof Module['setWindowTitle'] === 'undefined', 'Module.setWindowTitle option was removed (modify setWindowTitle in JS)');
247
assert(typeof Module['TOTAL_MEMORY'] === 'undefined', 'Module.TOTAL_MEMORY has been renamed Module.INITIAL_MEMORY');
248
if (!Object.getOwnPropertyDescriptor(Module, 'read')) Object.defineProperty(Module, 'read', { configurable: true, get: function() { abort('Module.read has been replaced with plain read_') } });
249
if (!Object.getOwnPropertyDescriptor(Module, 'readAsync')) Object.defineProperty(Module, 'readAsync', { configurable: true, get: function() { abort('Module.readAsync has been replaced with plain readAsync') } });
250
if (!Object.getOwnPropertyDescriptor(Module, 'readBinary')) Object.defineProperty(Module, 'readBinary', { configurable: true, get: function() { abort('Module.readBinary has been replaced with plain readBinary') } });
251
// TODO: add when SDL2 is fixed if (!Object.getOwnPropertyDescriptor(Module, 'setWindowTitle')) Object.defineProperty(Module, 'setWindowTitle', { configurable: true, get: function() { abort('Module.setWindowTitle has been replaced with plain setWindowTitle') } });
252
var IDBFS = 'IDBFS is no longer included by default; build with -lidbfs.js';
253
var PROXYFS = 'PROXYFS is no longer included by default; build with -lproxyfs.js';
254
var WORKERFS = 'WORKERFS is no longer included by default; build with -lworkerfs.js';
255
var NODEFS = 'NODEFS is no longer included by default; build with -lnodefs.js';
256
257
258
// TODO remove when SDL2 is fixed (also see above)
259
260
261
262
// Copyright 2017 The Emscripten Authors. All rights reserved.
263
// Emscripten is available under two separate licenses, the MIT license and the
264
// University of Illinois/NCSA Open Source License. Both these licenses can be
265
// found in the LICENSE file.
266
267
// {{PREAMBLE_ADDITIONS}}
268
269
var STACK_ALIGN = 16;
270
271
// stack management, and other functionality that is provided by the compiled code,
272
// should not be used before it is ready
273
274
/** @suppress{duplicate} */
275
var stackSave;
276
/** @suppress{duplicate} */
277
var stackRestore;
278
/** @suppress{duplicate} */
279
var stackAlloc;
280
281
stackSave = stackRestore = stackAlloc = function() {
282
abort('cannot use the stack before compiled code is ready to run, and has provided stack access');
283
};
284
285
function staticAlloc(size) {
286
abort('staticAlloc is no longer available at runtime; instead, perform static allocations at compile time (using makeStaticAlloc)');
287
}
288
289
function dynamicAlloc(size) {
290
assert(DYNAMICTOP_PTR);
291
var ret = HEAP32[DYNAMICTOP_PTR>>2];
292
var end = (ret + size + 15) & -16;
293
assert(end <= HEAP8.length, 'failure to dynamicAlloc - memory growth etc. is not supported there, call malloc/sbrk directly');
294
HEAP32[DYNAMICTOP_PTR>>2] = end;
295
return ret;
296
}
297
298
function alignMemory(size, factor) {
299
if (!factor) factor = STACK_ALIGN; // stack alignment (16-byte) by default
300
return Math.ceil(size / factor) * factor;
301
}
302
303
function getNativeTypeSize(type) {
304
switch (type) {
305
case 'i1': case 'i8': return 1;
306
case 'i16': return 2;
307
case 'i32': return 4;
308
case 'i64': return 8;
309
case 'float': return 4;
310
case 'double': return 8;
311
default: {
312
if (type[type.length-1] === '*') {
313
return 4; // A pointer
314
} else if (type[0] === 'i') {
315
var bits = Number(type.substr(1));
316
assert(bits % 8 === 0, 'getNativeTypeSize invalid bits ' + bits + ', type ' + type);
317
return bits / 8;
318
} else {
319
return 0;
320
}
321
}
322
}
323
}
324
325
function warnOnce(text) {
326
if (!warnOnce.shown) warnOnce.shown = {};
327
if (!warnOnce.shown[text]) {
328
warnOnce.shown[text] = 1;
329
err(text);
330
}
331
}
332
333
334
335
336
337
338
// Wraps a JS function as a wasm function with a given signature.
339
function convertJsFunctionToWasm(func, sig) {
340
341
// If the type reflection proposal is available, use the new
342
// "WebAssembly.Function" constructor.
343
// Otherwise, construct a minimal wasm module importing the JS function and
344
// re-exporting it.
345
if (typeof WebAssembly.Function === "function") {
346
var typeNames = {
347
'i': 'i32',
348
'j': 'i64',
349
'f': 'f32',
350
'd': 'f64'
351
};
352
var type = {
353
parameters: [],
354
results: sig[0] == 'v' ? [] : [typeNames[sig[0]]]
355
};
356
for (var i = 1; i < sig.length; ++i) {
357
type.parameters.push(typeNames[sig[i]]);
358
}
359
return new WebAssembly.Function(type, func);
360
}
361
362
// The module is static, with the exception of the type section, which is
363
// generated based on the signature passed in.
364
var typeSection = [
365
0x01, // id: section,
366
0x00, // length: 0 (placeholder)
367
0x01, // count: 1
368
0x60, // form: func
369
];
370
var sigRet = sig.slice(0, 1);
371
var sigParam = sig.slice(1);
372
var typeCodes = {
373
'i': 0x7f, // i32
374
'j': 0x7e, // i64
375
'f': 0x7d, // f32
376
'd': 0x7c, // f64
377
};
378
379
// Parameters, length + signatures
380
typeSection.push(sigParam.length);
381
for (var i = 0; i < sigParam.length; ++i) {
382
typeSection.push(typeCodes[sigParam[i]]);
383
}
384
385
// Return values, length + signatures
386
// With no multi-return in MVP, either 0 (void) or 1 (anything else)
387
if (sigRet == 'v') {
388
typeSection.push(0x00);
389
} else {
390
typeSection = typeSection.concat([0x01, typeCodes[sigRet]]);
391
}
392
393
// Write the overall length of the type section back into the section header
394
// (excepting the 2 bytes for the section id and length)
395
typeSection[1] = typeSection.length - 2;
396
397
// Rest of the module is static
398
var bytes = new Uint8Array([
399
0x00, 0x61, 0x73, 0x6d, // magic ("\0asm")
400
0x01, 0x00, 0x00, 0x00, // version: 1
401
].concat(typeSection, [
402
0x02, 0x07, // import section
403
// (import "e" "f" (func 0 (type 0)))
404
0x01, 0x01, 0x65, 0x01, 0x66, 0x00, 0x00,
405
0x07, 0x05, // export section
406
// (export "f" (func 0 (type 0)))
407
0x01, 0x01, 0x66, 0x00, 0x00,
408
]));
409
410
// We can compile this wasm module synchronously because it is very small.
411
// This accepts an import (at "e.f"), that it reroutes to an export (at "f")
412
var module = new WebAssembly.Module(bytes);
413
var instance = new WebAssembly.Instance(module, {
414
'e': {
415
'f': func
416
}
417
});
418
var wrappedFunc = instance.exports['f'];
419
return wrappedFunc;
420
}
421
422
var freeTableIndexes = [];
423
424
// Add a wasm function to the table.
425
function addFunctionWasm(func, sig) {
426
var table = wasmTable;
427
var ret;
428
// Reuse a free index if there is one, otherwise grow.
429
if (freeTableIndexes.length) {
430
ret = freeTableIndexes.pop();
431
} else {
432
ret = table.length;
433
// Grow the table
434
try {
435
table.grow(1);
436
} catch (err) {
437
if (!(err instanceof RangeError)) {
438
throw err;
439
}
440
throw 'Unable to grow wasm table. Set ALLOW_TABLE_GROWTH.';
441
}
442
}
443
444
// Set the new value.
445
try {
446
// Attempting to call this with JS function will cause of table.set() to fail
447
table.set(ret, func);
448
} catch (err) {
449
if (!(err instanceof TypeError)) {
450
throw err;
451
}
452
assert(typeof sig !== 'undefined', 'Missing signature argument to addFunction');
453
var wrapped = convertJsFunctionToWasm(func, sig);
454
table.set(ret, wrapped);
455
}
456
457
return ret;
458
}
459
460
function removeFunctionWasm(index) {
461
freeTableIndexes.push(index);
462
}
463
464
// 'sig' parameter is required for the llvm backend but only when func is not
465
// already a WebAssembly function.
466
function addFunction(func, sig) {
467
assert(typeof func !== 'undefined');
468
469
return addFunctionWasm(func, sig);
470
}
471
472
function removeFunction(index) {
473
removeFunctionWasm(index);
474
}
475
476
477
478
var funcWrappers = {};
479
480
function getFuncWrapper(func, sig) {
481
if (!func) return; // on null pointer, return undefined
482
assert(sig);
483
if (!funcWrappers[sig]) {
484
funcWrappers[sig] = {};
485
}
486
var sigCache = funcWrappers[sig];
487
if (!sigCache[func]) {
488
// optimize away arguments usage in common cases
489
if (sig.length === 1) {
490
sigCache[func] = function dynCall_wrapper() {
491
return dynCall(sig, func);
492
};
493
} else if (sig.length === 2) {
494
sigCache[func] = function dynCall_wrapper(arg) {
495
return dynCall(sig, func, [arg]);
496
};
497
} else {
498
// general case
499
sigCache[func] = function dynCall_wrapper() {
500
return dynCall(sig, func, Array.prototype.slice.call(arguments));
501
};
502
}
503
}
504
return sigCache[func];
505
}
506
507
508
509
510
511
function makeBigInt(low, high, unsigned) {
512
return unsigned ? ((+((low>>>0)))+((+((high>>>0)))*4294967296.0)) : ((+((low>>>0)))+((+((high|0)))*4294967296.0));
513
}
514
515
/** @param {Array=} args */
516
function dynCall(sig, ptr, args) {
517
if (args && args.length) {
518
// j (64-bit integer) must be passed in as two numbers [low 32, high 32].
519
assert(args.length === sig.substring(1).replace(/j/g, '--').length);
520
assert(('dynCall_' + sig) in Module, 'bad function pointer type - no table for sig \'' + sig + '\'');
521
return Module['dynCall_' + sig].apply(null, [ptr].concat(args));
522
} else {
523
assert(sig.length == 1);
524
assert(('dynCall_' + sig) in Module, 'bad function pointer type - no table for sig \'' + sig + '\'');
525
return Module['dynCall_' + sig].call(null, ptr);
526
}
527
}
528
529
var tempRet0 = 0;
530
531
var setTempRet0 = function(value) {
532
tempRet0 = value;
533
};
534
535
var getTempRet0 = function() {
536
return tempRet0;
537
};
538
539
function getCompilerSetting(name) {
540
throw 'You must build with -s RETAIN_COMPILER_SETTINGS=1 for getCompilerSetting or emscripten_get_compiler_setting to work';
541
}
542
543
var Runtime = {
544
// helpful errors
545
getTempRet0: function() { abort('getTempRet0() is now a top-level function, after removing the Runtime object. Remove "Runtime."') },
546
staticAlloc: function() { abort('staticAlloc() is now a top-level function, after removing the Runtime object. Remove "Runtime."') },
547
stackAlloc: function() { abort('stackAlloc() is now a top-level function, after removing the Runtime object. Remove "Runtime."') },
548
};
549
550
// The address globals begin at. Very low in memory, for code size and optimization opportunities.
551
// Above 0 is static memory, starting with globals.
552
// Then the stack.
553
// Then 'dynamic' memory for sbrk.
554
var GLOBAL_BASE = 1024;
555
556
557
558
559
// === Preamble library stuff ===
560
561
// Documentation for the public APIs defined in this file must be updated in:
562
// site/source/docs/api_reference/preamble.js.rst
563
// A prebuilt local version of the documentation is available at:
564
// site/build/text/docs/api_reference/preamble.js.txt
565
// You can also build docs locally as HTML or other formats in site/
566
// An online HTML version (which may be of a different version of Emscripten)
567
// is up at http://kripken.github.io/emscripten-site/docs/api_reference/preamble.js.html
568
569
570
var wasmBinary;if (Module['wasmBinary']) wasmBinary = Module['wasmBinary'];if (!Object.getOwnPropertyDescriptor(Module, 'wasmBinary')) Object.defineProperty(Module, 'wasmBinary', { configurable: true, get: function() { abort('Module.wasmBinary has been replaced with plain wasmBinary') } });
571
var noExitRuntime;if (Module['noExitRuntime']) noExitRuntime = Module['noExitRuntime'];if (!Object.getOwnPropertyDescriptor(Module, 'noExitRuntime')) Object.defineProperty(Module, 'noExitRuntime', { configurable: true, get: function() { abort('Module.noExitRuntime has been replaced with plain noExitRuntime') } });
572
573
574
if (typeof WebAssembly !== 'object') {
575
abort('No WebAssembly support found. Build with -s WASM=0 to target JavaScript instead.');
576
}
577
578
579
// In MINIMAL_RUNTIME, setValue() and getValue() are only available when building with safe heap enabled, for heap safety checking.
580
// In traditional runtime, setValue() and getValue() are always available (although their use is highly discouraged due to perf penalties)
581
582
/** @param {number} ptr
583
@param {number} value
584
@param {string} type
585
@param {number|boolean=} noSafe */
586
function setValue(ptr, value, type, noSafe) {
587
type = type || 'i8';
588
if (type.charAt(type.length-1) === '*') type = 'i32'; // pointers are 32-bit
589
switch(type) {
590
case 'i1': HEAP8[((ptr)>>0)]=value; break;
591
case 'i8': HEAP8[((ptr)>>0)]=value; break;
592
case 'i16': HEAP16[((ptr)>>1)]=value; break;
593
case 'i32': HEAP32[((ptr)>>2)]=value; break;
594
case 'i64': (tempI64 = [value>>>0,(tempDouble=value,(+(Math_abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? ((Math_min((+(Math_floor((tempDouble)/4294967296.0))), 4294967295.0))|0)>>>0 : (~~((+(Math_ceil((tempDouble - +(((~~(tempDouble)))>>>0))/4294967296.0)))))>>>0) : 0)],HEAP32[((ptr)>>2)]=tempI64[0],HEAP32[(((ptr)+(4))>>2)]=tempI64[1]); break;
595
case 'float': HEAPF32[((ptr)>>2)]=value; break;
596
case 'double': HEAPF64[((ptr)>>3)]=value; break;
597
default: abort('invalid type for setValue: ' + type);
598
}
599
}
600
601
/** @param {number} ptr
602
@param {string} type
603
@param {number|boolean=} noSafe */
604
function getValue(ptr, type, noSafe) {
605
type = type || 'i8';
606
if (type.charAt(type.length-1) === '*') type = 'i32'; // pointers are 32-bit
607
switch(type) {
608
case 'i1': return HEAP8[((ptr)>>0)];
609
case 'i8': return HEAP8[((ptr)>>0)];
610
case 'i16': return HEAP16[((ptr)>>1)];
611
case 'i32': return HEAP32[((ptr)>>2)];
612
case 'i64': return HEAP32[((ptr)>>2)];
613
case 'float': return HEAPF32[((ptr)>>2)];
614
case 'double': return HEAPF64[((ptr)>>3)];
615
default: abort('invalid type for getValue: ' + type);
616
}
617
return null;
618
}
619
620
621
622
623
624
// Wasm globals
625
626
var wasmMemory;
627
628
// In fastcomp asm.js, we don't need a wasm Table at all.
629
// In the wasm backend, we polyfill the WebAssembly object,
630
// so this creates a (non-native-wasm) table for us.
631
var wasmTable = new WebAssembly.Table({
632
'initial': 1821,
633
'maximum': 1821 + 0,
634
'element': 'anyfunc'
635
});
636
637
638
//========================================
639
// Runtime essentials
640
//========================================
641
642
// whether we are quitting the application. no code should run after this.
643
// set in exit() and abort()
644
var ABORT = false;
645
646
// set by exit() and abort(). Passed to 'onExit' handler.
647
// NOTE: This is also used as the process return code code in shell environments
648
// but only when noExitRuntime is false.
649
var EXITSTATUS = 0;
650
651
/** @type {function(*, string=)} */
652
function assert(condition, text) {
653
if (!condition) {
654
abort('Assertion failed: ' + text);
655
}
656
}
657
658
// Returns the C function with a specified identifier (for C++, you need to do manual name mangling)
659
function getCFunc(ident) {
660
var func = Module['_' + ident]; // closure exported function
661
assert(func, 'Cannot call unknown function ' + ident + ', make sure it is exported');
662
return func;
663
}
664
665
// C calling interface.
666
/** @param {Array=} argTypes
667
@param {Arguments|Array=} args
668
@param {Object=} opts */
669
function ccall(ident, returnType, argTypes, args, opts) {
670
// For fast lookup of conversion functions
671
var toC = {
672
'string': function(str) {
673
var ret = 0;
674
if (str !== null && str !== undefined && str !== 0) { // null string
675
// at most 4 bytes per UTF-8 code point, +1 for the trailing '\0'
676
var len = (str.length << 2) + 1;
677
ret = stackAlloc(len);
678
stringToUTF8(str, ret, len);
679
}
680
return ret;
681
},
682
'array': function(arr) {
683
var ret = stackAlloc(arr.length);
684
writeArrayToMemory(arr, ret);
685
return ret;
686
}
687
};
688
689
function convertReturnValue(ret) {
690
if (returnType === 'string') return UTF8ToString(ret);
691
if (returnType === 'boolean') return Boolean(ret);
692
return ret;
693
}
694
695
var func = getCFunc(ident);
696
var cArgs = [];
697
var stack = 0;
698
assert(returnType !== 'array', 'Return type should not be "array".');
699
if (args) {
700
for (var i = 0; i < args.length; i++) {
701
var converter = toC[argTypes[i]];
702
if (converter) {
703
if (stack === 0) stack = stackSave();
704
cArgs[i] = converter(args[i]);
705
} else {
706
cArgs[i] = args[i];
707
}
708
}
709
}
710
var ret = func.apply(null, cArgs);
711
712
ret = convertReturnValue(ret);
713
if (stack !== 0) stackRestore(stack);
714
return ret;
715
}
716
717
/** @param {Array=} argTypes
718
@param {Object=} opts */
719
function cwrap(ident, returnType, argTypes, opts) {
720
return function() {
721
return ccall(ident, returnType, argTypes, arguments, opts);
722
}
723
}
724
725
var ALLOC_NORMAL = 0; // Tries to use _malloc()
726
var ALLOC_STACK = 1; // Lives for the duration of the current function call
727
var ALLOC_DYNAMIC = 2; // Cannot be freed except through sbrk
728
var ALLOC_NONE = 3; // Do not allocate
729
730
// allocate(): This is for internal use. You can use it yourself as well, but the interface
731
// is a little tricky (see docs right below). The reason is that it is optimized
732
// for multiple syntaxes to save space in generated code. So you should
733
// normally not use allocate(), and instead allocate memory using _malloc(),
734
// initialize it with setValue(), and so forth.
735
// @slab: An array of data, or a number. If a number, then the size of the block to allocate,
736
// in *bytes* (note that this is sometimes confusing: the next parameter does not
737
// affect this!)
738
// @types: Either an array of types, one for each byte (or 0 if no type at that position),
739
// or a single type which is used for the entire block. This only matters if there
740
// is initial data - if @slab is a number, then this does not matter at all and is
741
// ignored.
742
// @allocator: How to allocate memory, see ALLOC_*
743
/** @type {function((TypedArray|Array<number>|number), string, number, number=)} */
744
function allocate(slab, types, allocator, ptr) {
745
var zeroinit, size;
746
if (typeof slab === 'number') {
747
zeroinit = true;
748
size = slab;
749
} else {
750
zeroinit = false;
751
size = slab.length;
752
}
753
754
var singleType = typeof types === 'string' ? types : null;
755
756
var ret;
757
if (allocator == ALLOC_NONE) {
758
ret = ptr;
759
} else {
760
ret = [_malloc,
761
stackAlloc,
762
dynamicAlloc][allocator](Math.max(size, singleType ? 1 : types.length));
763
}
764
765
if (zeroinit) {
766
var stop;
767
ptr = ret;
768
assert((ret & 3) == 0);
769
stop = ret + (size & ~3);
770
for (; ptr < stop; ptr += 4) {
771
HEAP32[((ptr)>>2)]=0;
772
}
773
stop = ret + size;
774
while (ptr < stop) {
775
HEAP8[((ptr++)>>0)]=0;
776
}
777
return ret;
778
}
779
780
if (singleType === 'i8') {
781
if (slab.subarray || slab.slice) {
782
HEAPU8.set(/** @type {!Uint8Array} */ (slab), ret);
783
} else {
784
HEAPU8.set(new Uint8Array(slab), ret);
785
}
786
return ret;
787
}
788
789
var i = 0, type, typeSize, previousType;
790
while (i < size) {
791
var curr = slab[i];
792
793
type = singleType || types[i];
794
if (type === 0) {
795
i++;
796
continue;
797
}
798
assert(type, 'Must know what type to store in allocate!');
799
800
if (type == 'i64') type = 'i32'; // special case: we have one i32 here, and one i32 later
801
802
setValue(ret+i, curr, type);
803
804
// no need to look up size unless type changes, so cache it
805
if (previousType !== type) {
806
typeSize = getNativeTypeSize(type);
807
previousType = type;
808
}
809
i += typeSize;
810
}
811
812
return ret;
813
}
814
815
// Allocate memory during any stage of startup - static memory early on, dynamic memory later, malloc when ready
816
function getMemory(size) {
817
if (!runtimeInitialized) return dynamicAlloc(size);
818
return _malloc(size);
819
}
820
821
822
// runtime_strings.js: Strings related runtime functions that are part of both MINIMAL_RUNTIME and regular runtime.
823
824
// Given a pointer 'ptr' to a null-terminated UTF8-encoded string in the given array that contains uint8 values, returns
825
// a copy of that string as a Javascript String object.
826
827
var UTF8Decoder = typeof TextDecoder !== 'undefined' ? new TextDecoder('utf8') : undefined;
828
829
/**
830
* @param {number} idx
831
* @param {number=} maxBytesToRead
832
* @return {string}
833
*/
834
function UTF8ArrayToString(u8Array, idx, maxBytesToRead) {
835
var endIdx = idx + maxBytesToRead;
836
var endPtr = idx;
837
// TextDecoder needs to know the byte length in advance, it doesn't stop on null terminator by itself.
838
// Also, use the length info to avoid running tiny strings through TextDecoder, since .subarray() allocates garbage.
839
// (As a tiny code save trick, compare endPtr against endIdx using a negation, so that undefined means Infinity)
840
while (u8Array[endPtr] && !(endPtr >= endIdx)) ++endPtr;
841
842
if (endPtr - idx > 16 && u8Array.subarray && UTF8Decoder) {
843
return UTF8Decoder.decode(u8Array.subarray(idx, endPtr));
844
} else {
845
var str = '';
846
// If building with TextDecoder, we have already computed the string length above, so test loop end condition against that
847
while (idx < endPtr) {
848
// For UTF8 byte structure, see:
849
// http://en.wikipedia.org/wiki/UTF-8#Description
850
// https://www.ietf.org/rfc/rfc2279.txt
851
// https://tools.ietf.org/html/rfc3629
852
var u0 = u8Array[idx++];
853
if (!(u0 & 0x80)) { str += String.fromCharCode(u0); continue; }
854
var u1 = u8Array[idx++] & 63;
855
if ((u0 & 0xE0) == 0xC0) { str += String.fromCharCode(((u0 & 31) << 6) | u1); continue; }
856
var u2 = u8Array[idx++] & 63;
857
if ((u0 & 0xF0) == 0xE0) {
858
u0 = ((u0 & 15) << 12) | (u1 << 6) | u2;
859
} else {
860
if ((u0 & 0xF8) != 0xF0) warnOnce('Invalid UTF-8 leading byte 0x' + u0.toString(16) + ' encountered when deserializing a UTF-8 string on the asm.js/wasm heap to a JS string!');
861
u0 = ((u0 & 7) << 18) | (u1 << 12) | (u2 << 6) | (u8Array[idx++] & 63);
862
}
863
864
if (u0 < 0x10000) {
865
str += String.fromCharCode(u0);
866
} else {
867
var ch = u0 - 0x10000;
868
str += String.fromCharCode(0xD800 | (ch >> 10), 0xDC00 | (ch & 0x3FF));
869
}
870
}
871
}
872
return str;
873
}
874
875
// Given a pointer 'ptr' to a null-terminated UTF8-encoded string in the emscripten HEAP, returns a
876
// copy of that string as a Javascript String object.
877
// maxBytesToRead: an optional length that specifies the maximum number of bytes to read. You can omit
878
// this parameter to scan the string until the first \0 byte. If maxBytesToRead is
879
// passed, and the string at [ptr, ptr+maxBytesToReadr[ contains a null byte in the
880
// middle, then the string will cut short at that byte index (i.e. maxBytesToRead will
881
// not produce a string of exact length [ptr, ptr+maxBytesToRead[)
882
// N.B. mixing frequent uses of UTF8ToString() with and without maxBytesToRead may
883
// throw JS JIT optimizations off, so it is worth to consider consistently using one
884
// style or the other.
885
/**
886
* @param {number} ptr
887
* @param {number=} maxBytesToRead
888
* @return {string}
889
*/
890
function UTF8ToString(ptr, maxBytesToRead) {
891
return ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead) : '';
892
}
893
894
// Copies the given Javascript String object 'str' to the given byte array at address 'outIdx',
895
// encoded in UTF8 form and null-terminated. The copy will require at most str.length*4+1 bytes of space in the HEAP.
896
// Use the function lengthBytesUTF8 to compute the exact number of bytes (excluding null terminator) that this function will write.
897
// Parameters:
898
// str: the Javascript string to copy.
899
// outU8Array: the array to copy to. Each index in this array is assumed to be one 8-byte element.
900
// outIdx: The starting offset in the array to begin the copying.
901
// maxBytesToWrite: The maximum number of bytes this function can write to the array.
902
// This count should include the null terminator,
903
// i.e. if maxBytesToWrite=1, only the null terminator will be written and nothing else.
904
// maxBytesToWrite=0 does not write any bytes to the output, not even the null terminator.
905
// Returns the number of bytes written, EXCLUDING the null terminator.
906
907
function stringToUTF8Array(str, outU8Array, outIdx, maxBytesToWrite) {
908
if (!(maxBytesToWrite > 0)) // Parameter maxBytesToWrite is not optional. Negative values, 0, null, undefined and false each don't write out any bytes.
909
return 0;
910
911
var startIdx = outIdx;
912
var endIdx = outIdx + maxBytesToWrite - 1; // -1 for string null terminator.
913
for (var i = 0; i < str.length; ++i) {
914
// Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code unit, not a Unicode code point of the character! So decode UTF16->UTF32->UTF8.
915
// See http://unicode.org/faq/utf_bom.html#utf16-3
916
// For UTF8 byte structure, see http://en.wikipedia.org/wiki/UTF-8#Description and https://www.ietf.org/rfc/rfc2279.txt and https://tools.ietf.org/html/rfc3629
917
var u = str.charCodeAt(i); // possibly a lead surrogate
918
if (u >= 0xD800 && u <= 0xDFFF) {
919
var u1 = str.charCodeAt(++i);
920
u = 0x10000 + ((u & 0x3FF) << 10) | (u1 & 0x3FF);
921
}
922
if (u <= 0x7F) {
923
if (outIdx >= endIdx) break;
924
outU8Array[outIdx++] = u;
925
} else if (u <= 0x7FF) {
926
if (outIdx + 1 >= endIdx) break;
927
outU8Array[outIdx++] = 0xC0 | (u >> 6);
928
outU8Array[outIdx++] = 0x80 | (u & 63);
929
} else if (u <= 0xFFFF) {
930
if (outIdx + 2 >= endIdx) break;
931
outU8Array[outIdx++] = 0xE0 | (u >> 12);
932
outU8Array[outIdx++] = 0x80 | ((u >> 6) & 63);
933
outU8Array[outIdx++] = 0x80 | (u & 63);
934
} else {
935
if (outIdx + 3 >= endIdx) break;
936
if (u >= 0x200000) warnOnce('Invalid Unicode code point 0x' + u.toString(16) + ' encountered when serializing a JS string to an UTF-8 string on the asm.js/wasm heap! (Valid unicode code points should be in range 0-0x1FFFFF).');
937
outU8Array[outIdx++] = 0xF0 | (u >> 18);
938
outU8Array[outIdx++] = 0x80 | ((u >> 12) & 63);
939
outU8Array[outIdx++] = 0x80 | ((u >> 6) & 63);
940
outU8Array[outIdx++] = 0x80 | (u & 63);
941
}
942
}
943
// Null-terminate the pointer to the buffer.
944
outU8Array[outIdx] = 0;
945
return outIdx - startIdx;
946
}
947
948
// Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr',
949
// null-terminated and encoded in UTF8 form. The copy will require at most str.length*4+1 bytes of space in the HEAP.
950
// Use the function lengthBytesUTF8 to compute the exact number of bytes (excluding null terminator) that this function will write.
951
// Returns the number of bytes written, EXCLUDING the null terminator.
952
953
function stringToUTF8(str, outPtr, maxBytesToWrite) {
954
assert(typeof maxBytesToWrite == 'number', 'stringToUTF8(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!');
955
return stringToUTF8Array(str, HEAPU8,outPtr, maxBytesToWrite);
956
}
957
958
// Returns the number of bytes the given Javascript string takes if encoded as a UTF8 byte array, EXCLUDING the null terminator byte.
959
function lengthBytesUTF8(str) {
960
var len = 0;
961
for (var i = 0; i < str.length; ++i) {
962
// Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code unit, not a Unicode code point of the character! So decode UTF16->UTF32->UTF8.
963
// See http://unicode.org/faq/utf_bom.html#utf16-3
964
var u = str.charCodeAt(i); // possibly a lead surrogate
965
if (u >= 0xD800 && u <= 0xDFFF) u = 0x10000 + ((u & 0x3FF) << 10) | (str.charCodeAt(++i) & 0x3FF);
966
if (u <= 0x7F) ++len;
967
else if (u <= 0x7FF) len += 2;
968
else if (u <= 0xFFFF) len += 3;
969
else len += 4;
970
}
971
return len;
972
}
973
974
975
976
// runtime_strings_extra.js: Strings related runtime functions that are available only in regular runtime.
977
978
// Given a pointer 'ptr' to a null-terminated ASCII-encoded string in the emscripten HEAP, returns
979
// a copy of that string as a Javascript String object.
980
981
function AsciiToString(ptr) {
982
var str = '';
983
while (1) {
984
var ch = HEAPU8[((ptr++)>>0)];
985
if (!ch) return str;
986
str += String.fromCharCode(ch);
987
}
988
}
989
990
// Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr',
991
// null-terminated and encoded in ASCII form. The copy will require at most str.length+1 bytes of space in the HEAP.
992
993
function stringToAscii(str, outPtr) {
994
return writeAsciiToMemory(str, outPtr, false);
995
}
996
997
// Given a pointer 'ptr' to a null-terminated UTF16LE-encoded string in the emscripten HEAP, returns
998
// a copy of that string as a Javascript String object.
999
1000
var UTF16Decoder = typeof TextDecoder !== 'undefined' ? new TextDecoder('utf-16le') : undefined;
1001
1002
function UTF16ToString(ptr) {
1003
assert(ptr % 2 == 0, 'Pointer passed to UTF16ToString must be aligned to two bytes!');
1004
var endPtr = ptr;
1005
// TextDecoder needs to know the byte length in advance, it doesn't stop on null terminator by itself.
1006
// Also, use the length info to avoid running tiny strings through TextDecoder, since .subarray() allocates garbage.
1007
var idx = endPtr >> 1;
1008
while (HEAP16[idx]) ++idx;
1009
endPtr = idx << 1;
1010
1011
if (endPtr - ptr > 32 && UTF16Decoder) {
1012
return UTF16Decoder.decode(HEAPU8.subarray(ptr, endPtr));
1013
} else {
1014
var i = 0;
1015
1016
var str = '';
1017
while (1) {
1018
var codeUnit = HEAP16[(((ptr)+(i*2))>>1)];
1019
if (codeUnit == 0) return str;
1020
++i;
1021
// fromCharCode constructs a character from a UTF-16 code unit, so we can pass the UTF16 string right through.
1022
str += String.fromCharCode(codeUnit);
1023
}
1024
}
1025
}
1026
1027
// Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr',
1028
// null-terminated and encoded in UTF16 form. The copy will require at most str.length*4+2 bytes of space in the HEAP.
1029
// Use the function lengthBytesUTF16() to compute the exact number of bytes (excluding null terminator) that this function will write.
1030
// Parameters:
1031
// str: the Javascript string to copy.
1032
// outPtr: Byte address in Emscripten HEAP where to write the string to.
1033
// maxBytesToWrite: The maximum number of bytes this function can write to the array. This count should include the null
1034
// terminator, i.e. if maxBytesToWrite=2, only the null terminator will be written and nothing else.
1035
// maxBytesToWrite<2 does not write any bytes to the output, not even the null terminator.
1036
// Returns the number of bytes written, EXCLUDING the null terminator.
1037
1038
function stringToUTF16(str, outPtr, maxBytesToWrite) {
1039
assert(outPtr % 2 == 0, 'Pointer passed to stringToUTF16 must be aligned to two bytes!');
1040
assert(typeof maxBytesToWrite == 'number', 'stringToUTF16(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!');
1041
// Backwards compatibility: if max bytes is not specified, assume unsafe unbounded write is allowed.
1042
if (maxBytesToWrite === undefined) {
1043
maxBytesToWrite = 0x7FFFFFFF;
1044
}
1045
if (maxBytesToWrite < 2) return 0;
1046
maxBytesToWrite -= 2; // Null terminator.
1047
var startPtr = outPtr;
1048
var numCharsToWrite = (maxBytesToWrite < str.length*2) ? (maxBytesToWrite / 2) : str.length;
1049
for (var i = 0; i < numCharsToWrite; ++i) {
1050
// charCodeAt returns a UTF-16 encoded code unit, so it can be directly written to the HEAP.
1051
var codeUnit = str.charCodeAt(i); // possibly a lead surrogate
1052
HEAP16[((outPtr)>>1)]=codeUnit;
1053
outPtr += 2;
1054
}
1055
// Null-terminate the pointer to the HEAP.
1056
HEAP16[((outPtr)>>1)]=0;
1057
return outPtr - startPtr;
1058
}
1059
1060
// Returns the number of bytes the given Javascript string takes if encoded as a UTF16 byte array, EXCLUDING the null terminator byte.
1061
1062
function lengthBytesUTF16(str) {
1063
return str.length*2;
1064
}
1065
1066
function UTF32ToString(ptr) {
1067
assert(ptr % 4 == 0, 'Pointer passed to UTF32ToString must be aligned to four bytes!');
1068
var i = 0;
1069
1070
var str = '';
1071
while (1) {
1072
var utf32 = HEAP32[(((ptr)+(i*4))>>2)];
1073
if (utf32 == 0)
1074
return str;
1075
++i;
1076
// Gotcha: fromCharCode constructs a character from a UTF-16 encoded code (pair), not from a Unicode code point! So encode the code point to UTF-16 for constructing.
1077
// See http://unicode.org/faq/utf_bom.html#utf16-3
1078
if (utf32 >= 0x10000) {
1079
var ch = utf32 - 0x10000;
1080
str += String.fromCharCode(0xD800 | (ch >> 10), 0xDC00 | (ch & 0x3FF));
1081
} else {
1082
str += String.fromCharCode(utf32);
1083
}
1084
}
1085
}
1086
1087
// Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr',
1088
// null-terminated and encoded in UTF32 form. The copy will require at most str.length*4+4 bytes of space in the HEAP.
1089
// Use the function lengthBytesUTF32() to compute the exact number of bytes (excluding null terminator) that this function will write.
1090
// Parameters:
1091
// str: the Javascript string to copy.
1092
// outPtr: Byte address in Emscripten HEAP where to write the string to.
1093
// maxBytesToWrite: The maximum number of bytes this function can write to the array. This count should include the null
1094
// terminator, i.e. if maxBytesToWrite=4, only the null terminator will be written and nothing else.
1095
// maxBytesToWrite<4 does not write any bytes to the output, not even the null terminator.
1096
// Returns the number of bytes written, EXCLUDING the null terminator.
1097
1098
function stringToUTF32(str, outPtr, maxBytesToWrite) {
1099
assert(outPtr % 4 == 0, 'Pointer passed to stringToUTF32 must be aligned to four bytes!');
1100
assert(typeof maxBytesToWrite == 'number', 'stringToUTF32(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!');
1101
// Backwards compatibility: if max bytes is not specified, assume unsafe unbounded write is allowed.
1102
if (maxBytesToWrite === undefined) {
1103
maxBytesToWrite = 0x7FFFFFFF;
1104
}
1105
if (maxBytesToWrite < 4) return 0;
1106
var startPtr = outPtr;
1107
var endPtr = startPtr + maxBytesToWrite - 4;
1108
for (var i = 0; i < str.length; ++i) {
1109
// Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code unit, not a Unicode code point of the character! We must decode the string to UTF-32 to the heap.
1110
// See http://unicode.org/faq/utf_bom.html#utf16-3
1111
var codeUnit = str.charCodeAt(i); // possibly a lead surrogate
1112
if (codeUnit >= 0xD800 && codeUnit <= 0xDFFF) {
1113
var trailSurrogate = str.charCodeAt(++i);
1114
codeUnit = 0x10000 + ((codeUnit & 0x3FF) << 10) | (trailSurrogate & 0x3FF);
1115
}
1116
HEAP32[((outPtr)>>2)]=codeUnit;
1117
outPtr += 4;
1118
if (outPtr + 4 > endPtr) break;
1119
}
1120
// Null-terminate the pointer to the HEAP.
1121
HEAP32[((outPtr)>>2)]=0;
1122
return outPtr - startPtr;
1123
}
1124
1125
// Returns the number of bytes the given Javascript string takes if encoded as a UTF16 byte array, EXCLUDING the null terminator byte.
1126
1127
function lengthBytesUTF32(str) {
1128
var len = 0;
1129
for (var i = 0; i < str.length; ++i) {
1130
// Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code unit, not a Unicode code point of the character! We must decode the string to UTF-32 to the heap.
1131
// See http://unicode.org/faq/utf_bom.html#utf16-3
1132
var codeUnit = str.charCodeAt(i);
1133
if (codeUnit >= 0xD800 && codeUnit <= 0xDFFF) ++i; // possibly a lead surrogate, so skip over the tail surrogate.
1134
len += 4;
1135
}
1136
1137
return len;
1138
}
1139
1140
// Allocate heap space for a JS string, and write it there.
1141
// It is the responsibility of the caller to free() that memory.
1142
function allocateUTF8(str) {
1143
var size = lengthBytesUTF8(str) + 1;
1144
var ret = _malloc(size);
1145
if (ret) stringToUTF8Array(str, HEAP8, ret, size);
1146
return ret;
1147
}
1148
1149
// Allocate stack space for a JS string, and write it there.
1150
function allocateUTF8OnStack(str) {
1151
var size = lengthBytesUTF8(str) + 1;
1152
var ret = stackAlloc(size);
1153
stringToUTF8Array(str, HEAP8, ret, size);
1154
return ret;
1155
}
1156
1157
// Deprecated: This function should not be called because it is unsafe and does not provide
1158
// a maximum length limit of how many bytes it is allowed to write. Prefer calling the
1159
// function stringToUTF8Array() instead, which takes in a maximum length that can be used
1160
// to be secure from out of bounds writes.
1161
/** @deprecated
1162
@param {boolean=} dontAddNull */
1163
function writeStringToMemory(string, buffer, dontAddNull) {
1164
warnOnce('writeStringToMemory is deprecated and should not be called! Use stringToUTF8() instead!');
1165
1166
var /** @type {number} */ lastChar, /** @type {number} */ end;
1167
if (dontAddNull) {
1168
// stringToUTF8Array always appends null. If we don't want to do that, remember the
1169
// character that existed at the location where the null will be placed, and restore
1170
// that after the write (below).
1171
end = buffer + lengthBytesUTF8(string);
1172
lastChar = HEAP8[end];
1173
}
1174
stringToUTF8(string, buffer, Infinity);
1175
if (dontAddNull) HEAP8[end] = lastChar; // Restore the value under the null character.
1176
}
1177
1178
function writeArrayToMemory(array, buffer) {
1179
assert(array.length >= 0, 'writeArrayToMemory array must have a length (should be an array or typed array)')
1180
HEAP8.set(array, buffer);
1181
}
1182
1183
/** @param {boolean=} dontAddNull */
1184
function writeAsciiToMemory(str, buffer, dontAddNull) {
1185
for (var i = 0; i < str.length; ++i) {
1186
assert(str.charCodeAt(i) === str.charCodeAt(i)&0xff);
1187
HEAP8[((buffer++)>>0)]=str.charCodeAt(i);
1188
}
1189
// Null-terminate the pointer to the HEAP.
1190
if (!dontAddNull) HEAP8[((buffer)>>0)]=0;
1191
}
1192
1193
1194
1195
// Memory management
1196
1197
var PAGE_SIZE = 16384;
1198
var WASM_PAGE_SIZE = 65536;
1199
var ASMJS_PAGE_SIZE = 16777216;
1200
1201
function alignUp(x, multiple) {
1202
if (x % multiple > 0) {
1203
x += multiple - (x % multiple);
1204
}
1205
return x;
1206
}
1207
1208
var HEAP,
1209
/** @type {ArrayBuffer} */
1210
buffer,
1211
/** @type {Int8Array} */
1212
HEAP8,
1213
/** @type {Uint8Array} */
1214
HEAPU8,
1215
/** @type {Int16Array} */
1216
HEAP16,
1217
/** @type {Uint16Array} */
1218
HEAPU16,
1219
/** @type {Int32Array} */
1220
HEAP32,
1221
/** @type {Uint32Array} */
1222
HEAPU32,
1223
/** @type {Float32Array} */
1224
HEAPF32,
1225
/** @type {Float64Array} */
1226
HEAPF64;
1227
1228
function updateGlobalBufferAndViews(buf) {
1229
buffer = buf;
1230
Module['HEAP8'] = HEAP8 = new Int8Array(buf);
1231
Module['HEAP16'] = HEAP16 = new Int16Array(buf);
1232
Module['HEAP32'] = HEAP32 = new Int32Array(buf);
1233
Module['HEAPU8'] = HEAPU8 = new Uint8Array(buf);
1234
Module['HEAPU16'] = HEAPU16 = new Uint16Array(buf);
1235
Module['HEAPU32'] = HEAPU32 = new Uint32Array(buf);
1236
Module['HEAPF32'] = HEAPF32 = new Float32Array(buf);
1237
Module['HEAPF64'] = HEAPF64 = new Float64Array(buf);
1238
}
1239
1240
var STATIC_BASE = 1024,
1241
STACK_BASE = 19593120,
1242
STACKTOP = STACK_BASE,
1243
STACK_MAX = 14350240,
1244
DYNAMIC_BASE = 19593120,
1245
DYNAMICTOP_PTR = 14350080;
1246
1247
assert(STACK_BASE % 16 === 0, 'stack must start aligned');
1248
assert(DYNAMIC_BASE % 16 === 0, 'heap must start aligned');
1249
1250
1251
1252
var TOTAL_STACK = 5242880;
1253
if (Module['TOTAL_STACK']) assert(TOTAL_STACK === Module['TOTAL_STACK'], 'the stack size can no longer be determined at runtime')
1254
1255
var INITIAL_INITIAL_MEMORY = Module['INITIAL_MEMORY'] || 20971520;if (!Object.getOwnPropertyDescriptor(Module, 'INITIAL_MEMORY')) Object.defineProperty(Module, 'INITIAL_MEMORY', { configurable: true, get: function() { abort('Module.INITIAL_MEMORY has been replaced with plain INITIAL_INITIAL_MEMORY') } });
1256
1257
assert(INITIAL_INITIAL_MEMORY >= TOTAL_STACK, 'INITIAL_MEMORY should be larger than TOTAL_STACK, was ' + INITIAL_INITIAL_MEMORY + '! (TOTAL_STACK=' + TOTAL_STACK + ')');
1258
1259
// check for full engine support (use string 'subarray' to avoid closure compiler confusion)
1260
assert(typeof Int32Array !== 'undefined' && typeof Float64Array !== 'undefined' && Int32Array.prototype.subarray !== undefined && Int32Array.prototype.set !== undefined,
1261
'JS engine does not provide full typed array support');
1262
1263
1264
1265
1266
1267
1268
// In standalone mode, the wasm creates the memory, and the user can't provide it.
1269
// In non-standalone/normal mode, we create the memory here.
1270
1271
// Create the main memory. (Note: this isn't used in STANDALONE_WASM mode since the wasm
1272
// memory is created in the wasm, not in JS.)
1273
1274
if (Module['wasmMemory']) {
1275
wasmMemory = Module['wasmMemory'];
1276
} else
1277
{
1278
wasmMemory = new WebAssembly.Memory({
1279
'initial': INITIAL_INITIAL_MEMORY / WASM_PAGE_SIZE
1280
,
1281
'maximum': INITIAL_INITIAL_MEMORY / WASM_PAGE_SIZE
1282
});
1283
}
1284
1285
1286
if (wasmMemory) {
1287
buffer = wasmMemory.buffer;
1288
}
1289
1290
// If the user provides an incorrect length, just use that length instead rather than providing the user to
1291
// specifically provide the memory length with Module['INITIAL_MEMORY'].
1292
INITIAL_INITIAL_MEMORY = buffer.byteLength;
1293
assert(INITIAL_INITIAL_MEMORY % WASM_PAGE_SIZE === 0);
1294
updateGlobalBufferAndViews(buffer);
1295
1296
HEAP32[DYNAMICTOP_PTR>>2] = DYNAMIC_BASE;
1297
1298
1299
1300
1301
// Initializes the stack cookie. Called at the startup of main and at the startup of each thread in pthreads mode.
1302
function writeStackCookie() {
1303
assert((STACK_MAX & 3) == 0);
1304
// The stack grows downwards
1305
HEAPU32[(STACK_MAX >> 2)+1] = 0x2135467;
1306
HEAPU32[(STACK_MAX >> 2)+2] = 0x89BACDFE;
1307
// Also test the global address 0 for integrity.
1308
// We don't do this with ASan because ASan does its own checks for this.
1309
HEAP32[0] = 0x63736d65; /* 'emsc' */
1310
}
1311
1312
function checkStackCookie() {
1313
var cookie1 = HEAPU32[(STACK_MAX >> 2)+1];
1314
var cookie2 = HEAPU32[(STACK_MAX >> 2)+2];
1315
if (cookie1 != 0x2135467 || cookie2 != 0x89BACDFE) {
1316
abort('Stack overflow! Stack cookie has been overwritten, expected hex dwords 0x89BACDFE and 0x2135467, but received 0x' + cookie2.toString(16) + ' ' + cookie1.toString(16));
1317
}
1318
// Also test the global address 0 for integrity.
1319
// We don't do this with ASan because ASan does its own checks for this.
1320
if (HEAP32[0] !== 0x63736d65 /* 'emsc' */) abort('Runtime error: The application has corrupted its heap memory area (address zero)!');
1321
}
1322
1323
function abortStackOverflow(allocSize) {
1324
abort('Stack overflow! Attempted to allocate ' + allocSize + ' bytes on the stack, but stack has only ' + (STACK_MAX - stackSave() + allocSize) + ' bytes available!');
1325
}
1326
1327
1328
1329
1330
// Endianness check (note: assumes compiler arch was little-endian)
1331
(function() {
1332
var h16 = new Int16Array(1);
1333
var h8 = new Int8Array(h16.buffer);
1334
h16[0] = 0x6373;
1335
if (h8[0] !== 0x73 || h8[1] !== 0x63) throw 'Runtime error: expected the system to be little-endian!';
1336
})();
1337
1338
function abortFnPtrError(ptr, sig) {
1339
abort("Invalid function pointer " + ptr + " called with signature '" + sig + "'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this). Build with ASSERTIONS=2 for more info.");
1340
}
1341
1342
1343
1344
function callRuntimeCallbacks(callbacks) {
1345
while(callbacks.length > 0) {
1346
var callback = callbacks.shift();
1347
if (typeof callback == 'function') {
1348
callback();
1349
continue;
1350
}
1351
var func = callback.func;
1352
if (typeof func === 'number') {
1353
if (callback.arg === undefined) {
1354
Module['dynCall_v'](func);
1355
} else {
1356
Module['dynCall_vi'](func, callback.arg);
1357
}
1358
} else {
1359
func(callback.arg === undefined ? null : callback.arg);
1360
}
1361
}
1362
}
1363
1364
var __ATPRERUN__ = []; // functions called before the runtime is initialized
1365
var __ATINIT__ = []; // functions called during startup
1366
var __ATMAIN__ = []; // functions called when main() is to be run
1367
var __ATEXIT__ = []; // functions called during shutdown
1368
var __ATPOSTRUN__ = []; // functions called after the main() is called
1369
1370
var runtimeInitialized = false;
1371
var runtimeExited = false;
1372
1373
1374
function preRun() {
1375
1376
if (Module['preRun']) {
1377
if (typeof Module['preRun'] == 'function') Module['preRun'] = [Module['preRun']];
1378
while (Module['preRun'].length) {
1379
addOnPreRun(Module['preRun'].shift());
1380
}
1381
}
1382
1383
callRuntimeCallbacks(__ATPRERUN__);
1384
}
1385
1386
function initRuntime() {
1387
checkStackCookie();
1388
assert(!runtimeInitialized);
1389
runtimeInitialized = true;
1390
if (!Module["noFSInit"] && !FS.init.initialized) FS.init();
1391
TTY.init();
1392
callRuntimeCallbacks(__ATINIT__);
1393
}
1394
1395
function preMain() {
1396
checkStackCookie();
1397
FS.ignorePermissions = false;
1398
callRuntimeCallbacks(__ATMAIN__);
1399
}
1400
1401
function exitRuntime() {
1402
checkStackCookie();
1403
runtimeExited = true;
1404
}
1405
1406
function postRun() {
1407
checkStackCookie();
1408
1409
if (Module['postRun']) {
1410
if (typeof Module['postRun'] == 'function') Module['postRun'] = [Module['postRun']];
1411
while (Module['postRun'].length) {
1412
addOnPostRun(Module['postRun'].shift());
1413
}
1414
}
1415
1416
callRuntimeCallbacks(__ATPOSTRUN__);
1417
}
1418
1419
function addOnPreRun(cb) {
1420
__ATPRERUN__.unshift(cb);
1421
}
1422
1423
function addOnInit(cb) {
1424
__ATINIT__.unshift(cb);
1425
}
1426
1427
function addOnPreMain(cb) {
1428
__ATMAIN__.unshift(cb);
1429
}
1430
1431
function addOnExit(cb) {
1432
}
1433
1434
function addOnPostRun(cb) {
1435
__ATPOSTRUN__.unshift(cb);
1436
}
1437
1438
/** @param {number|boolean=} ignore */
1439
function unSign(value, bits, ignore) {
1440
if (value >= 0) {
1441
return value;
1442
}
1443
return bits <= 32 ? 2*Math.abs(1 << (bits-1)) + value // Need some trickery, since if bits == 32, we are right at the limit of the bits JS uses in bitshifts
1444
: Math.pow(2, bits) + value;
1445
}
1446
/** @param {number|boolean=} ignore */
1447
function reSign(value, bits, ignore) {
1448
if (value <= 0) {
1449
return value;
1450
}
1451
var half = bits <= 32 ? Math.abs(1 << (bits-1)) // abs is needed if bits == 32
1452
: Math.pow(2, bits-1);
1453
if (value >= half && (bits <= 32 || value > half)) { // for huge values, we can hit the precision limit and always get true here. so don't do that
1454
// but, in general there is no perfect solution here. With 64-bit ints, we get rounding and errors
1455
// TODO: In i64 mode 1, resign the two parts separately and safely
1456
value = -2*half + value; // Cannot bitshift half, as it may be at the limit of the bits JS uses in bitshifts
1457
}
1458
return value;
1459
}
1460
1461
1462
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/imul
1463
1464
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/fround
1465
1466
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32
1467
1468
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc
1469
1470
assert(Math.imul, 'This browser does not support Math.imul(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill');
1471
assert(Math.fround, 'This browser does not support Math.fround(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill');
1472
assert(Math.clz32, 'This browser does not support Math.clz32(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill');
1473
assert(Math.trunc, 'This browser does not support Math.trunc(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill');
1474
1475
var Math_abs = Math.abs;
1476
var Math_cos = Math.cos;
1477
var Math_sin = Math.sin;
1478
var Math_tan = Math.tan;
1479
var Math_acos = Math.acos;
1480
var Math_asin = Math.asin;
1481
var Math_atan = Math.atan;
1482
var Math_atan2 = Math.atan2;
1483
var Math_exp = Math.exp;
1484
var Math_log = Math.log;
1485
var Math_sqrt = Math.sqrt;
1486
var Math_ceil = Math.ceil;
1487
var Math_floor = Math.floor;
1488
var Math_pow = Math.pow;
1489
var Math_imul = Math.imul;
1490
var Math_fround = Math.fround;
1491
var Math_round = Math.round;
1492
var Math_min = Math.min;
1493
var Math_max = Math.max;
1494
var Math_clz32 = Math.clz32;
1495
var Math_trunc = Math.trunc;
1496
1497
1498
1499
// A counter of dependencies for calling run(). If we need to
1500
// do asynchronous work before running, increment this and
1501
// decrement it. Incrementing must happen in a place like
1502
// Module.preRun (used by emcc to add file preloading).
1503
// Note that you can add dependencies in preRun, even though
1504
// it happens right before run - run will be postponed until
1505
// the dependencies are met.
1506
var runDependencies = 0;
1507
var runDependencyWatcher = null;
1508
var dependenciesFulfilled = null; // overridden to take different actions when all run dependencies are fulfilled
1509
var runDependencyTracking = {};
1510
1511
function getUniqueRunDependency(id) {
1512
var orig = id;
1513
while (1) {
1514
if (!runDependencyTracking[id]) return id;
1515
id = orig + Math.random();
1516
}
1517
}
1518
1519
function addRunDependency(id) {
1520
runDependencies++;
1521
1522
if (Module['monitorRunDependencies']) {
1523
Module['monitorRunDependencies'](runDependencies);
1524
}
1525
1526
if (id) {
1527
assert(!runDependencyTracking[id]);
1528
runDependencyTracking[id] = 1;
1529
if (runDependencyWatcher === null && typeof setInterval !== 'undefined') {
1530
// Check for missing dependencies every few seconds
1531
runDependencyWatcher = setInterval(function() {
1532
if (ABORT) {
1533
clearInterval(runDependencyWatcher);
1534
runDependencyWatcher = null;
1535
return;
1536
}
1537
var shown = false;
1538
for (var dep in runDependencyTracking) {
1539
if (!shown) {
1540
shown = true;
1541
err('still waiting on run dependencies:');
1542
}
1543
err('dependency: ' + dep);
1544
}
1545
if (shown) {
1546
err('(end of list)');
1547
}
1548
}, 10000);
1549
}
1550
} else {
1551
err('warning: run dependency added without ID');
1552
}
1553
}
1554
1555
function removeRunDependency(id) {
1556
runDependencies--;
1557
1558
if (Module['monitorRunDependencies']) {
1559
Module['monitorRunDependencies'](runDependencies);
1560
}
1561
1562
if (id) {
1563
assert(runDependencyTracking[id]);
1564
delete runDependencyTracking[id];
1565
} else {
1566
err('warning: run dependency removed without ID');
1567
}
1568
if (runDependencies == 0) {
1569
if (runDependencyWatcher !== null) {
1570
clearInterval(runDependencyWatcher);
1571
runDependencyWatcher = null;
1572
}
1573
if (dependenciesFulfilled) {
1574
var callback = dependenciesFulfilled;
1575
dependenciesFulfilled = null;
1576
callback(); // can add another dependenciesFulfilled
1577
}
1578
}
1579
}
1580
1581
Module["preloadedImages"] = {}; // maps url to image data
1582
Module["preloadedAudios"] = {}; // maps url to audio data
1583
1584
1585
/** @param {string|number=} what */
1586
function abort(what) {
1587
if (Module['onAbort']) {
1588
Module['onAbort'](what);
1589
}
1590
1591
what += '';
1592
out(what);
1593
err(what);
1594
1595
ABORT = true;
1596
EXITSTATUS = 1;
1597
1598
var output = 'abort(' + what + ') at ' + stackTrace();
1599
what = output;
1600
1601
// Throw a wasm runtime error, because a JS error might be seen as a foreign
1602
// exception, which means we'd run destructors on it. We need the error to
1603
// simply make the program stop.
1604
throw new WebAssembly.RuntimeError(what);
1605
}
1606
1607
1608
var memoryInitializer = null;
1609
1610
1611
1612
1613
1614
1615
1616
1617
// Copyright 2017 The Emscripten Authors. All rights reserved.
1618
// Emscripten is available under two separate licenses, the MIT license and the
1619
// University of Illinois/NCSA Open Source License. Both these licenses can be
1620
// found in the LICENSE file.
1621
1622
// Prefix of data URIs emitted by SINGLE_FILE and related options.
1623
var dataURIPrefix = 'data:application/octet-stream;base64,';
1624
1625
// Indicates whether filename is a base64 data URI.
1626
function isDataURI(filename) {
1627
return String.prototype.startsWith ?
1628
filename.startsWith(dataURIPrefix) :
1629
filename.indexOf(dataURIPrefix) === 0;
1630
}
1631
1632
1633
1634
1635
var wasmBinaryFile = 'sm64.us.f3dex2e.wasm';
1636
if (!isDataURI(wasmBinaryFile)) {
1637
wasmBinaryFile = locateFile(wasmBinaryFile);
1638
}
1639
1640
function getBinary() {
1641
try {
1642
if (wasmBinary) {
1643
return new Uint8Array(wasmBinary);
1644
}
1645
1646
if (readBinary) {
1647
return readBinary(wasmBinaryFile);
1648
} else {
1649
throw "both async and sync fetching of the wasm failed";
1650
}
1651
}
1652
catch (err) {
1653
abort(err);
1654
}
1655
}
1656
1657
function getBinaryPromise() {
1658
// if we don't have the binary yet, and have the Fetch api, use that
1659
// in some environments, like Electron's render process, Fetch api may be present, but have a different context than expected, let's only use it on the Web
1660
if (!wasmBinary && (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) && typeof fetch === 'function') {
1661
return fetch(wasmBinaryFile, { credentials: 'same-origin' }).then(function(response) {
1662
if (!response['ok']) {
1663
throw "failed to load wasm binary file at '" + wasmBinaryFile + "'";
1664
}
1665
return response['arrayBuffer']();
1666
}).catch(function () {
1667
return getBinary();
1668
});
1669
}
1670
// Otherwise, getBinary should be able to get it synchronously
1671
return new Promise(function(resolve, reject) {
1672
resolve(getBinary());
1673
});
1674
}
1675
1676
1677
1678
// Create the wasm instance.
1679
// Receives the wasm imports, returns the exports.
1680
function createWasm() {
1681
// prepare imports
1682
var info = {
1683
'env': asmLibraryArg,
1684
'wasi_snapshot_preview1': asmLibraryArg
1685
};
1686
// Load the wasm module and create an instance of using native support in the JS engine.
1687
// handle a generated wasm instance, receiving its exports and
1688
// performing other necessary setup
1689
/** @param {WebAssembly.Module=} module*/
1690
function receiveInstance(instance, module) {
1691
var exports = instance.exports;
1692
Module['asm'] = exports;
1693
removeRunDependency('wasm-instantiate');
1694
}
1695
// we can't run yet (except in a pthread, where we have a custom sync instantiator)
1696
addRunDependency('wasm-instantiate');
1697
1698
1699
// Async compilation can be confusing when an error on the page overwrites Module
1700
// (for example, if the order of elements is wrong, and the one defining Module is
1701
// later), so we save Module and check it later.
1702
var trueModule = Module;
1703
function receiveInstantiatedSource(output) {
1704
// 'output' is a WebAssemblyInstantiatedSource object which has both the module and instance.
1705
// receiveInstance() will swap in the exports (to Module.asm) so they can be called
1706
assert(Module === trueModule, 'the Module object should not be replaced during async compilation - perhaps the order of HTML elements is wrong?');
1707
trueModule = null;
1708
// TODO: Due to Closure regression https://github.com/google/closure-compiler/issues/3193, the above line no longer optimizes out down to the following line.
1709
// When the regression is fixed, can restore the above USE_PTHREADS-enabled path.
1710
receiveInstance(output['instance']);
1711
}
1712
1713
1714
function instantiateArrayBuffer(receiver) {
1715
return getBinaryPromise().then(function(binary) {
1716
return WebAssembly.instantiate(binary, info);
1717
}).then(receiver, function(reason) {
1718
err('failed to asynchronously prepare wasm: ' + reason);
1719
abort(reason);
1720
});
1721
}
1722
1723
// Prefer streaming instantiation if available.
1724
function instantiateAsync() {
1725
if (!wasmBinary &&
1726
typeof WebAssembly.instantiateStreaming === 'function' &&
1727
!isDataURI(wasmBinaryFile) &&
1728
typeof fetch === 'function') {
1729
fetch(wasmBinaryFile, { credentials: 'same-origin' }).then(function (response) {
1730
var result = WebAssembly.instantiateStreaming(response, info);
1731
return result.then(receiveInstantiatedSource, function(reason) {
1732
// We expect the most common failure cause to be a bad MIME type for the binary,
1733
// in which case falling back to ArrayBuffer instantiation should work.
1734
err('wasm streaming compile failed: ' + reason);
1735
err('falling back to ArrayBuffer instantiation');
1736
instantiateArrayBuffer(receiveInstantiatedSource);
1737
});
1738
});
1739
} else {
1740
return instantiateArrayBuffer(receiveInstantiatedSource);
1741
}
1742
}
1743
// User shell pages can write their own Module.instantiateWasm = function(imports, successCallback) callback
1744
// to manually instantiate the Wasm module themselves. This allows pages to run the instantiation parallel
1745
// to any other async startup actions they are performing.
1746
if (Module['instantiateWasm']) {
1747
try {
1748
var exports = Module['instantiateWasm'](info, receiveInstance);
1749
return exports;
1750
} catch(e) {
1751
err('Module.instantiateWasm callback failed with error: ' + e);
1752
return false;
1753
}
1754
}
1755
1756
instantiateAsync();
1757
return {}; // no exports yet; we'll fill them in later
1758
}
1759
1760
1761
// Globals used by JS i64 conversions
1762
var tempDouble;
1763
var tempI64;
1764
1765
// === Body ===
1766
1767
var ASM_CONSTS = {
1768
3069901: function($0) {requestAnimationFrame(function(time) { dynCall("vd", $0, [time]); })},
1769
3069970: function($0) {var s = localStorage.sm64_save_file; if (s && s.length === 684) { try { var binary = atob(s); if (binary.length === 512) { for (var i = 0; i < 512; i++) { HEAPU8[$0 + i] = binary.charCodeAt(i); } return 1; } } catch (e) { } } return 0;},
1770
3070210: function($0) {var str = ""; for (var i = 0; i < 512; i++) { str += String.fromCharCode(HEAPU8[$0 + i]); } localStorage.sm64_save_file = btoa(str);},
1771
8775252: function($0, $1, $2) {var w = $0; var h = $1; var pixels = $2; if (!Module['SDL2']) Module['SDL2'] = {}; var SDL2 = Module['SDL2']; if (SDL2.ctxCanvas !== Module['canvas']) { SDL2.ctx = Module['createContext'](Module['canvas'], false, true); SDL2.ctxCanvas = Module['canvas']; } if (SDL2.w !== w || SDL2.h !== h || SDL2.imageCtx !== SDL2.ctx) { SDL2.image = SDL2.ctx.createImageData(w, h); SDL2.w = w; SDL2.h = h; SDL2.imageCtx = SDL2.ctx; } var data = SDL2.image.data; var src = pixels >> 2; var dst = 0; var num; if (typeof CanvasPixelArray !== 'undefined' && data instanceof CanvasPixelArray) { num = data.length; while (dst < num) { var val = HEAP32[src]; data[dst ] = val & 0xff; data[dst+1] = (val >> 8) & 0xff; data[dst+2] = (val >> 16) & 0xff; data[dst+3] = 0xff; src++; dst += 4; } } else { if (SDL2.data32Data !== data) { SDL2.data32 = new Int32Array(data.buffer); SDL2.data8 = new Uint8Array(data.buffer); } var data32 = SDL2.data32; num = data32.length; data32.set(HEAP32.subarray(src, src + num)); var data8 = SDL2.data8; var i = 3; var j = i + 4*num; if (num % 8 == 0) { while (i < j) { data8[i] = 0xff; i = i + 4 | 0; data8[i] = 0xff; i = i + 4 | 0; data8[i] = 0xff; i = i + 4 | 0; data8[i] = 0xff; i = i + 4 | 0; data8[i] = 0xff; i = i + 4 | 0; data8[i] = 0xff; i = i + 4 | 0; data8[i] = 0xff; i = i + 4 | 0; data8[i] = 0xff; i = i + 4 | 0; } } else { while (i < j) { data8[i] = 0xff; i = i + 4 | 0; } } } SDL2.ctx.putImageData(SDL2.image, 0, 0); return 0;},
1772
8776707: function($0, $1, $2, $3, $4) {var w = $0; var h = $1; var hot_x = $2; var hot_y = $3; var pixels = $4; var canvas = document.createElement("canvas"); canvas.width = w; canvas.height = h; var ctx = canvas.getContext("2d"); var image = ctx.createImageData(w, h); var data = image.data; var src = pixels >> 2; var dst = 0; var num; if (typeof CanvasPixelArray !== 'undefined' && data instanceof CanvasPixelArray) { num = data.length; while (dst < num) { var val = HEAP32[src]; data[dst ] = val & 0xff; data[dst+1] = (val >> 8) & 0xff; data[dst+2] = (val >> 16) & 0xff; data[dst+3] = (val >> 24) & 0xff; src++; dst += 4; } } else { var data32 = new Int32Array(data.buffer); num = data32.length; data32.set(HEAP32.subarray(src, src + num)); } ctx.putImageData(image, 0, 0); var url = hot_x === 0 && hot_y === 0 ? "url(" + canvas.toDataURL() + "), auto" : "url(" + canvas.toDataURL() + ") " + hot_x + " " + hot_y + ", auto"; var urlBuf = _malloc(url.length + 1); stringToUTF8(url, urlBuf, url.length + 1); return urlBuf;},
1773
8777696: function($0) {if (Module['canvas']) { Module['canvas'].style['cursor'] = UTF8ToString($0); } return 0;},
1774
8777789: function() {if (Module['canvas']) { Module['canvas'].style['cursor'] = 'none'; }},
1775
8779014: function() {return screen.width;},
1776
8779041: function() {return screen.height;},
1777
8779069: function() {return window.innerWidth;},
1778
8779101: function() {return window.innerHeight;},
1779
8779179: function($0) {if (typeof Module['setWindowTitle'] !== 'undefined') { Module['setWindowTitle'](UTF8ToString($0)); } return 0;},
1780
8779333: function() {if (typeof(AudioContext) !== 'undefined') { return 1; } else if (typeof(webkitAudioContext) !== 'undefined') { return 1; } return 0;},
1781
8779499: function() {if ((typeof(navigator.mediaDevices) !== 'undefined') && (typeof(navigator.mediaDevices.getUserMedia) !== 'undefined')) { return 1; } else if (typeof(navigator.webkitGetUserMedia) !== 'undefined') { return 1; } return 0;},
1782
8779725: function($0) {if(typeof(Module['SDL2']) === 'undefined') { Module['SDL2'] = {}; } var SDL2 = Module['SDL2']; if (!$0) { SDL2.audio = {}; } else { SDL2.capture = {}; } if (!SDL2.audioContext) { if (typeof(AudioContext) !== 'undefined') { SDL2.audioContext = new AudioContext(); } else if (typeof(webkitAudioContext) !== 'undefined') { SDL2.audioContext = new webkitAudioContext(); } } return SDL2.audioContext === undefined ? -1 : 0;},
1783
8780208: function() {var SDL2 = Module['SDL2']; return SDL2.audioContext.sampleRate;},
1784
8780278: function($0, $1, $2, $3) {var SDL2 = Module['SDL2']; var have_microphone = function(stream) { if (SDL2.capture.silenceTimer !== undefined) { clearTimeout(SDL2.capture.silenceTimer); SDL2.capture.silenceTimer = undefined; } SDL2.capture.mediaStreamNode = SDL2.audioContext.createMediaStreamSource(stream); SDL2.capture.scriptProcessorNode = SDL2.audioContext.createScriptProcessor($1, $0, 1); SDL2.capture.scriptProcessorNode.onaudioprocess = function(audioProcessingEvent) { if ((SDL2 === undefined) || (SDL2.capture === undefined)) { return; } audioProcessingEvent.outputBuffer.getChannelData(0).fill(0.0); SDL2.capture.currentCaptureBuffer = audioProcessingEvent.inputBuffer; dynCall('vi', $2, [$3]); }; SDL2.capture.mediaStreamNode.connect(SDL2.capture.scriptProcessorNode); SDL2.capture.scriptProcessorNode.connect(SDL2.audioContext.destination); SDL2.capture.stream = stream; }; var no_microphone = function(error) { }; SDL2.capture.silenceBuffer = SDL2.audioContext.createBuffer($0, $1, SDL2.audioContext.sampleRate); SDL2.capture.silenceBuffer.getChannelData(0).fill(0.0); var silence_callback = function() { SDL2.capture.currentCaptureBuffer = SDL2.capture.silenceBuffer; dynCall('vi', $2, [$3]); }; SDL2.capture.silenceTimer = setTimeout(silence_callback, ($1 / SDL2.audioContext.sampleRate) * 1000); if ((navigator.mediaDevices !== undefined) && (navigator.mediaDevices.getUserMedia !== undefined)) { navigator.mediaDevices.getUserMedia({ audio: true, video: false }).then(have_microphone).catch(no_microphone); } else if (navigator.webkitGetUserMedia !== undefined) { navigator.webkitGetUserMedia({ audio: true, video: false }, have_microphone, no_microphone); }},
1785
8781930: function($0, $1, $2, $3) {var SDL2 = Module['SDL2']; SDL2.audio.scriptProcessorNode = SDL2.audioContext['createScriptProcessor']($1, 0, $0); SDL2.audio.scriptProcessorNode['onaudioprocess'] = function (e) { if ((SDL2 === undefined) || (SDL2.audio === undefined)) { return; } SDL2.audio.currentOutputBuffer = e['outputBuffer']; dynCall('vi', $2, [$3]); }; SDL2.audio.scriptProcessorNode['connect'](SDL2.audioContext['destination']);},
1786
8782340: function($0, $1) {var SDL2 = Module['SDL2']; var numChannels = SDL2.capture.currentCaptureBuffer.numberOfChannels; for (var c = 0; c < numChannels; ++c) { var channelData = SDL2.capture.currentCaptureBuffer.getChannelData(c); if (channelData.length != $1) { throw 'Web Audio capture buffer length mismatch! Destination size: ' + channelData.length + ' samples vs expected ' + $1 + ' samples!'; } if (numChannels == 1) { for (var j = 0; j < $1; ++j) { setValue($0 + (j * 4), channelData[j], 'float'); } } else { for (var j = 0; j < $1; ++j) { setValue($0 + (((j * numChannels) + c) * 4), channelData[j], 'float'); } } }},
1787
8782945: function($0, $1) {var SDL2 = Module['SDL2']; var numChannels = SDL2.audio.currentOutputBuffer['numberOfChannels']; for (var c = 0; c < numChannels; ++c) { var channelData = SDL2.audio.currentOutputBuffer['getChannelData'](c); if (channelData.length != $1) { throw 'Web Audio output buffer length mismatch! Destination size: ' + channelData.length + ' samples vs expected ' + $1 + ' samples!'; } for (var j = 0; j < $1; ++j) { channelData[j] = HEAPF32[$0 + ((j*numChannels + c) << 2) >> 2]; } }},
1788
8783425: function($0) {var SDL2 = Module['SDL2']; if ($0) { if (SDL2.capture.silenceTimer !== undefined) { clearTimeout(SDL2.capture.silenceTimer); } if (SDL2.capture.stream !== undefined) { var tracks = SDL2.capture.stream.getAudioTracks(); for (var i = 0; i < tracks.length; i++) { SDL2.capture.stream.removeTrack(tracks[i]); } SDL2.capture.stream = undefined; } if (SDL2.capture.scriptProcessorNode !== undefined) { SDL2.capture.scriptProcessorNode.onaudioprocess = function(audioProcessingEvent) {}; SDL2.capture.scriptProcessorNode.disconnect(); SDL2.capture.scriptProcessorNode = undefined; } if (SDL2.capture.mediaStreamNode !== undefined) { SDL2.capture.mediaStreamNode.disconnect(); SDL2.capture.mediaStreamNode = undefined; } if (SDL2.capture.silenceBuffer !== undefined) { SDL2.capture.silenceBuffer = undefined } SDL2.capture = undefined; } else { if (SDL2.audio.scriptProcessorNode != undefined) { SDL2.audio.scriptProcessorNode.disconnect(); SDL2.audio.scriptProcessorNode = undefined; } SDL2.audio = undefined; } if ((SDL2.audioContext !== undefined) && (SDL2.audio === undefined) && (SDL2.capture === undefined)) { SDL2.audioContext.close(); SDL2.audioContext = undefined; }}
1789
};
1790
1791
function _emscripten_asm_const_iii(code, sigPtr, argbuf) {
1792
var args = readAsmConstArgs(sigPtr, argbuf);
1793
return ASM_CONSTS[code].apply(null, args);
1794
}
1795
1796
1797
1798
// STATICTOP = STATIC_BASE + 14349216;
1799
/* global initializers */ __ATINIT__.push({ func: function() { ___wasm_call_ctors() } });
1800
1801
1802
1803
1804
/* no memory initializer */
1805
// {{PRE_LIBRARY}}
1806
1807
1808
function demangle(func) {
1809
warnOnce('warning: build with -s DEMANGLE_SUPPORT=1 to link in libcxxabi demangling');
1810
return func;
1811
}
1812
1813
function demangleAll(text) {
1814
var regex =
1815
/\b_Z[\w\d_]+/g;
1816
return text.replace(regex,
1817
function(x) {
1818
var y = demangle(x);
1819
return x === y ? x : (y + ' [' + x + ']');
1820
});
1821
}
1822
1823
function jsStackTrace() {
1824
var err = new Error();
1825
if (!err.stack) {
1826
// IE10+ special cases: It does have callstack info, but it is only populated if an Error object is thrown,
1827
// so try that as a special-case.
1828
try {
1829
throw new Error();
1830
} catch(e) {
1831
err = e;
1832
}
1833
if (!err.stack) {
1834
return '(no stack trace available)';
1835
}
1836
}
1837
return err.stack.toString();
1838
}
1839
1840
function stackTrace() {
1841
var js = jsStackTrace();
1842
if (Module['extraStackTrace']) js += '\n' + Module['extraStackTrace']();
1843
return demangleAll(js);
1844
}
1845
1846
function ___assert_fail(condition, filename, line, func) {
1847
abort('Assertion failed: ' + UTF8ToString(condition) + ', at: ' + [filename ? UTF8ToString(filename) : 'unknown filename', line, func ? UTF8ToString(func) : 'unknown function']);
1848
}
1849
1850
function ___handle_stack_overflow() {
1851
abort('stack overflow')
1852
}
1853
1854
1855
function ___setErrNo(value) {
1856
if (Module['___errno_location']) HEAP32[((Module['___errno_location']())>>2)]=value;
1857
else err('failed to set errno from JS');
1858
return value;
1859
}
1860
1861
1862
var PATH={splitPath:function(filename) {
1863
var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
1864
return splitPathRe.exec(filename).slice(1);
1865
},normalizeArray:function(parts, allowAboveRoot) {
1866
// if the path tries to go above the root, `up` ends up > 0
1867
var up = 0;
1868
for (var i = parts.length - 1; i >= 0; i--) {
1869
var last = parts[i];
1870
if (last === '.') {
1871
parts.splice(i, 1);
1872
} else if (last === '..') {
1873
parts.splice(i, 1);
1874
up++;
1875
} else if (up) {
1876
parts.splice(i, 1);
1877
up--;
1878
}
1879
}
1880
// if the path is allowed to go above the root, restore leading ..s
1881
if (allowAboveRoot) {
1882
for (; up; up--) {
1883
parts.unshift('..');
1884
}
1885
}
1886
return parts;
1887
},normalize:function(path) {
1888
var isAbsolute = path.charAt(0) === '/',
1889
trailingSlash = path.substr(-1) === '/';
1890
// Normalize the path
1891
path = PATH.normalizeArray(path.split('/').filter(function(p) {
1892
return !!p;
1893
}), !isAbsolute).join('/');
1894
if (!path && !isAbsolute) {
1895
path = '.';
1896
}
1897
if (path && trailingSlash) {
1898
path += '/';
1899
}
1900
return (isAbsolute ? '/' : '') + path;
1901
},dirname:function(path) {
1902
var result = PATH.splitPath(path),
1903
root = result[0],
1904
dir = result[1];
1905
if (!root && !dir) {
1906
// No dirname whatsoever
1907
return '.';
1908
}
1909
if (dir) {
1910
// It has a dirname, strip trailing slash
1911
dir = dir.substr(0, dir.length - 1);
1912
}
1913
return root + dir;
1914
},basename:function(path) {
1915
// EMSCRIPTEN return '/'' for '/', not an empty string
1916
if (path === '/') return '/';
1917
var lastSlash = path.lastIndexOf('/');
1918
if (lastSlash === -1) return path;
1919
return path.substr(lastSlash+1);
1920
},extname:function(path) {
1921
return PATH.splitPath(path)[3];
1922
},join:function() {
1923
var paths = Array.prototype.slice.call(arguments, 0);
1924
return PATH.normalize(paths.join('/'));
1925
},join2:function(l, r) {
1926
return PATH.normalize(l + '/' + r);
1927
}};
1928
1929
1930
var PATH_FS={resolve:function() {
1931
var resolvedPath = '',
1932
resolvedAbsolute = false;
1933
for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
1934
var path = (i >= 0) ? arguments[i] : FS.cwd();
1935
// Skip empty and invalid entries
1936
if (typeof path !== 'string') {
1937
throw new TypeError('Arguments to path.resolve must be strings');
1938
} else if (!path) {
1939
return ''; // an invalid portion invalidates the whole thing
1940
}
1941
resolvedPath = path + '/' + resolvedPath;
1942
resolvedAbsolute = path.charAt(0) === '/';
1943
}
1944
// At this point the path should be resolved to a full absolute path, but
1945
// handle relative paths to be safe (might happen when process.cwd() fails)
1946
resolvedPath = PATH.normalizeArray(resolvedPath.split('/').filter(function(p) {
1947
return !!p;
1948
}), !resolvedAbsolute).join('/');
1949
return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
1950
},relative:function(from, to) {
1951
from = PATH_FS.resolve(from).substr(1);
1952
to = PATH_FS.resolve(to).substr(1);
1953
function trim(arr) {
1954
var start = 0;
1955
for (; start < arr.length; start++) {
1956
if (arr[start] !== '') break;
1957
}
1958
var end = arr.length - 1;
1959
for (; end >= 0; end--) {
1960
if (arr[end] !== '') break;
1961
}
1962
if (start > end) return [];
1963
return arr.slice(start, end - start + 1);
1964
}
1965
var fromParts = trim(from.split('/'));
1966
var toParts = trim(to.split('/'));
1967
var length = Math.min(fromParts.length, toParts.length);
1968
var samePartsLength = length;
1969
for (var i = 0; i < length; i++) {
1970
if (fromParts[i] !== toParts[i]) {
1971
samePartsLength = i;
1972
break;
1973
}
1974
}
1975
var outputParts = [];
1976
for (var i = samePartsLength; i < fromParts.length; i++) {
1977
outputParts.push('..');
1978
}
1979
outputParts = outputParts.concat(toParts.slice(samePartsLength));
1980
return outputParts.join('/');
1981
}};
1982
1983
var TTY={ttys:[],init:function () {
1984
// https://github.com/emscripten-core/emscripten/pull/1555
1985
// if (ENVIRONMENT_IS_NODE) {
1986
// // currently, FS.init does not distinguish if process.stdin is a file or TTY
1987
// // device, it always assumes it's a TTY device. because of this, we're forcing
1988
// // process.stdin to UTF8 encoding to at least make stdin reading compatible
1989
// // with text files until FS.init can be refactored.
1990
// process['stdin']['setEncoding']('utf8');
1991
// }
1992
},shutdown:function() {
1993
// https://github.com/emscripten-core/emscripten/pull/1555
1994
// if (ENVIRONMENT_IS_NODE) {
1995
// // inolen: any idea as to why node -e 'process.stdin.read()' wouldn't exit immediately (with process.stdin being a tty)?
1996
// // isaacs: because now it's reading from the stream, you've expressed interest in it, so that read() kicks off a _read() which creates a ReadReq operation
1997
// // inolen: I thought read() in that case was a synchronous operation that just grabbed some amount of buffered data if it exists?
1998
// // isaacs: it is. but it also triggers a _read() call, which calls readStart() on the handle
1999
// // isaacs: do process.stdin.pause() and i'd think it'd probably close the pending call
2000
// process['stdin']['pause']();
2001
// }
2002
},register:function(dev, ops) {
2003
TTY.ttys[dev] = { input: [], output: [], ops: ops };
2004
FS.registerDevice(dev, TTY.stream_ops);
2005
},stream_ops:{open:function(stream) {
2006
var tty = TTY.ttys[stream.node.rdev];
2007
if (!tty) {
2008
throw new FS.ErrnoError(43);
2009
}
2010
stream.tty = tty;
2011
stream.seekable = false;
2012
},close:function(stream) {
2013
// flush any pending line data
2014
stream.tty.ops.flush(stream.tty);
2015
},flush:function(stream) {
2016
stream.tty.ops.flush(stream.tty);
2017
},read:function(stream, buffer, offset, length, pos /* ignored */) {
2018
if (!stream.tty || !stream.tty.ops.get_char) {
2019
throw new FS.ErrnoError(60);
2020
}
2021
var bytesRead = 0;
2022
for (var i = 0; i < length; i++) {
2023
var result;
2024
try {
2025
result = stream.tty.ops.get_char(stream.tty);
2026
} catch (e) {
2027
throw new FS.ErrnoError(29);
2028
}
2029
if (result === undefined && bytesRead === 0) {
2030
throw new FS.ErrnoError(6);
2031
}
2032
if (result === null || result === undefined) break;
2033
bytesRead++;
2034
buffer[offset+i] = result;
2035
}
2036
if (bytesRead) {
2037
stream.node.timestamp = Date.now();
2038
}
2039
return bytesRead;
2040
},write:function(stream, buffer, offset, length, pos) {
2041
if (!stream.tty || !stream.tty.ops.put_char) {
2042
throw new FS.ErrnoError(60);
2043
}
2044
try {
2045
for (var i = 0; i < length; i++) {
2046
stream.tty.ops.put_char(stream.tty, buffer[offset+i]);
2047
}
2048
} catch (e) {
2049
throw new FS.ErrnoError(29);
2050
}
2051
if (length) {
2052
stream.node.timestamp = Date.now();
2053
}
2054
return i;
2055
}},default_tty_ops:{get_char:function(tty) {
2056
if (!tty.input.length) {
2057
var result = null;
2058
if (ENVIRONMENT_IS_NODE) {
2059
// we will read data by chunks of BUFSIZE
2060
var BUFSIZE = 256;
2061
var buf = Buffer.alloc ? Buffer.alloc(BUFSIZE) : new Buffer(BUFSIZE);
2062
var bytesRead = 0;
2063
2064
try {
2065
bytesRead = nodeFS.readSync(process.stdin.fd, buf, 0, BUFSIZE, null);
2066
} catch(e) {
2067
// Cross-platform differences: on Windows, reading EOF throws an exception, but on other OSes,
2068
// reading EOF returns 0. Uniformize behavior by treating the EOF exception to return 0.
2069
if (e.toString().indexOf('EOF') != -1) bytesRead = 0;
2070
else throw e;
2071
}
2072
2073
if (bytesRead > 0) {
2074
result = buf.slice(0, bytesRead).toString('utf-8');
2075
} else {
2076
result = null;
2077
}
2078
} else
2079
if (typeof window != 'undefined' &&
2080
typeof window.prompt == 'function') {
2081
// Browser.
2082
result = window.prompt('Input: '); // returns null on cancel
2083
if (result !== null) {
2084
result += '\n';
2085
}
2086
} else if (typeof readline == 'function') {
2087
// Command line.
2088
result = readline();
2089
if (result !== null) {
2090
result += '\n';
2091
}
2092
}
2093
if (!result) {
2094
return null;
2095
}
2096
tty.input = intArrayFromString(result, true);
2097
}
2098
return tty.input.shift();
2099
},put_char:function(tty, val) {
2100
if (val === null || val === 10) {
2101
out(UTF8ArrayToString(tty.output, 0));
2102
tty.output = [];
2103
} else {
2104
if (val != 0) tty.output.push(val); // val == 0 would cut text output off in the middle.
2105
}
2106
},flush:function(tty) {
2107
if (tty.output && tty.output.length > 0) {
2108
out(UTF8ArrayToString(tty.output, 0));
2109
tty.output = [];
2110
}
2111
}},default_tty1_ops:{put_char:function(tty, val) {
2112
if (val === null || val === 10) {
2113
err(UTF8ArrayToString(tty.output, 0));
2114
tty.output = [];
2115
} else {
2116
if (val != 0) tty.output.push(val);
2117
}
2118
},flush:function(tty) {
2119
if (tty.output && tty.output.length > 0) {
2120
err(UTF8ArrayToString(tty.output, 0));
2121
tty.output = [];
2122
}
2123
}}};
2124
2125
var MEMFS={ops_table:null,mount:function(mount) {
2126
return MEMFS.createNode(null, '/', 16384 | 511 /* 0777 */, 0);
2127
},createNode:function(parent, name, mode, dev) {
2128
if (FS.isBlkdev(mode) || FS.isFIFO(mode)) {
2129
// no supported
2130
throw new FS.ErrnoError(63);
2131
}
2132
if (!MEMFS.ops_table) {
2133
MEMFS.ops_table = {
2134
dir: {
2135
node: {
2136
getattr: MEMFS.node_ops.getattr,
2137
setattr: MEMFS.node_ops.setattr,
2138
lookup: MEMFS.node_ops.lookup,
2139
mknod: MEMFS.node_ops.mknod,
2140
rename: MEMFS.node_ops.rename,
2141
unlink: MEMFS.node_ops.unlink,
2142
rmdir: MEMFS.node_ops.rmdir,
2143
readdir: MEMFS.node_ops.readdir,
2144
symlink: MEMFS.node_ops.symlink
2145
},
2146
stream: {
2147
llseek: MEMFS.stream_ops.llseek
2148
}
2149
},
2150
file: {
2151
node: {
2152
getattr: MEMFS.node_ops.getattr,
2153
setattr: MEMFS.node_ops.setattr
2154
},
2155
stream: {
2156
llseek: MEMFS.stream_ops.llseek,
2157
read: MEMFS.stream_ops.read,
2158
write: MEMFS.stream_ops.write,
2159
allocate: MEMFS.stream_ops.allocate,
2160
mmap: MEMFS.stream_ops.mmap,
2161
msync: MEMFS.stream_ops.msync
2162
}
2163
},
2164
link: {
2165
node: {
2166
getattr: MEMFS.node_ops.getattr,
2167
setattr: MEMFS.node_ops.setattr,
2168
readlink: MEMFS.node_ops.readlink
2169
},
2170
stream: {}
2171
},
2172
chrdev: {
2173
node: {
2174
getattr: MEMFS.node_ops.getattr,
2175
setattr: MEMFS.node_ops.setattr
2176
},
2177
stream: FS.chrdev_stream_ops
2178
}
2179
};
2180
}
2181
var node = FS.createNode(parent, name, mode, dev);
2182
if (FS.isDir(node.mode)) {
2183
node.node_ops = MEMFS.ops_table.dir.node;
2184
node.stream_ops = MEMFS.ops_table.dir.stream;
2185
node.contents = {};
2186
} else if (FS.isFile(node.mode)) {
2187
node.node_ops = MEMFS.ops_table.file.node;
2188
node.stream_ops = MEMFS.ops_table.file.stream;
2189
node.usedBytes = 0; // The actual number of bytes used in the typed array, as opposed to contents.length which gives the whole capacity.
2190
// When the byte data of the file is populated, this will point to either a typed array, or a normal JS array. Typed arrays are preferred
2191
// for performance, and used by default. However, typed arrays are not resizable like normal JS arrays are, so there is a small disk size
2192
// penalty involved for appending file writes that continuously grow a file similar to std::vector capacity vs used -scheme.
2193
node.contents = null;
2194
} else if (FS.isLink(node.mode)) {
2195
node.node_ops = MEMFS.ops_table.link.node;
2196
node.stream_ops = MEMFS.ops_table.link.stream;
2197
} else if (FS.isChrdev(node.mode)) {
2198
node.node_ops = MEMFS.ops_table.chrdev.node;
2199
node.stream_ops = MEMFS.ops_table.chrdev.stream;
2200
}
2201
node.timestamp = Date.now();
2202
// add the new node to the parent
2203
if (parent) {
2204
parent.contents[name] = node;
2205
}
2206
return node;
2207
},getFileDataAsRegularArray:function(node) {
2208
if (node.contents && node.contents.subarray) {
2209
var arr = [];
2210
for (var i = 0; i < node.usedBytes; ++i) arr.push(node.contents[i]);
2211
return arr; // Returns a copy of the original data.
2212
}
2213
return node.contents; // No-op, the file contents are already in a JS array. Return as-is.
2214
},getFileDataAsTypedArray:function(node) {
2215
if (!node.contents) return new Uint8Array(0);
2216
if (node.contents.subarray) return node.contents.subarray(0, node.usedBytes); // Make sure to not return excess unused bytes.
2217
return new Uint8Array(node.contents);
2218
},expandFileStorage:function(node, newCapacity) {
2219
var prevCapacity = node.contents ? node.contents.length : 0;
2220
if (prevCapacity >= newCapacity) return; // No need to expand, the storage was already large enough.
2221
// Don't expand strictly to the given requested limit if it's only a very small increase, but instead geometrically grow capacity.
2222
// For small filesizes (<1MB), perform size*2 geometric increase, but for large sizes, do a much more conservative size*1.125 increase to
2223
// avoid overshooting the allocation cap by a very large margin.
2224
var CAPACITY_DOUBLING_MAX = 1024 * 1024;
2225
newCapacity = Math.max(newCapacity, (prevCapacity * (prevCapacity < CAPACITY_DOUBLING_MAX ? 2.0 : 1.125)) | 0);
2226
if (prevCapacity != 0) newCapacity = Math.max(newCapacity, 256); // At minimum allocate 256b for each file when expanding.
2227
var oldContents = node.contents;
2228
node.contents = new Uint8Array(newCapacity); // Allocate new storage.
2229
if (node.usedBytes > 0) node.contents.set(oldContents.subarray(0, node.usedBytes), 0); // Copy old data over to the new storage.
2230
return;
2231
},resizeFileStorage:function(node, newSize) {
2232
if (node.usedBytes == newSize) return;
2233
if (newSize == 0) {
2234
node.contents = null; // Fully decommit when requesting a resize to zero.
2235
node.usedBytes = 0;
2236
return;
2237
}
2238
if (!node.contents || node.contents.subarray) { // Resize a typed array if that is being used as the backing store.
2239
var oldContents = node.contents;
2240
node.contents = new Uint8Array(newSize); // Allocate new storage.
2241
if (oldContents) {
2242
node.contents.set(oldContents.subarray(0, Math.min(newSize, node.usedBytes))); // Copy old data over to the new storage.
2243
}
2244
node.usedBytes = newSize;
2245
return;
2246
}
2247
// Backing with a JS array.
2248
if (!node.contents) node.contents = [];
2249
if (node.contents.length > newSize) node.contents.length = newSize;
2250
else while (node.contents.length < newSize) node.contents.push(0);
2251
node.usedBytes = newSize;
2252
},node_ops:{getattr:function(node) {
2253
var attr = {};
2254
// device numbers reuse inode numbers.
2255
attr.dev = FS.isChrdev(node.mode) ? node.id : 1;
2256
attr.ino = node.id;
2257
attr.mode = node.mode;
2258
attr.nlink = 1;
2259
attr.uid = 0;
2260
attr.gid = 0;
2261
attr.rdev = node.rdev;
2262
if (FS.isDir(node.mode)) {
2263
attr.size = 4096;
2264
} else if (FS.isFile(node.mode)) {
2265
attr.size = node.usedBytes;
2266
} else if (FS.isLink(node.mode)) {
2267
attr.size = node.link.length;
2268
} else {
2269
attr.size = 0;
2270
}
2271
attr.atime = new Date(node.timestamp);
2272
attr.mtime = new Date(node.timestamp);
2273
attr.ctime = new Date(node.timestamp);
2274
// NOTE: In our implementation, st_blocks = Math.ceil(st_size/st_blksize),
2275
// but this is not required by the standard.
2276
attr.blksize = 4096;
2277
attr.blocks = Math.ceil(attr.size / attr.blksize);
2278
return attr;
2279
},setattr:function(node, attr) {
2280
if (attr.mode !== undefined) {
2281
node.mode = attr.mode;
2282
}
2283
if (attr.timestamp !== undefined) {
2284
node.timestamp = attr.timestamp;
2285
}
2286
if (attr.size !== undefined) {
2287
MEMFS.resizeFileStorage(node, attr.size);
2288
}
2289
},lookup:function(parent, name) {
2290
throw FS.genericErrors[44];
2291
},mknod:function(parent, name, mode, dev) {
2292
return MEMFS.createNode(parent, name, mode, dev);
2293
},rename:function(old_node, new_dir, new_name) {
2294
// if we're overwriting a directory at new_name, make sure it's empty.
2295
if (FS.isDir(old_node.mode)) {
2296
var new_node;
2297
try {
2298
new_node = FS.lookupNode(new_dir, new_name);
2299
} catch (e) {
2300
}
2301
if (new_node) {
2302
for (var i in new_node.contents) {
2303
throw new FS.ErrnoError(55);
2304
}
2305
}
2306
}
2307
// do the internal rewiring
2308
delete old_node.parent.contents[old_node.name];
2309
old_node.name = new_name;
2310
new_dir.contents[new_name] = old_node;
2311
old_node.parent = new_dir;
2312
},unlink:function(parent, name) {
2313
delete parent.contents[name];
2314
},rmdir:function(parent, name) {
2315
var node = FS.lookupNode(parent, name);
2316
for (var i in node.contents) {
2317
throw new FS.ErrnoError(55);
2318
}
2319
delete parent.contents[name];
2320
},readdir:function(node) {
2321
var entries = ['.', '..'];
2322
for (var key in node.contents) {
2323
if (!node.contents.hasOwnProperty(key)) {
2324
continue;
2325
}
2326
entries.push(key);
2327
}
2328
return entries;
2329
},symlink:function(parent, newname, oldpath) {
2330
var node = MEMFS.createNode(parent, newname, 511 /* 0777 */ | 40960, 0);
2331
node.link = oldpath;
2332
return node;
2333
},readlink:function(node) {
2334
if (!FS.isLink(node.mode)) {
2335
throw new FS.ErrnoError(28);
2336
}
2337
return node.link;
2338
}},stream_ops:{read:function(stream, buffer, offset, length, position) {
2339
var contents = stream.node.contents;
2340
if (position >= stream.node.usedBytes) return 0;
2341
var size = Math.min(stream.node.usedBytes - position, length);
2342
assert(size >= 0);
2343
if (size > 8 && contents.subarray) { // non-trivial, and typed array
2344
buffer.set(contents.subarray(position, position + size), offset);
2345
} else {
2346
for (var i = 0; i < size; i++) buffer[offset + i] = contents[position + i];
2347
}
2348
return size;
2349
},write:function(stream, buffer, offset, length, position, canOwn) {
2350
// The data buffer should be a typed array view
2351
assert(!(buffer instanceof ArrayBuffer));
2352
2353
if (!length) return 0;
2354
var node = stream.node;
2355
node.timestamp = Date.now();
2356
2357
if (buffer.subarray && (!node.contents || node.contents.subarray)) { // This write is from a typed array to a typed array?
2358
if (canOwn) {
2359
assert(position === 0, 'canOwn must imply no weird position inside the file');
2360
node.contents = buffer.subarray(offset, offset + length);
2361
node.usedBytes = length;
2362
return length;
2363
} else if (node.usedBytes === 0 && position === 0) { // If this is a simple first write to an empty file, do a fast set since we don't need to care about old data.
2364
node.contents = buffer.slice(offset, offset + length);
2365
node.usedBytes = length;
2366
return length;
2367
} else if (position + length <= node.usedBytes) { // Writing to an already allocated and used subrange of the file?
2368
node.contents.set(buffer.subarray(offset, offset + length), position);
2369
return length;
2370
}
2371
}
2372
2373
// Appending to an existing file and we need to reallocate, or source data did not come as a typed array.
2374
MEMFS.expandFileStorage(node, position+length);
2375
if (node.contents.subarray && buffer.subarray) node.contents.set(buffer.subarray(offset, offset + length), position); // Use typed array write if available.
2376
else {
2377
for (var i = 0; i < length; i++) {
2378
node.contents[position + i] = buffer[offset + i]; // Or fall back to manual write if not.
2379
}
2380
}
2381
node.usedBytes = Math.max(node.usedBytes, position+length);
2382
return length;
2383
},llseek:function(stream, offset, whence) {
2384
var position = offset;
2385
if (whence === 1) {
2386
position += stream.position;
2387
} else if (whence === 2) {
2388
if (FS.isFile(stream.node.mode)) {
2389
position += stream.node.usedBytes;
2390
}
2391
}
2392
if (position < 0) {
2393
throw new FS.ErrnoError(28);
2394
}
2395
return position;
2396
},allocate:function(stream, offset, length) {
2397
MEMFS.expandFileStorage(stream.node, offset + length);
2398
stream.node.usedBytes = Math.max(stream.node.usedBytes, offset + length);
2399
},mmap:function(stream, buffer, offset, length, position, prot, flags) {
2400
// The data buffer should be a typed array view
2401
assert(!(buffer instanceof ArrayBuffer));
2402
if (!FS.isFile(stream.node.mode)) {
2403
throw new FS.ErrnoError(43);
2404
}
2405
var ptr;
2406
var allocated;
2407
var contents = stream.node.contents;
2408
// Only make a new copy when MAP_PRIVATE is specified.
2409
if ( !(flags & 2) &&
2410
contents.buffer === buffer.buffer ) {
2411
// We can't emulate MAP_SHARED when the file is not backed by the buffer
2412
// we're mapping to (e.g. the HEAP buffer).
2413
allocated = false;
2414
ptr = contents.byteOffset;
2415
} else {
2416
// Try to avoid unnecessary slices.
2417
if (position > 0 || position + length < contents.length) {
2418
if (contents.subarray) {
2419
contents = contents.subarray(position, position + length);
2420
} else {
2421
contents = Array.prototype.slice.call(contents, position, position + length);
2422
}
2423
}
2424
allocated = true;
2425
// malloc() can lead to growing the heap. If targeting the heap, we need to
2426
// re-acquire the heap buffer object in case growth had occurred.
2427
var fromHeap = (buffer.buffer == HEAP8.buffer);
2428
ptr = _malloc(length);
2429
if (!ptr) {
2430
throw new FS.ErrnoError(48);
2431
}
2432
(fromHeap ? HEAP8 : buffer).set(contents, ptr);
2433
}
2434
return { ptr: ptr, allocated: allocated };
2435
},msync:function(stream, buffer, offset, length, mmapFlags) {
2436
if (!FS.isFile(stream.node.mode)) {
2437
throw new FS.ErrnoError(43);
2438
}
2439
if (mmapFlags & 2) {
2440
// MAP_PRIVATE calls need not to be synced back to underlying fs
2441
return 0;
2442
}
2443
2444
var bytesWritten = MEMFS.stream_ops.write(stream, buffer, 0, length, offset, false);
2445
// should we check if bytesWritten and length are the same?
2446
return 0;
2447
}}};
2448
2449
var ERRNO_MESSAGES={0:"Success",1:"Arg list too long",2:"Permission denied",3:"Address already in use",4:"Address not available",5:"Address family not supported by protocol family",6:"No more processes",7:"Socket already connected",8:"Bad file number",9:"Trying to read unreadable message",10:"Mount device busy",11:"Operation canceled",12:"No children",13:"Connection aborted",14:"Connection refused",15:"Connection reset by peer",16:"File locking deadlock error",17:"Destination address required",18:"Math arg out of domain of func",19:"Quota exceeded",20:"File exists",21:"Bad address",22:"File too large",23:"Host is unreachable",24:"Identifier removed",25:"Illegal byte sequence",26:"Connection already in progress",27:"Interrupted system call",28:"Invalid argument",29:"I/O error",30:"Socket is already connected",31:"Is a directory",32:"Too many symbolic links",33:"Too many open files",34:"Too many links",35:"Message too long",36:"Multihop attempted",37:"File or path name too long",38:"Network interface is not configured",39:"Connection reset by network",40:"Network is unreachable",41:"Too many open files in system",42:"No buffer space available",43:"No such device",44:"No such file or directory",45:"Exec format error",46:"No record locks available",47:"The link has been severed",48:"Not enough core",49:"No message of desired type",50:"Protocol not available",51:"No space left on device",52:"Function not implemented",53:"Socket is not connected",54:"Not a directory",55:"Directory not empty",56:"State not recoverable",57:"Socket operation on non-socket",59:"Not a typewriter",60:"No such device or address",61:"Value too large for defined data type",62:"Previous owner died",63:"Not super-user",64:"Broken pipe",65:"Protocol error",66:"Unknown protocol",67:"Protocol wrong type for socket",68:"Math result not representable",69:"Read only file system",70:"Illegal seek",71:"No such process",72:"Stale file handle",73:"Connection timed out",74:"Text file busy",75:"Cross-device link",100:"Device not a stream",101:"Bad font file fmt",102:"Invalid slot",103:"Invalid request code",104:"No anode",105:"Block device required",106:"Channel number out of range",107:"Level 3 halted",108:"Level 3 reset",109:"Link number out of range",110:"Protocol driver not attached",111:"No CSI structure available",112:"Level 2 halted",113:"Invalid exchange",114:"Invalid request descriptor",115:"Exchange full",116:"No data (for no delay io)",117:"Timer expired",118:"Out of streams resources",119:"Machine is not on the network",120:"Package not installed",121:"The object is remote",122:"Advertise error",123:"Srmount error",124:"Communication error on send",125:"Cross mount point (not really error)",126:"Given log. name not unique",127:"f.d. invalid for this operation",128:"Remote address changed",129:"Can access a needed shared lib",130:"Accessing a corrupted shared lib",131:".lib section in a.out corrupted",132:"Attempting to link in too many libs",133:"Attempting to exec a shared library",135:"Streams pipe error",136:"Too many users",137:"Socket type not supported",138:"Not supported",139:"Protocol family not supported",140:"Can't send after socket shutdown",141:"Too many references",142:"Host is down",148:"No medium (in tape drive)",156:"Level 2 not synchronized"};
2450
2451
var ERRNO_CODES={EPERM:63,ENOENT:44,ESRCH:71,EINTR:27,EIO:29,ENXIO:60,E2BIG:1,ENOEXEC:45,EBADF:8,ECHILD:12,EAGAIN:6,EWOULDBLOCK:6,ENOMEM:48,EACCES:2,EFAULT:21,ENOTBLK:105,EBUSY:10,EEXIST:20,EXDEV:75,ENODEV:43,ENOTDIR:54,EISDIR:31,EINVAL:28,ENFILE:41,EMFILE:33,ENOTTY:59,ETXTBSY:74,EFBIG:22,ENOSPC:51,ESPIPE:70,EROFS:69,EMLINK:34,EPIPE:64,EDOM:18,ERANGE:68,ENOMSG:49,EIDRM:24,ECHRNG:106,EL2NSYNC:156,EL3HLT:107,EL3RST:108,ELNRNG:109,EUNATCH:110,ENOCSI:111,EL2HLT:112,EDEADLK:16,ENOLCK:46,EBADE:113,EBADR:114,EXFULL:115,ENOANO:104,EBADRQC:103,EBADSLT:102,EDEADLOCK:16,EBFONT:101,ENOSTR:100,ENODATA:116,ETIME:117,ENOSR:118,ENONET:119,ENOPKG:120,EREMOTE:121,ENOLINK:47,EADV:122,ESRMNT:123,ECOMM:124,EPROTO:65,EMULTIHOP:36,EDOTDOT:125,EBADMSG:9,ENOTUNIQ:126,EBADFD:127,EREMCHG:128,ELIBACC:129,ELIBBAD:130,ELIBSCN:131,ELIBMAX:132,ELIBEXEC:133,ENOSYS:52,ENOTEMPTY:55,ENAMETOOLONG:37,ELOOP:32,EOPNOTSUPP:138,EPFNOSUPPORT:139,ECONNRESET:15,ENOBUFS:42,EAFNOSUPPORT:5,EPROTOTYPE:67,ENOTSOCK:57,ENOPROTOOPT:50,ESHUTDOWN:140,ECONNREFUSED:14,EADDRINUSE:3,ECONNABORTED:13,ENETUNREACH:40,ENETDOWN:38,ETIMEDOUT:73,EHOSTDOWN:142,EHOSTUNREACH:23,EINPROGRESS:26,EALREADY:7,EDESTADDRREQ:17,EMSGSIZE:35,EPROTONOSUPPORT:66,ESOCKTNOSUPPORT:137,EADDRNOTAVAIL:4,ENETRESET:39,EISCONN:30,ENOTCONN:53,ETOOMANYREFS:141,EUSERS:136,EDQUOT:19,ESTALE:72,ENOTSUP:138,ENOMEDIUM:148,EILSEQ:25,EOVERFLOW:61,ECANCELED:11,ENOTRECOVERABLE:56,EOWNERDEAD:62,ESTRPIPE:135};var FS={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:false,ignorePermissions:true,trackingDelegate:{},tracking:{openFlags:{READ:1,WRITE:2}},ErrnoError:null,genericErrors:{},filesystems:null,syncFSRequests:0,handleFSError:function(e) {
2452
if (!(e instanceof FS.ErrnoError)) throw e + ' : ' + stackTrace();
2453
return ___setErrNo(e.errno);
2454
},lookupPath:function(path, opts) {
2455
path = PATH_FS.resolve(FS.cwd(), path);
2456
opts = opts || {};
2457
2458
if (!path) return { path: '', node: null };
2459
2460
var defaults = {
2461
follow_mount: true,
2462
recurse_count: 0
2463
};
2464
for (var key in defaults) {
2465
if (opts[key] === undefined) {
2466
opts[key] = defaults[key];
2467
}
2468
}
2469
2470
if (opts.recurse_count > 8) { // max recursive lookup of 8
2471
throw new FS.ErrnoError(32);
2472
}
2473
2474
// split the path
2475
var parts = PATH.normalizeArray(path.split('/').filter(function(p) {
2476
return !!p;
2477
}), false);
2478
2479
// start at the root
2480
var current = FS.root;
2481
var current_path = '/';
2482
2483
for (var i = 0; i < parts.length; i++) {
2484
var islast = (i === parts.length-1);
2485
if (islast && opts.parent) {
2486
// stop resolving
2487
break;
2488
}
2489
2490
current = FS.lookupNode(current, parts[i]);
2491
current_path = PATH.join2(current_path, parts[i]);
2492
2493
// jump to the mount's root node if this is a mountpoint
2494
if (FS.isMountpoint(current)) {
2495
if (!islast || (islast && opts.follow_mount)) {
2496
current = current.mounted.root;
2497
}
2498
}
2499
2500
// by default, lookupPath will not follow a symlink if it is the final path component.
2501
// setting opts.follow = true will override this behavior.
2502
if (!islast || opts.follow) {
2503
var count = 0;
2504
while (FS.isLink(current.mode)) {
2505
var link = FS.readlink(current_path);
2506
current_path = PATH_FS.resolve(PATH.dirname(current_path), link);
2507
2508
var lookup = FS.lookupPath(current_path, { recurse_count: opts.recurse_count });
2509
current = lookup.node;
2510
2511
if (count++ > 40) { // limit max consecutive symlinks to 40 (SYMLOOP_MAX).
2512
throw new FS.ErrnoError(32);
2513
}
2514
}
2515
}
2516
}
2517
2518
return { path: current_path, node: current };
2519
},getPath:function(node) {
2520
var path;
2521
while (true) {
2522
if (FS.isRoot(node)) {
2523
var mount = node.mount.mountpoint;
2524
if (!path) return mount;
2525
return mount[mount.length-1] !== '/' ? mount + '/' + path : mount + path;
2526
}
2527
path = path ? node.name + '/' + path : node.name;
2528
node = node.parent;
2529
}
2530
},hashName:function(parentid, name) {
2531
var hash = 0;
2532
2533
2534
for (var i = 0; i < name.length; i++) {
2535
hash = ((hash << 5) - hash + name.charCodeAt(i)) | 0;
2536
}
2537
return ((parentid + hash) >>> 0) % FS.nameTable.length;
2538
},hashAddNode:function(node) {
2539
var hash = FS.hashName(node.parent.id, node.name);
2540
node.name_next = FS.nameTable[hash];
2541
FS.nameTable[hash] = node;
2542
},hashRemoveNode:function(node) {
2543
var hash = FS.hashName(node.parent.id, node.name);
2544
if (FS.nameTable[hash] === node) {
2545
FS.nameTable[hash] = node.name_next;
2546
} else {
2547
var current = FS.nameTable[hash];
2548
while (current) {
2549
if (current.name_next === node) {
2550
current.name_next = node.name_next;
2551
break;
2552
}
2553
current = current.name_next;
2554
}
2555
}
2556
},lookupNode:function(parent, name) {
2557
var errCode = FS.mayLookup(parent);
2558
if (errCode) {
2559
throw new FS.ErrnoError(errCode, parent);
2560
}
2561
var hash = FS.hashName(parent.id, name);
2562
for (var node = FS.nameTable[hash]; node; node = node.name_next) {
2563
var nodeName = node.name;
2564
if (node.parent.id === parent.id && nodeName === name) {
2565
return node;
2566
}
2567
}
2568
// if we failed to find it in the cache, call into the VFS
2569
return FS.lookup(parent, name);
2570
},createNode:function(parent, name, mode, rdev) {
2571
var node = new FS.FSNode(parent, name, mode, rdev);
2572
2573
FS.hashAddNode(node);
2574
2575
return node;
2576
},destroyNode:function(node) {
2577
FS.hashRemoveNode(node);
2578
},isRoot:function(node) {
2579
return node === node.parent;
2580
},isMountpoint:function(node) {
2581
return !!node.mounted;
2582
},isFile:function(mode) {
2583
return (mode & 61440) === 32768;
2584
},isDir:function(mode) {
2585
return (mode & 61440) === 16384;
2586
},isLink:function(mode) {
2587
return (mode & 61440) === 40960;
2588
},isChrdev:function(mode) {
2589
return (mode & 61440) === 8192;
2590
},isBlkdev:function(mode) {
2591
return (mode & 61440) === 24576;
2592
},isFIFO:function(mode) {
2593
return (mode & 61440) === 4096;
2594
},isSocket:function(mode) {
2595
return (mode & 49152) === 49152;
2596
},flagModes:{"r":0,"rs":1052672,"r+":2,"w":577,"wx":705,"xw":705,"w+":578,"wx+":706,"xw+":706,"a":1089,"ax":1217,"xa":1217,"a+":1090,"ax+":1218,"xa+":1218},modeStringToFlags:function(str) {
2597
var flags = FS.flagModes[str];
2598
if (typeof flags === 'undefined') {
2599
throw new Error('Unknown file open mode: ' + str);
2600
}
2601
return flags;
2602
},flagsToPermissionString:function(flag) {
2603
var perms = ['r', 'w', 'rw'][flag & 3];
2604
if ((flag & 512)) {
2605
perms += 'w';
2606
}
2607
return perms;
2608
},nodePermissions:function(node, perms) {
2609
if (FS.ignorePermissions) {
2610
return 0;
2611
}
2612
// return 0 if any user, group or owner bits are set.
2613
if (perms.indexOf('r') !== -1 && !(node.mode & 292)) {
2614
return 2;
2615
} else if (perms.indexOf('w') !== -1 && !(node.mode & 146)) {
2616
return 2;
2617
} else if (perms.indexOf('x') !== -1 && !(node.mode & 73)) {
2618
return 2;
2619
}
2620
return 0;
2621
},mayLookup:function(dir) {
2622
var errCode = FS.nodePermissions(dir, 'x');
2623
if (errCode) return errCode;
2624
if (!dir.node_ops.lookup) return 2;
2625
return 0;
2626
},mayCreate:function(dir, name) {
2627
try {
2628
var node = FS.lookupNode(dir, name);
2629
return 20;
2630
} catch (e) {
2631
}
2632
return FS.nodePermissions(dir, 'wx');
2633
},mayDelete:function(dir, name, isdir) {
2634
var node;
2635
try {
2636
node = FS.lookupNode(dir, name);
2637
} catch (e) {
2638
return e.errno;
2639
}
2640
var errCode = FS.nodePermissions(dir, 'wx');
2641
if (errCode) {
2642
return errCode;
2643
}
2644
if (isdir) {
2645
if (!FS.isDir(node.mode)) {
2646
return 54;
2647
}
2648
if (FS.isRoot(node) || FS.getPath(node) === FS.cwd()) {
2649
return 10;
2650
}
2651
} else {
2652
if (FS.isDir(node.mode)) {
2653
return 31;
2654
}
2655
}
2656
return 0;
2657
},mayOpen:function(node, flags) {
2658
if (!node) {
2659
return 44;
2660
}
2661
if (FS.isLink(node.mode)) {
2662
return 32;
2663
} else if (FS.isDir(node.mode)) {
2664
if (FS.flagsToPermissionString(flags) !== 'r' || // opening for write
2665
(flags & 512)) { // TODO: check for O_SEARCH? (== search for dir only)
2666
return 31;
2667
}
2668
}
2669
return FS.nodePermissions(node, FS.flagsToPermissionString(flags));
2670
},MAX_OPEN_FDS:4096,nextfd:function(fd_start, fd_end) {
2671
fd_start = fd_start || 0;
2672
fd_end = fd_end || FS.MAX_OPEN_FDS;
2673
for (var fd = fd_start; fd <= fd_end; fd++) {
2674
if (!FS.streams[fd]) {
2675
return fd;
2676
}
2677
}
2678
throw new FS.ErrnoError(33);
2679
},getStream:function(fd) {
2680
return FS.streams[fd];
2681
},createStream:function(stream, fd_start, fd_end) {
2682
if (!FS.FSStream) {
2683
FS.FSStream = /** @constructor */ function(){};
2684
FS.FSStream.prototype = {
2685
object: {
2686
get: function() { return this.node; },
2687
set: function(val) { this.node = val; }
2688
},
2689
isRead: {
2690
get: function() { return (this.flags & 2097155) !== 1; }
2691
},
2692
isWrite: {
2693
get: function() { return (this.flags & 2097155) !== 0; }
2694
},
2695
isAppend: {
2696
get: function() { return (this.flags & 1024); }
2697
}
2698
};
2699
}
2700
// clone it, so we can return an instance of FSStream
2701
var newStream = new FS.FSStream();
2702
for (var p in stream) {
2703
newStream[p] = stream[p];
2704
}
2705
stream = newStream;
2706
var fd = FS.nextfd(fd_start, fd_end);
2707
stream.fd = fd;
2708
FS.streams[fd] = stream;
2709
return stream;
2710
},closeStream:function(fd) {
2711
FS.streams[fd] = null;
2712
},chrdev_stream_ops:{open:function(stream) {
2713
var device = FS.getDevice(stream.node.rdev);
2714
// override node's stream ops with the device's
2715
stream.stream_ops = device.stream_ops;
2716
// forward the open call
2717
if (stream.stream_ops.open) {
2718
stream.stream_ops.open(stream);
2719
}
2720
},llseek:function() {
2721
throw new FS.ErrnoError(70);
2722
}},major:function(dev) {
2723
return ((dev) >> 8);
2724
},minor:function(dev) {
2725
return ((dev) & 0xff);
2726
},makedev:function(ma, mi) {
2727
return ((ma) << 8 | (mi));
2728
},registerDevice:function(dev, ops) {
2729
FS.devices[dev] = { stream_ops: ops };
2730
},getDevice:function(dev) {
2731
return FS.devices[dev];
2732
},getMounts:function(mount) {
2733
var mounts = [];
2734
var check = [mount];
2735
2736
while (check.length) {
2737
var m = check.pop();
2738
2739
mounts.push(m);
2740
2741
check.push.apply(check, m.mounts);
2742
}
2743
2744
return mounts;
2745
},syncfs:function(populate, callback) {
2746
if (typeof(populate) === 'function') {
2747
callback = populate;
2748
populate = false;
2749
}
2750
2751
FS.syncFSRequests++;
2752
2753
if (FS.syncFSRequests > 1) {
2754
err('warning: ' + FS.syncFSRequests + ' FS.syncfs operations in flight at once, probably just doing extra work');
2755
}
2756
2757
var mounts = FS.getMounts(FS.root.mount);
2758
var completed = 0;
2759
2760
function doCallback(errCode) {
2761
assert(FS.syncFSRequests > 0);
2762
FS.syncFSRequests--;
2763
return callback(errCode);
2764
}
2765
2766
function done(errCode) {
2767
if (errCode) {
2768
if (!done.errored) {
2769
done.errored = true;
2770
return doCallback(errCode);
2771
}
2772
return;
2773
}
2774
if (++completed >= mounts.length) {
2775
doCallback(null);
2776
}
2777
};
2778
2779
// sync all mounts
2780
mounts.forEach(function (mount) {
2781
if (!mount.type.syncfs) {
2782
return done(null);
2783
}
2784
mount.type.syncfs(mount, populate, done);
2785
});
2786
},mount:function(type, opts, mountpoint) {
2787
if (typeof type === 'string') {
2788
// The filesystem was not included, and instead we have an error
2789
// message stored in the variable.
2790
throw type;
2791
}
2792
var root = mountpoint === '/';
2793
var pseudo = !mountpoint;
2794
var node;
2795
2796
if (root && FS.root) {
2797
throw new FS.ErrnoError(10);
2798
} else if (!root && !pseudo) {
2799
var lookup = FS.lookupPath(mountpoint, { follow_mount: false });
2800
2801
mountpoint = lookup.path; // use the absolute path
2802
node = lookup.node;
2803
2804
if (FS.isMountpoint(node)) {
2805
throw new FS.ErrnoError(10);
2806
}
2807
2808
if (!FS.isDir(node.mode)) {
2809
throw new FS.ErrnoError(54);
2810
}
2811
}
2812
2813
var mount = {
2814
type: type,
2815
opts: opts,
2816
mountpoint: mountpoint,
2817
mounts: []
2818
};
2819
2820
// create a root node for the fs
2821
var mountRoot = type.mount(mount);
2822
mountRoot.mount = mount;
2823
mount.root = mountRoot;
2824
2825
if (root) {
2826
FS.root = mountRoot;
2827
} else if (node) {
2828
// set as a mountpoint
2829
node.mounted = mount;
2830
2831
// add the new mount to the current mount's children
2832
if (node.mount) {
2833
node.mount.mounts.push(mount);
2834
}
2835
}
2836
2837
return mountRoot;
2838
},unmount:function (mountpoint) {
2839
var lookup = FS.lookupPath(mountpoint, { follow_mount: false });
2840
2841
if (!FS.isMountpoint(lookup.node)) {
2842
throw new FS.ErrnoError(28);
2843
}
2844
2845
// destroy the nodes for this mount, and all its child mounts
2846
var node = lookup.node;
2847
var mount = node.mounted;
2848
var mounts = FS.getMounts(mount);
2849
2850
Object.keys(FS.nameTable).forEach(function (hash) {
2851
var current = FS.nameTable[hash];
2852
2853
while (current) {
2854
var next = current.name_next;
2855
2856
if (mounts.indexOf(current.mount) !== -1) {
2857
FS.destroyNode(current);
2858
}
2859
2860
current = next;
2861
}
2862
});
2863
2864
// no longer a mountpoint
2865
node.mounted = null;
2866
2867
// remove this mount from the child mounts
2868
var idx = node.mount.mounts.indexOf(mount);
2869
assert(idx !== -1);
2870
node.mount.mounts.splice(idx, 1);
2871
},lookup:function(parent, name) {
2872
return parent.node_ops.lookup(parent, name);
2873
},mknod:function(path, mode, dev) {
2874
var lookup = FS.lookupPath(path, { parent: true });
2875
var parent = lookup.node;
2876
var name = PATH.basename(path);
2877
if (!name || name === '.' || name === '..') {
2878
throw new FS.ErrnoError(28);
2879
}
2880
var errCode = FS.mayCreate(parent, name);
2881
if (errCode) {
2882
throw new FS.ErrnoError(errCode);
2883
}
2884
if (!parent.node_ops.mknod) {
2885
throw new FS.ErrnoError(63);
2886
}
2887
return parent.node_ops.mknod(parent, name, mode, dev);
2888
},create:function(path, mode) {
2889
mode = mode !== undefined ? mode : 438 /* 0666 */;
2890
mode &= 4095;
2891
mode |= 32768;
2892
return FS.mknod(path, mode, 0);
2893
},mkdir:function(path, mode) {
2894
mode = mode !== undefined ? mode : 511 /* 0777 */;
2895
mode &= 511 | 512;
2896
mode |= 16384;
2897
return FS.mknod(path, mode, 0);
2898
},mkdirTree:function(path, mode) {
2899
var dirs = path.split('/');
2900
var d = '';
2901
for (var i = 0; i < dirs.length; ++i) {
2902
if (!dirs[i]) continue;
2903
d += '/' + dirs[i];
2904
try {
2905
FS.mkdir(d, mode);
2906
} catch(e) {
2907
if (e.errno != 20) throw e;
2908
}
2909
}
2910
},mkdev:function(path, mode, dev) {
2911
if (typeof(dev) === 'undefined') {
2912
dev = mode;
2913
mode = 438 /* 0666 */;
2914
}
2915
mode |= 8192;
2916
return FS.mknod(path, mode, dev);
2917
},symlink:function(oldpath, newpath) {
2918
if (!PATH_FS.resolve(oldpath)) {
2919
throw new FS.ErrnoError(44);
2920
}
2921
var lookup = FS.lookupPath(newpath, { parent: true });
2922
var parent = lookup.node;
2923
if (!parent) {
2924
throw new FS.ErrnoError(44);
2925
}
2926
var newname = PATH.basename(newpath);
2927
var errCode = FS.mayCreate(parent, newname);
2928
if (errCode) {
2929
throw new FS.ErrnoError(errCode);
2930
}
2931
if (!parent.node_ops.symlink) {
2932
throw new FS.ErrnoError(63);
2933
}
2934
return parent.node_ops.symlink(parent, newname, oldpath);
2935
},rename:function(old_path, new_path) {
2936
var old_dirname = PATH.dirname(old_path);
2937
var new_dirname = PATH.dirname(new_path);
2938
var old_name = PATH.basename(old_path);
2939
var new_name = PATH.basename(new_path);
2940
// parents must exist
2941
var lookup, old_dir, new_dir;
2942
try {
2943
lookup = FS.lookupPath(old_path, { parent: true });
2944
old_dir = lookup.node;
2945
lookup = FS.lookupPath(new_path, { parent: true });
2946
new_dir = lookup.node;
2947
} catch (e) {
2948
throw new FS.ErrnoError(10);
2949
}
2950
if (!old_dir || !new_dir) throw new FS.ErrnoError(44);
2951
// need to be part of the same mount
2952
if (old_dir.mount !== new_dir.mount) {
2953
throw new FS.ErrnoError(75);
2954
}
2955
// source must exist
2956
var old_node = FS.lookupNode(old_dir, old_name);
2957
// old path should not be an ancestor of the new path
2958
var relative = PATH_FS.relative(old_path, new_dirname);
2959
if (relative.charAt(0) !== '.') {
2960
throw new FS.ErrnoError(28);
2961
}
2962
// new path should not be an ancestor of the old path
2963
relative = PATH_FS.relative(new_path, old_dirname);
2964
if (relative.charAt(0) !== '.') {
2965
throw new FS.ErrnoError(55);
2966
}
2967
// see if the new path already exists
2968
var new_node;
2969
try {
2970
new_node = FS.lookupNode(new_dir, new_name);
2971
} catch (e) {
2972
// not fatal
2973
}
2974
// early out if nothing needs to change
2975
if (old_node === new_node) {
2976
return;
2977
}
2978
// we'll need to delete the old entry
2979
var isdir = FS.isDir(old_node.mode);
2980
var errCode = FS.mayDelete(old_dir, old_name, isdir);
2981
if (errCode) {
2982
throw new FS.ErrnoError(errCode);
2983
}
2984
// need delete permissions if we'll be overwriting.
2985
// need create permissions if new doesn't already exist.
2986
errCode = new_node ?
2987
FS.mayDelete(new_dir, new_name, isdir) :
2988
FS.mayCreate(new_dir, new_name);
2989
if (errCode) {
2990
throw new FS.ErrnoError(errCode);
2991
}
2992
if (!old_dir.node_ops.rename) {
2993
throw new FS.ErrnoError(63);
2994
}
2995
if (FS.isMountpoint(old_node) || (new_node && FS.isMountpoint(new_node))) {
2996
throw new FS.ErrnoError(10);
2997
}
2998
// if we are going to change the parent, check write permissions
2999
if (new_dir !== old_dir) {
3000
errCode = FS.nodePermissions(old_dir, 'w');
3001
if (errCode) {
3002
throw new FS.ErrnoError(errCode);
3003
}
3004
}
3005
try {
3006
if (FS.trackingDelegate['willMovePath']) {
3007
FS.trackingDelegate['willMovePath'](old_path, new_path);
3008
}
3009
} catch(e) {
3010
err("FS.trackingDelegate['willMovePath']('"+old_path+"', '"+new_path+"') threw an exception: " + e.message);
3011
}
3012
// remove the node from the lookup hash
3013
FS.hashRemoveNode(old_node);
3014
// do the underlying fs rename
3015
try {
3016
old_dir.node_ops.rename(old_node, new_dir, new_name);
3017
} catch (e) {
3018
throw e;
3019
} finally {
3020
// add the node back to the hash (in case node_ops.rename
3021
// changed its name)
3022
FS.hashAddNode(old_node);
3023
}
3024
try {
3025
if (FS.trackingDelegate['onMovePath']) FS.trackingDelegate['onMovePath'](old_path, new_path);
3026
} catch(e) {
3027
err("FS.trackingDelegate['onMovePath']('"+old_path+"', '"+new_path+"') threw an exception: " + e.message);
3028
}
3029
},rmdir:function(path) {
3030
var lookup = FS.lookupPath(path, { parent: true });
3031
var parent = lookup.node;
3032
var name = PATH.basename(path);
3033
var node = FS.lookupNode(parent, name);
3034
var errCode = FS.mayDelete(parent, name, true);
3035
if (errCode) {
3036
throw new FS.ErrnoError(errCode);
3037
}
3038
if (!parent.node_ops.rmdir) {
3039
throw new FS.ErrnoError(63);
3040
}
3041
if (FS.isMountpoint(node)) {
3042
throw new FS.ErrnoError(10);
3043
}
3044
try {
3045
if (FS.trackingDelegate['willDeletePath']) {
3046
FS.trackingDelegate['willDeletePath'](path);
3047
}
3048
} catch(e) {
3049
err("FS.trackingDelegate['willDeletePath']('"+path+"') threw an exception: " + e.message);
3050
}
3051
parent.node_ops.rmdir(parent, name);
3052
FS.destroyNode(node);
3053
try {
3054
if (FS.trackingDelegate['onDeletePath']) FS.trackingDelegate['onDeletePath'](path);
3055
} catch(e) {
3056
err("FS.trackingDelegate['onDeletePath']('"+path+"') threw an exception: " + e.message);
3057
}
3058
},readdir:function(path) {
3059
var lookup = FS.lookupPath(path, { follow: true });
3060
var node = lookup.node;
3061
if (!node.node_ops.readdir) {
3062
throw new FS.ErrnoError(54);
3063
}
3064
return node.node_ops.readdir(node);
3065
},unlink:function(path) {
3066
var lookup = FS.lookupPath(path, { parent: true });
3067
var parent = lookup.node;
3068
var name = PATH.basename(path);
3069
var node = FS.lookupNode(parent, name);
3070
var errCode = FS.mayDelete(parent, name, false);
3071
if (errCode) {
3072
// According to POSIX, we should map EISDIR to EPERM, but
3073
// we instead do what Linux does (and we must, as we use
3074
// the musl linux libc).
3075
throw new FS.ErrnoError(errCode);
3076
}
3077
if (!parent.node_ops.unlink) {
3078
throw new FS.ErrnoError(63);
3079
}
3080
if (FS.isMountpoint(node)) {
3081
throw new FS.ErrnoError(10);
3082
}
3083
try {
3084
if (FS.trackingDelegate['willDeletePath']) {
3085
FS.trackingDelegate['willDeletePath'](path);
3086
}
3087
} catch(e) {
3088
err("FS.trackingDelegate['willDeletePath']('"+path+"') threw an exception: " + e.message);
3089
}
3090
parent.node_ops.unlink(parent, name);
3091
FS.destroyNode(node);
3092
try {
3093
if (FS.trackingDelegate['onDeletePath']) FS.trackingDelegate['onDeletePath'](path);
3094
} catch(e) {
3095
err("FS.trackingDelegate['onDeletePath']('"+path+"') threw an exception: " + e.message);
3096
}
3097
},readlink:function(path) {
3098
var lookup = FS.lookupPath(path);
3099
var link = lookup.node;
3100
if (!link) {
3101
throw new FS.ErrnoError(44);
3102
}
3103
if (!link.node_ops.readlink) {
3104
throw new FS.ErrnoError(28);
3105
}
3106
return PATH_FS.resolve(FS.getPath(link.parent), link.node_ops.readlink(link));
3107
},stat:function(path, dontFollow) {
3108
var lookup = FS.lookupPath(path, { follow: !dontFollow });
3109
var node = lookup.node;
3110
if (!node) {
3111
throw new FS.ErrnoError(44);
3112
}
3113
if (!node.node_ops.getattr) {
3114
throw new FS.ErrnoError(63);
3115
}
3116
return node.node_ops.getattr(node);
3117
},lstat:function(path) {
3118
return FS.stat(path, true);
3119
},chmod:function(path, mode, dontFollow) {
3120
var node;
3121
if (typeof path === 'string') {
3122
var lookup = FS.lookupPath(path, { follow: !dontFollow });
3123
node = lookup.node;
3124
} else {
3125
node = path;
3126
}
3127
if (!node.node_ops.setattr) {
3128
throw new FS.ErrnoError(63);
3129
}
3130
node.node_ops.setattr(node, {
3131
mode: (mode & 4095) | (node.mode & ~4095),
3132
timestamp: Date.now()
3133
});
3134
},lchmod:function(path, mode) {
3135
FS.chmod(path, mode, true);
3136
},fchmod:function(fd, mode) {
3137
var stream = FS.getStream(fd);
3138
if (!stream) {
3139
throw new FS.ErrnoError(8);
3140
}
3141
FS.chmod(stream.node, mode);
3142
},chown:function(path, uid, gid, dontFollow) {
3143
var node;
3144
if (typeof path === 'string') {
3145
var lookup = FS.lookupPath(path, { follow: !dontFollow });
3146
node = lookup.node;
3147
} else {
3148
node = path;
3149
}
3150
if (!node.node_ops.setattr) {
3151
throw new FS.ErrnoError(63);
3152
}
3153
node.node_ops.setattr(node, {
3154
timestamp: Date.now()
3155
// we ignore the uid / gid for now
3156
});
3157
},lchown:function(path, uid, gid) {
3158
FS.chown(path, uid, gid, true);
3159
},fchown:function(fd, uid, gid) {
3160
var stream = FS.getStream(fd);
3161
if (!stream) {
3162
throw new FS.ErrnoError(8);
3163
}
3164
FS.chown(stream.node, uid, gid);
3165
},truncate:function(path, len) {
3166
if (len < 0) {
3167
throw new FS.ErrnoError(28);
3168
}
3169
var node;
3170
if (typeof path === 'string') {
3171
var lookup = FS.lookupPath(path, { follow: true });
3172
node = lookup.node;
3173
} else {
3174
node = path;
3175
}
3176
if (!node.node_ops.setattr) {
3177
throw new FS.ErrnoError(63);
3178
}
3179
if (FS.isDir(node.mode)) {
3180
throw new FS.ErrnoError(31);
3181
}
3182
if (!FS.isFile(node.mode)) {
3183
throw new FS.ErrnoError(28);
3184
}
3185
var errCode = FS.nodePermissions(node, 'w');
3186
if (errCode) {
3187
throw new FS.ErrnoError(errCode);
3188
}
3189
node.node_ops.setattr(node, {
3190
size: len,
3191
timestamp: Date.now()
3192
});
3193
},ftruncate:function(fd, len) {
3194
var stream = FS.getStream(fd);
3195
if (!stream) {
3196
throw new FS.ErrnoError(8);
3197
}
3198
if ((stream.flags & 2097155) === 0) {
3199
throw new FS.ErrnoError(28);
3200
}
3201
FS.truncate(stream.node, len);
3202
},utime:function(path, atime, mtime) {
3203
var lookup = FS.lookupPath(path, { follow: true });
3204
var node = lookup.node;
3205
node.node_ops.setattr(node, {
3206
timestamp: Math.max(atime, mtime)
3207
});
3208
},open:function(path, flags, mode, fd_start, fd_end) {
3209
if (path === "") {
3210
throw new FS.ErrnoError(44);
3211
}
3212
flags = typeof flags === 'string' ? FS.modeStringToFlags(flags) : flags;
3213
mode = typeof mode === 'undefined' ? 438 /* 0666 */ : mode;
3214
if ((flags & 64)) {
3215
mode = (mode & 4095) | 32768;
3216
} else {
3217
mode = 0;
3218
}
3219
var node;
3220
if (typeof path === 'object') {
3221
node = path;
3222
} else {
3223
path = PATH.normalize(path);
3224
try {
3225
var lookup = FS.lookupPath(path, {
3226
follow: !(flags & 131072)
3227
});
3228
node = lookup.node;
3229
} catch (e) {
3230
// ignore
3231
}
3232
}
3233
// perhaps we need to create the node
3234
var created = false;
3235
if ((flags & 64)) {
3236
if (node) {
3237
// if O_CREAT and O_EXCL are set, error out if the node already exists
3238
if ((flags & 128)) {
3239
throw new FS.ErrnoError(20);
3240
}
3241
} else {
3242
// node doesn't exist, try to create it
3243
node = FS.mknod(path, mode, 0);
3244
created = true;
3245
}
3246
}
3247
if (!node) {
3248
throw new FS.ErrnoError(44);
3249
}
3250
// can't truncate a device
3251
if (FS.isChrdev(node.mode)) {
3252
flags &= ~512;
3253
}
3254
// if asked only for a directory, then this must be one
3255
if ((flags & 65536) && !FS.isDir(node.mode)) {
3256
throw new FS.ErrnoError(54);
3257
}
3258
// check permissions, if this is not a file we just created now (it is ok to
3259
// create and write to a file with read-only permissions; it is read-only
3260
// for later use)
3261
if (!created) {
3262
var errCode = FS.mayOpen(node, flags);
3263
if (errCode) {
3264
throw new FS.ErrnoError(errCode);
3265
}
3266
}
3267
// do truncation if necessary
3268
if ((flags & 512)) {
3269
FS.truncate(node, 0);
3270
}
3271
// we've already handled these, don't pass down to the underlying vfs
3272
flags &= ~(128 | 512);
3273
3274
// register the stream with the filesystem
3275
var stream = FS.createStream({
3276
node: node,
3277
path: FS.getPath(node), // we want the absolute path to the node
3278
flags: flags,
3279
seekable: true,
3280
position: 0,
3281
stream_ops: node.stream_ops,
3282
// used by the file family libc calls (fopen, fwrite, ferror, etc.)
3283
ungotten: [],
3284
error: false
3285
}, fd_start, fd_end);
3286
// call the new stream's open function
3287
if (stream.stream_ops.open) {
3288
stream.stream_ops.open(stream);
3289
}
3290
if (Module['logReadFiles'] && !(flags & 1)) {
3291
if (!FS.readFiles) FS.readFiles = {};
3292
if (!(path in FS.readFiles)) {
3293
FS.readFiles[path] = 1;
3294
err("FS.trackingDelegate error on read file: " + path);
3295
}
3296
}
3297
try {
3298
if (FS.trackingDelegate['onOpenFile']) {
3299
var trackingFlags = 0;
3300
if ((flags & 2097155) !== 1) {
3301
trackingFlags |= FS.tracking.openFlags.READ;
3302
}
3303
if ((flags & 2097155) !== 0) {
3304
trackingFlags |= FS.tracking.openFlags.WRITE;
3305
}
3306
FS.trackingDelegate['onOpenFile'](path, trackingFlags);
3307
}
3308
} catch(e) {
3309
err("FS.trackingDelegate['onOpenFile']('"+path+"', flags) threw an exception: " + e.message);
3310
}
3311
return stream;
3312
},close:function(stream) {
3313
if (FS.isClosed(stream)) {
3314
throw new FS.ErrnoError(8);
3315
}
3316
if (stream.getdents) stream.getdents = null; // free readdir state
3317
try {
3318
if (stream.stream_ops.close) {
3319
stream.stream_ops.close(stream);
3320
}
3321
} catch (e) {
3322
throw e;
3323
} finally {
3324
FS.closeStream(stream.fd);
3325
}
3326
stream.fd = null;
3327
},isClosed:function(stream) {
3328
return stream.fd === null;
3329
},llseek:function(stream, offset, whence) {
3330
if (FS.isClosed(stream)) {
3331
throw new FS.ErrnoError(8);
3332
}
3333
if (!stream.seekable || !stream.stream_ops.llseek) {
3334
throw new FS.ErrnoError(70);
3335
}
3336
if (whence != 0 && whence != 1 && whence != 2) {
3337
throw new FS.ErrnoError(28);
3338
}
3339
stream.position = stream.stream_ops.llseek(stream, offset, whence);
3340
stream.ungotten = [];
3341
return stream.position;
3342
},read:function(stream, buffer, offset, length, position) {
3343
if (length < 0 || position < 0) {
3344
throw new FS.ErrnoError(28);
3345
}
3346
if (FS.isClosed(stream)) {
3347
throw new FS.ErrnoError(8);
3348
}
3349
if ((stream.flags & 2097155) === 1) {
3350
throw new FS.ErrnoError(8);
3351
}
3352
if (FS.isDir(stream.node.mode)) {
3353
throw new FS.ErrnoError(31);
3354
}
3355
if (!stream.stream_ops.read) {
3356
throw new FS.ErrnoError(28);
3357
}
3358
var seeking = typeof position !== 'undefined';
3359
if (!seeking) {
3360
position = stream.position;
3361
} else if (!stream.seekable) {
3362
throw new FS.ErrnoError(70);
3363
}
3364
var bytesRead = stream.stream_ops.read(stream, buffer, offset, length, position);
3365
if (!seeking) stream.position += bytesRead;
3366
return bytesRead;
3367
},write:function(stream, buffer, offset, length, position, canOwn) {
3368
if (length < 0 || position < 0) {
3369
throw new FS.ErrnoError(28);
3370
}
3371
if (FS.isClosed(stream)) {
3372
throw new FS.ErrnoError(8);
3373
}
3374
if ((stream.flags & 2097155) === 0) {
3375
throw new FS.ErrnoError(8);
3376
}
3377
if (FS.isDir(stream.node.mode)) {
3378
throw new FS.ErrnoError(31);
3379
}
3380
if (!stream.stream_ops.write) {
3381
throw new FS.ErrnoError(28);
3382
}
3383
if (stream.flags & 1024) {
3384
// seek to the end before writing in append mode
3385
FS.llseek(stream, 0, 2);
3386
}
3387
var seeking = typeof position !== 'undefined';
3388
if (!seeking) {
3389
position = stream.position;
3390
} else if (!stream.seekable) {
3391
throw new FS.ErrnoError(70);
3392
}
3393
var bytesWritten = stream.stream_ops.write(stream, buffer, offset, length, position, canOwn);
3394
if (!seeking) stream.position += bytesWritten;
3395
try {
3396
if (stream.path && FS.trackingDelegate['onWriteToFile']) FS.trackingDelegate['onWriteToFile'](stream.path);
3397
} catch(e) {
3398
err("FS.trackingDelegate['onWriteToFile']('"+stream.path+"') threw an exception: " + e.message);
3399
}
3400
return bytesWritten;
3401
},allocate:function(stream, offset, length) {
3402
if (FS.isClosed(stream)) {
3403
throw new FS.ErrnoError(8);
3404
}
3405
if (offset < 0 || length <= 0) {
3406
throw new FS.ErrnoError(28);
3407
}
3408
if ((stream.flags & 2097155) === 0) {
3409
throw new FS.ErrnoError(8);
3410
}
3411
if (!FS.isFile(stream.node.mode) && !FS.isDir(stream.node.mode)) {
3412
throw new FS.ErrnoError(43);
3413
}
3414
if (!stream.stream_ops.allocate) {
3415
throw new FS.ErrnoError(138);
3416
}
3417
stream.stream_ops.allocate(stream, offset, length);
3418
},mmap:function(stream, buffer, offset, length, position, prot, flags) {
3419
// User requests writing to file (prot & PROT_WRITE != 0).
3420
// Checking if we have permissions to write to the file unless
3421
// MAP_PRIVATE flag is set. According to POSIX spec it is possible
3422
// to write to file opened in read-only mode with MAP_PRIVATE flag,
3423
// as all modifications will be visible only in the memory of
3424
// the current process.
3425
if ((prot & 2) !== 0
3426
&& (flags & 2) === 0
3427
&& (stream.flags & 2097155) !== 2) {
3428
throw new FS.ErrnoError(2);
3429
}
3430
if ((stream.flags & 2097155) === 1) {
3431
throw new FS.ErrnoError(2);
3432
}
3433
if (!stream.stream_ops.mmap) {
3434
throw new FS.ErrnoError(43);
3435
}
3436
return stream.stream_ops.mmap(stream, buffer, offset, length, position, prot, flags);
3437
},msync:function(stream, buffer, offset, length, mmapFlags) {
3438
if (!stream || !stream.stream_ops.msync) {
3439
return 0;
3440
}
3441
return stream.stream_ops.msync(stream, buffer, offset, length, mmapFlags);
3442
},munmap:function(stream) {
3443
return 0;
3444
},ioctl:function(stream, cmd, arg) {
3445
if (!stream.stream_ops.ioctl) {
3446
throw new FS.ErrnoError(59);
3447
}
3448
return stream.stream_ops.ioctl(stream, cmd, arg);
3449
},readFile:function(path, opts) {
3450
opts = opts || {};
3451
opts.flags = opts.flags || 'r';
3452
opts.encoding = opts.encoding || 'binary';
3453
if (opts.encoding !== 'utf8' && opts.encoding !== 'binary') {
3454
throw new Error('Invalid encoding type "' + opts.encoding + '"');
3455
}
3456
var ret;
3457
var stream = FS.open(path, opts.flags);
3458
var stat = FS.stat(path);
3459
var length = stat.size;
3460
var buf = new Uint8Array(length);
3461
FS.read(stream, buf, 0, length, 0);
3462
if (opts.encoding === 'utf8') {
3463
ret = UTF8ArrayToString(buf, 0);
3464
} else if (opts.encoding === 'binary') {
3465
ret = buf;
3466
}
3467
FS.close(stream);
3468
return ret;
3469
},writeFile:function(path, data, opts) {
3470
opts = opts || {};
3471
opts.flags = opts.flags || 'w';
3472
var stream = FS.open(path, opts.flags, opts.mode);
3473
if (typeof data === 'string') {
3474
var buf = new Uint8Array(lengthBytesUTF8(data)+1);
3475
var actualNumBytes = stringToUTF8Array(data, buf, 0, buf.length);
3476
FS.write(stream, buf, 0, actualNumBytes, undefined, opts.canOwn);
3477
} else if (ArrayBuffer.isView(data)) {
3478
FS.write(stream, data, 0, data.byteLength, undefined, opts.canOwn);
3479
} else {
3480
throw new Error('Unsupported data type');
3481
}
3482
FS.close(stream);
3483
},cwd:function() {
3484
return FS.currentPath;
3485
},chdir:function(path) {
3486
var lookup = FS.lookupPath(path, { follow: true });
3487
if (lookup.node === null) {
3488
throw new FS.ErrnoError(44);
3489
}
3490
if (!FS.isDir(lookup.node.mode)) {
3491
throw new FS.ErrnoError(54);
3492
}
3493
var errCode = FS.nodePermissions(lookup.node, 'x');
3494
if (errCode) {
3495
throw new FS.ErrnoError(errCode);
3496
}
3497
FS.currentPath = lookup.path;
3498
},createDefaultDirectories:function() {
3499
FS.mkdir('/tmp');
3500
FS.mkdir('/home');
3501
FS.mkdir('/home/web_user');
3502
},createDefaultDevices:function() {
3503
// create /dev
3504
FS.mkdir('/dev');
3505
// setup /dev/null
3506
FS.registerDevice(FS.makedev(1, 3), {
3507
read: function() { return 0; },
3508
write: function(stream, buffer, offset, length, pos) { return length; }
3509
});
3510
FS.mkdev('/dev/null', FS.makedev(1, 3));
3511
// setup /dev/tty and /dev/tty1
3512
// stderr needs to print output using Module['printErr']
3513
// so we register a second tty just for it.
3514
TTY.register(FS.makedev(5, 0), TTY.default_tty_ops);
3515
TTY.register(FS.makedev(6, 0), TTY.default_tty1_ops);
3516
FS.mkdev('/dev/tty', FS.makedev(5, 0));
3517
FS.mkdev('/dev/tty1', FS.makedev(6, 0));
3518
// setup /dev/[u]random
3519
var random_device;
3520
if (typeof crypto === 'object' && typeof crypto['getRandomValues'] === 'function') {
3521
// for modern web browsers
3522
var randomBuffer = new Uint8Array(1);
3523
random_device = function() { crypto.getRandomValues(randomBuffer); return randomBuffer[0]; };
3524
} else
3525
if (ENVIRONMENT_IS_NODE) {
3526
// for nodejs with or without crypto support included
3527
try {
3528
var crypto_module = require('crypto');
3529
// nodejs has crypto support
3530
random_device = function() { return crypto_module['randomBytes'](1)[0]; };
3531
} catch (e) {
3532
// nodejs doesn't have crypto support
3533
}
3534
} else
3535
{}
3536
if (!random_device) {
3537
// we couldn't find a proper implementation, as Math.random() is not suitable for /dev/random, see emscripten-core/emscripten/pull/7096
3538
random_device = function() { abort("no cryptographic support found for random_device. consider polyfilling it if you want to use something insecure like Math.random(), e.g. put this in a --pre-js: var crypto = { getRandomValues: function(array) { for (var i = 0; i < array.length; i++) array[i] = (Math.random()*256)|0 } };"); };
3539
}
3540
FS.createDevice('/dev', 'random', random_device);
3541
FS.createDevice('/dev', 'urandom', random_device);
3542
// we're not going to emulate the actual shm device,
3543
// just create the tmp dirs that reside in it commonly
3544
FS.mkdir('/dev/shm');
3545
FS.mkdir('/dev/shm/tmp');
3546
},createSpecialDirectories:function() {
3547
// create /proc/self/fd which allows /proc/self/fd/6 => readlink gives the name of the stream for fd 6 (see test_unistd_ttyname)
3548
FS.mkdir('/proc');
3549
FS.mkdir('/proc/self');
3550
FS.mkdir('/proc/self/fd');
3551
FS.mount({
3552
mount: function() {
3553
var node = FS.createNode('/proc/self', 'fd', 16384 | 511 /* 0777 */, 73);
3554
node.node_ops = {
3555
lookup: function(parent, name) {
3556
var fd = +name;
3557
var stream = FS.getStream(fd);
3558
if (!stream) throw new FS.ErrnoError(8);
3559
var ret = {
3560
parent: null,
3561
mount: { mountpoint: 'fake' },
3562
node_ops: { readlink: function() { return stream.path } }
3563
};
3564
ret.parent = ret; // make it look like a simple root node
3565
return ret;
3566
}
3567
};
3568
return node;
3569
}
3570
}, {}, '/proc/self/fd');
3571
},createStandardStreams:function() {
3572
// TODO deprecate the old functionality of a single
3573
// input / output callback and that utilizes FS.createDevice
3574
// and instead require a unique set of stream ops
3575
3576
// by default, we symlink the standard streams to the
3577
// default tty devices. however, if the standard streams
3578
// have been overwritten we create a unique device for
3579
// them instead.
3580
if (Module['stdin']) {
3581
FS.createDevice('/dev', 'stdin', Module['stdin']);
3582
} else {
3583
FS.symlink('/dev/tty', '/dev/stdin');
3584
}
3585
if (Module['stdout']) {
3586
FS.createDevice('/dev', 'stdout', null, Module['stdout']);
3587
} else {
3588
FS.symlink('/dev/tty', '/dev/stdout');
3589
}
3590
if (Module['stderr']) {
3591
FS.createDevice('/dev', 'stderr', null, Module['stderr']);
3592
} else {
3593
FS.symlink('/dev/tty1', '/dev/stderr');
3594
}
3595
3596
// open default streams for the stdin, stdout and stderr devices
3597
var stdin = FS.open('/dev/stdin', 'r');
3598
var stdout = FS.open('/dev/stdout', 'w');
3599
var stderr = FS.open('/dev/stderr', 'w');
3600
assert(stdin.fd === 0, 'invalid handle for stdin (' + stdin.fd + ')');
3601
assert(stdout.fd === 1, 'invalid handle for stdout (' + stdout.fd + ')');
3602
assert(stderr.fd === 2, 'invalid handle for stderr (' + stderr.fd + ')');
3603
},ensureErrnoError:function() {
3604
if (FS.ErrnoError) return;
3605
FS.ErrnoError = /** @this{Object} */ function ErrnoError(errno, node) {
3606
this.node = node;
3607
this.setErrno = /** @this{Object} */ function(errno) {
3608
this.errno = errno;
3609
for (var key in ERRNO_CODES) {
3610
if (ERRNO_CODES[key] === errno) {
3611
this.code = key;
3612
break;
3613
}
3614
}
3615
};
3616
this.setErrno(errno);
3617
this.message = ERRNO_MESSAGES[errno];
3618
3619
// Try to get a maximally helpful stack trace. On Node.js, getting Error.stack
3620
// now ensures it shows what we want.
3621
if (this.stack) {
3622
// Define the stack property for Node.js 4, which otherwise errors on the next line.
3623
Object.defineProperty(this, "stack", { value: (new Error).stack, writable: true });
3624
this.stack = demangleAll(this.stack);
3625
}
3626
};
3627
FS.ErrnoError.prototype = new Error();
3628
FS.ErrnoError.prototype.constructor = FS.ErrnoError;
3629
// Some errors may happen quite a bit, to avoid overhead we reuse them (and suffer a lack of stack info)
3630
[44].forEach(function(code) {
3631
FS.genericErrors[code] = new FS.ErrnoError(code);
3632
FS.genericErrors[code].stack = '<generic error, no stack>';
3633
});
3634
},staticInit:function() {
3635
FS.ensureErrnoError();
3636
3637
FS.nameTable = new Array(4096);
3638
3639
FS.mount(MEMFS, {}, '/');
3640
3641
FS.createDefaultDirectories();
3642
FS.createDefaultDevices();
3643
FS.createSpecialDirectories();
3644
3645
FS.filesystems = {
3646
'MEMFS': MEMFS,
3647
};
3648
},init:function(input, output, error) {
3649
assert(!FS.init.initialized, 'FS.init was previously called. If you want to initialize later with custom parameters, remove any earlier calls (note that one is automatically added to the generated code)');
3650
FS.init.initialized = true;
3651
3652
FS.ensureErrnoError();
3653
3654
// Allow Module.stdin etc. to provide defaults, if none explicitly passed to us here
3655
Module['stdin'] = input || Module['stdin'];
3656
Module['stdout'] = output || Module['stdout'];
3657
Module['stderr'] = error || Module['stderr'];
3658
3659
FS.createStandardStreams();
3660
},quit:function() {
3661
FS.init.initialized = false;
3662
// force-flush all streams, so we get musl std streams printed out
3663
var fflush = Module['_fflush'];
3664
if (fflush) fflush(0);
3665
// close all of our streams
3666
for (var i = 0; i < FS.streams.length; i++) {
3667
var stream = FS.streams[i];
3668
if (!stream) {
3669
continue;
3670
}
3671
FS.close(stream);
3672
}
3673
},getMode:function(canRead, canWrite) {
3674
var mode = 0;
3675
if (canRead) mode |= 292 | 73;
3676
if (canWrite) mode |= 146;
3677
return mode;
3678
},joinPath:function(parts, forceRelative) {
3679
var path = PATH.join.apply(null, parts);
3680
if (forceRelative && path[0] == '/') path = path.substr(1);
3681
return path;
3682
},absolutePath:function(relative, base) {
3683
return PATH_FS.resolve(base, relative);
3684
},standardizePath:function(path) {
3685
return PATH.normalize(path);
3686
},findObject:function(path, dontResolveLastLink) {
3687
var ret = FS.analyzePath(path, dontResolveLastLink);
3688
if (ret.exists) {
3689
return ret.object;
3690
} else {
3691
___setErrNo(ret.error);
3692
return null;
3693
}
3694
},analyzePath:function(path, dontResolveLastLink) {
3695
// operate from within the context of the symlink's target
3696
try {
3697
var lookup = FS.lookupPath(path, { follow: !dontResolveLastLink });
3698
path = lookup.path;
3699
} catch (e) {
3700
}
3701
var ret = {
3702
isRoot: false, exists: false, error: 0, name: null, path: null, object: null,
3703
parentExists: false, parentPath: null, parentObject: null
3704
};
3705
try {
3706
var lookup = FS.lookupPath(path, { parent: true });
3707
ret.parentExists = true;
3708
ret.parentPath = lookup.path;
3709
ret.parentObject = lookup.node;
3710
ret.name = PATH.basename(path);
3711
lookup = FS.lookupPath(path, { follow: !dontResolveLastLink });
3712
ret.exists = true;
3713
ret.path = lookup.path;
3714
ret.object = lookup.node;
3715
ret.name = lookup.node.name;
3716
ret.isRoot = lookup.path === '/';
3717
} catch (e) {
3718
ret.error = e.errno;
3719
};
3720
return ret;
3721
},createFolder:function(parent, name, canRead, canWrite) {
3722
var path = PATH.join2(typeof parent === 'string' ? parent : FS.getPath(parent), name);
3723
var mode = FS.getMode(canRead, canWrite);
3724
return FS.mkdir(path, mode);
3725
},createPath:function(parent, path, canRead, canWrite) {
3726
parent = typeof parent === 'string' ? parent : FS.getPath(parent);
3727
var parts = path.split('/').reverse();
3728
while (parts.length) {
3729
var part = parts.pop();
3730
if (!part) continue;
3731
var current = PATH.join2(parent, part);
3732
try {
3733
FS.mkdir(current);
3734
} catch (e) {
3735
// ignore EEXIST
3736
}
3737
parent = current;
3738
}
3739
return current;
3740
},createFile:function(parent, name, properties, canRead, canWrite) {
3741
var path = PATH.join2(typeof parent === 'string' ? parent : FS.getPath(parent), name);
3742
var mode = FS.getMode(canRead, canWrite);
3743
return FS.create(path, mode);
3744
},createDataFile:function(parent, name, data, canRead, canWrite, canOwn) {
3745
var path = name ? PATH.join2(typeof parent === 'string' ? parent : FS.getPath(parent), name) : parent;
3746
var mode = FS.getMode(canRead, canWrite);
3747
var node = FS.create(path, mode);
3748
if (data) {
3749
if (typeof data === 'string') {
3750
var arr = new Array(data.length);
3751
for (var i = 0, len = data.length; i < len; ++i) arr[i] = data.charCodeAt(i);
3752
data = arr;
3753
}
3754
// make sure we can write to the file
3755
FS.chmod(node, mode | 146);
3756
var stream = FS.open(node, 'w');
3757
FS.write(stream, data, 0, data.length, 0, canOwn);
3758
FS.close(stream);
3759
FS.chmod(node, mode);
3760
}
3761
return node;
3762
},createDevice:function(parent, name, input, output) {
3763
var path = PATH.join2(typeof parent === 'string' ? parent : FS.getPath(parent), name);
3764
var mode = FS.getMode(!!input, !!output);
3765
if (!FS.createDevice.major) FS.createDevice.major = 64;
3766
var dev = FS.makedev(FS.createDevice.major++, 0);
3767
// Create a fake device that a set of stream ops to emulate
3768
// the old behavior.
3769
FS.registerDevice(dev, {
3770
open: function(stream) {
3771
stream.seekable = false;
3772
},
3773
close: function(stream) {
3774
// flush any pending line data
3775
if (output && output.buffer && output.buffer.length) {
3776
output(10);
3777
}
3778
},
3779
read: function(stream, buffer, offset, length, pos /* ignored */) {
3780
var bytesRead = 0;
3781
for (var i = 0; i < length; i++) {
3782
var result;
3783
try {
3784
result = input();
3785
} catch (e) {
3786
throw new FS.ErrnoError(29);
3787
}
3788
if (result === undefined && bytesRead === 0) {
3789
throw new FS.ErrnoError(6);
3790
}
3791
if (result === null || result === undefined) break;
3792
bytesRead++;
3793
buffer[offset+i] = result;
3794
}
3795
if (bytesRead) {
3796
stream.node.timestamp = Date.now();
3797
}
3798
return bytesRead;
3799
},
3800
write: function(stream, buffer, offset, length, pos) {
3801
for (var i = 0; i < length; i++) {
3802
try {
3803
output(buffer[offset+i]);
3804
} catch (e) {
3805
throw new FS.ErrnoError(29);
3806
}
3807
}
3808
if (length) {
3809
stream.node.timestamp = Date.now();
3810
}
3811
return i;
3812
}
3813
});
3814
return FS.mkdev(path, mode, dev);
3815
},createLink:function(parent, name, target, canRead, canWrite) {
3816
var path = PATH.join2(typeof parent === 'string' ? parent : FS.getPath(parent), name);
3817
return FS.symlink(target, path);
3818
},forceLoadFile:function(obj) {
3819
if (obj.isDevice || obj.isFolder || obj.link || obj.contents) return true;
3820
var success = true;
3821
if (typeof XMLHttpRequest !== 'undefined') {
3822
throw new Error("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.");
3823
} else if (read_) {
3824
// Command-line.
3825
try {
3826
// WARNING: Can't read binary files in V8's d8 or tracemonkey's js, as
3827
// read() will try to parse UTF8.
3828
obj.contents = intArrayFromString(read_(obj.url), true);
3829
obj.usedBytes = obj.contents.length;
3830
} catch (e) {
3831
success = false;
3832
}
3833
} else {
3834
throw new Error('Cannot load without read() or XMLHttpRequest.');
3835
}
3836
if (!success) ___setErrNo(29);
3837
return success;
3838
},createLazyFile:function(parent, name, url, canRead, canWrite) {
3839
// Lazy chunked Uint8Array (implements get and length from Uint8Array). Actual getting is abstracted away for eventual reuse.
3840
/** @constructor */
3841
function LazyUint8Array() {
3842
this.lengthKnown = false;
3843
this.chunks = []; // Loaded chunks. Index is the chunk number
3844
}
3845
LazyUint8Array.prototype.get = /** @this{Object} */ function LazyUint8Array_get(idx) {
3846
if (idx > this.length-1 || idx < 0) {
3847
return undefined;
3848
}
3849
var chunkOffset = idx % this.chunkSize;
3850
var chunkNum = (idx / this.chunkSize)|0;
3851
return this.getter(chunkNum)[chunkOffset];
3852
};
3853
LazyUint8Array.prototype.setDataGetter = function LazyUint8Array_setDataGetter(getter) {
3854
this.getter = getter;
3855
};
3856
LazyUint8Array.prototype.cacheLength = function LazyUint8Array_cacheLength() {
3857
// Find length
3858
var xhr = new XMLHttpRequest();
3859
xhr.open('HEAD', url, false);
3860
xhr.send(null);
3861
if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) throw new Error("Couldn't load " + url + ". Status: " + xhr.status);
3862
var datalength = Number(xhr.getResponseHeader("Content-length"));
3863
var header;
3864
var hasByteServing = (header = xhr.getResponseHeader("Accept-Ranges")) && header === "bytes";
3865
var usesGzip = (header = xhr.getResponseHeader("Content-Encoding")) && header === "gzip";
3866
3867
var chunkSize = 1024*1024; // Chunk size in bytes
3868
3869
if (!hasByteServing) chunkSize = datalength;
3870
3871
// Function to get a range from the remote URL.
3872
var doXHR = (function(from, to) {
3873
if (from > to) throw new Error("invalid range (" + from + ", " + to + ") or no bytes requested!");
3874
if (to > datalength-1) throw new Error("only " + datalength + " bytes available! programmer error!");
3875
3876
// TODO: Use mozResponseArrayBuffer, responseStream, etc. if available.
3877
var xhr = new XMLHttpRequest();
3878
xhr.open('GET', url, false);
3879
if (datalength !== chunkSize) xhr.setRequestHeader("Range", "bytes=" + from + "-" + to);
3880
3881
// Some hints to the browser that we want binary data.
3882
if (typeof Uint8Array != 'undefined') xhr.responseType = 'arraybuffer';
3883
if (xhr.overrideMimeType) {
3884
xhr.overrideMimeType('text/plain; charset=x-user-defined');
3885
}
3886
3887
xhr.send(null);
3888
if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) throw new Error("Couldn't load " + url + ". Status: " + xhr.status);
3889
if (xhr.response !== undefined) {
3890
return new Uint8Array(/** @type{Array<number>} */(xhr.response || []));
3891
} else {
3892
return intArrayFromString(xhr.responseText || '', true);
3893
}
3894
});
3895
var lazyArray = this;
3896
lazyArray.setDataGetter(function(chunkNum) {
3897
var start = chunkNum * chunkSize;
3898
var end = (chunkNum+1) * chunkSize - 1; // including this byte
3899
end = Math.min(end, datalength-1); // if datalength-1 is selected, this is the last block
3900
if (typeof(lazyArray.chunks[chunkNum]) === "undefined") {
3901
lazyArray.chunks[chunkNum] = doXHR(start, end);
3902
}
3903
if (typeof(lazyArray.chunks[chunkNum]) === "undefined") throw new Error("doXHR failed!");
3904
return lazyArray.chunks[chunkNum];
3905
});
3906
3907
if (usesGzip || !datalength) {
3908
// if the server uses gzip or doesn't supply the length, we have to download the whole file to get the (uncompressed) length
3909
chunkSize = datalength = 1; // this will force getter(0)/doXHR do download the whole file
3910
datalength = this.getter(0).length;
3911
chunkSize = datalength;
3912
out("LazyFiles on gzip forces download of the whole file when length is accessed");
3913
}
3914
3915
this._length = datalength;
3916
this._chunkSize = chunkSize;
3917
this.lengthKnown = true;
3918
};
3919
if (typeof XMLHttpRequest !== 'undefined') {
3920
if (!ENVIRONMENT_IS_WORKER) throw 'Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc';
3921
var lazyArray = new LazyUint8Array();
3922
Object.defineProperties(lazyArray, {
3923
length: {
3924
get: /** @this{Object} */ function() {
3925
if(!this.lengthKnown) {
3926
this.cacheLength();
3927
}
3928
return this._length;
3929
}
3930
},
3931
chunkSize: {
3932
get: /** @this{Object} */ function() {
3933
if(!this.lengthKnown) {
3934
this.cacheLength();
3935
}
3936
return this._chunkSize;
3937
}
3938
}
3939
});
3940
3941
var properties = { isDevice: false, contents: lazyArray };
3942
} else {
3943
var properties = { isDevice: false, url: url };
3944
}
3945
3946
var node = FS.createFile(parent, name, properties, canRead, canWrite);
3947
// This is a total hack, but I want to get this lazy file code out of the
3948
// core of MEMFS. If we want to keep this lazy file concept I feel it should
3949
// be its own thin LAZYFS proxying calls to MEMFS.
3950
if (properties.contents) {
3951
node.contents = properties.contents;
3952
} else if (properties.url) {
3953
node.contents = null;
3954
node.url = properties.url;
3955
}
3956
// Add a function that defers querying the file size until it is asked the first time.
3957
Object.defineProperties(node, {
3958
usedBytes: {
3959
get: /** @this {FSNode} */ function() { return this.contents.length; }
3960
}
3961
});
3962
// override each stream op with one that tries to force load the lazy file first
3963
var stream_ops = {};
3964
var keys = Object.keys(node.stream_ops);
3965
keys.forEach(function(key) {
3966
var fn = node.stream_ops[key];
3967
stream_ops[key] = function forceLoadLazyFile() {
3968
if (!FS.forceLoadFile(node)) {
3969
throw new FS.ErrnoError(29);
3970
}
3971
return fn.apply(null, arguments);
3972
};
3973
});
3974
// use a custom read function
3975
stream_ops.read = function stream_ops_read(stream, buffer, offset, length, position) {
3976
if (!FS.forceLoadFile(node)) {
3977
throw new FS.ErrnoError(29);
3978
}
3979
var contents = stream.node.contents;
3980
if (position >= contents.length)
3981
return 0;
3982
var size = Math.min(contents.length - position, length);
3983
assert(size >= 0);
3984
if (contents.slice) { // normal array
3985
for (var i = 0; i < size; i++) {
3986
buffer[offset + i] = contents[position + i];
3987
}
3988
} else {
3989
for (var i = 0; i < size; i++) { // LazyUint8Array from sync binary XHR
3990
buffer[offset + i] = contents.get(position + i);
3991
}
3992
}
3993
return size;
3994
};
3995
node.stream_ops = stream_ops;
3996
return node;
3997
},createPreloadedFile:function(parent, name, url, canRead, canWrite, onload, onerror, dontCreateFile, canOwn, preFinish) {
3998
Browser.init(); // XXX perhaps this method should move onto Browser?
3999
// TODO we should allow people to just pass in a complete filename instead
4000
// of parent and name being that we just join them anyways
4001
var fullname = name ? PATH_FS.resolve(PATH.join2(parent, name)) : parent;
4002
var dep = getUniqueRunDependency('cp ' + fullname); // might have several active requests for the same fullname
4003
function processData(byteArray) {
4004
function finish(byteArray) {
4005
if (preFinish) preFinish();
4006
if (!dontCreateFile) {
4007
FS.createDataFile(parent, name, byteArray, canRead, canWrite, canOwn);
4008
}
4009
if (onload) onload();
4010
removeRunDependency(dep);
4011
}
4012
var handled = false;
4013
Module['preloadPlugins'].forEach(function(plugin) {
4014
if (handled) return;
4015
if (plugin['canHandle'](fullname)) {
4016
plugin['handle'](byteArray, fullname, finish, function() {
4017
if (onerror) onerror();
4018
removeRunDependency(dep);
4019
});
4020
handled = true;
4021
}
4022
});
4023
if (!handled) finish(byteArray);
4024
}
4025
addRunDependency(dep);
4026
if (typeof url == 'string') {
4027
Browser.asyncLoad(url, function(byteArray) {
4028
processData(byteArray);
4029
}, onerror);
4030
} else {
4031
processData(url);
4032
}
4033
},indexedDB:function() {
4034
return window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
4035
},DB_NAME:function() {
4036
return 'EM_FS_' + window.location.pathname;
4037
},DB_VERSION:20,DB_STORE_NAME:"FILE_DATA",saveFilesToDB:function(paths, onload, onerror) {
4038
onload = onload || function(){};
4039
onerror = onerror || function(){};
4040
var indexedDB = FS.indexedDB();
4041
try {
4042
var openRequest = indexedDB.open(FS.DB_NAME(), FS.DB_VERSION);
4043
} catch (e) {
4044
return onerror(e);
4045
}
4046
openRequest.onupgradeneeded = function openRequest_onupgradeneeded() {
4047
out('creating db');
4048
var db = openRequest.result;
4049
db.createObjectStore(FS.DB_STORE_NAME);
4050
};
4051
openRequest.onsuccess = function openRequest_onsuccess() {
4052
var db = openRequest.result;
4053
var transaction = db.transaction([FS.DB_STORE_NAME], 'readwrite');
4054
var files = transaction.objectStore(FS.DB_STORE_NAME);
4055
var ok = 0, fail = 0, total = paths.length;
4056
function finish() {
4057
if (fail == 0) onload(); else onerror();
4058
}
4059
paths.forEach(function(path) {
4060
var putRequest = files.put(FS.analyzePath(path).object.contents, path);
4061
putRequest.onsuccess = function putRequest_onsuccess() { ok++; if (ok + fail == total) finish() };
4062
putRequest.onerror = function putRequest_onerror() { fail++; if (ok + fail == total) finish() };
4063
});
4064
transaction.onerror = onerror;
4065
};
4066
openRequest.onerror = onerror;
4067
},loadFilesFromDB:function(paths, onload, onerror) {
4068
onload = onload || function(){};
4069
onerror = onerror || function(){};
4070
var indexedDB = FS.indexedDB();
4071
try {
4072
var openRequest = indexedDB.open(FS.DB_NAME(), FS.DB_VERSION);
4073
} catch (e) {
4074
return onerror(e);
4075
}
4076
openRequest.onupgradeneeded = onerror; // no database to load from
4077
openRequest.onsuccess = function openRequest_onsuccess() {
4078
var db = openRequest.result;
4079
try {
4080
var transaction = db.transaction([FS.DB_STORE_NAME], 'readonly');
4081
} catch(e) {
4082
onerror(e);
4083
return;
4084
}
4085
var files = transaction.objectStore(FS.DB_STORE_NAME);
4086
var ok = 0, fail = 0, total = paths.length;
4087
function finish() {
4088
if (fail == 0) onload(); else onerror();
4089
}
4090
paths.forEach(function(path) {
4091
var getRequest = files.get(path);
4092
getRequest.onsuccess = function getRequest_onsuccess() {
4093
if (FS.analyzePath(path).exists) {
4094
FS.unlink(path);
4095
}
4096
FS.createDataFile(PATH.dirname(path), PATH.basename(path), getRequest.result, true, true, true);
4097
ok++;
4098
if (ok + fail == total) finish();
4099
};
4100
getRequest.onerror = function getRequest_onerror() { fail++; if (ok + fail == total) finish() };
4101
});
4102
transaction.onerror = onerror;
4103
};
4104
openRequest.onerror = onerror;
4105
}};var SYSCALLS={mappings:{},DEFAULT_POLLMASK:5,umask:511,calculateAt:function(dirfd, path) {
4106
if (path[0] !== '/') {
4107
// relative path
4108
var dir;
4109
if (dirfd === -100) {
4110
dir = FS.cwd();
4111
} else {
4112
var dirstream = FS.getStream(dirfd);
4113
if (!dirstream) throw new FS.ErrnoError(8);
4114
dir = dirstream.path;
4115
}
4116
path = PATH.join2(dir, path);
4117
}
4118
return path;
4119
},doStat:function(func, path, buf) {
4120
try {
4121
var stat = func(path);
4122
} catch (e) {
4123
if (e && e.node && PATH.normalize(path) !== PATH.normalize(FS.getPath(e.node))) {
4124
// an error occurred while trying to look up the path; we should just report ENOTDIR
4125
return -54;
4126
}
4127
throw e;
4128
}
4129
HEAP32[((buf)>>2)]=stat.dev;
4130
HEAP32[(((buf)+(4))>>2)]=0;
4131
HEAP32[(((buf)+(8))>>2)]=stat.ino;
4132
HEAP32[(((buf)+(12))>>2)]=stat.mode;
4133
HEAP32[(((buf)+(16))>>2)]=stat.nlink;
4134
HEAP32[(((buf)+(20))>>2)]=stat.uid;
4135
HEAP32[(((buf)+(24))>>2)]=stat.gid;
4136
HEAP32[(((buf)+(28))>>2)]=stat.rdev;
4137
HEAP32[(((buf)+(32))>>2)]=0;
4138
(tempI64 = [stat.size>>>0,(tempDouble=stat.size,(+(Math_abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? ((Math_min((+(Math_floor((tempDouble)/4294967296.0))), 4294967295.0))|0)>>>0 : (~~((+(Math_ceil((tempDouble - +(((~~(tempDouble)))>>>0))/4294967296.0)))))>>>0) : 0)],HEAP32[(((buf)+(40))>>2)]=tempI64[0],HEAP32[(((buf)+(44))>>2)]=tempI64[1]);
4139
HEAP32[(((buf)+(48))>>2)]=4096;
4140
HEAP32[(((buf)+(52))>>2)]=stat.blocks;
4141
HEAP32[(((buf)+(56))>>2)]=(stat.atime.getTime() / 1000)|0;
4142
HEAP32[(((buf)+(60))>>2)]=0;
4143
HEAP32[(((buf)+(64))>>2)]=(stat.mtime.getTime() / 1000)|0;
4144
HEAP32[(((buf)+(68))>>2)]=0;
4145
HEAP32[(((buf)+(72))>>2)]=(stat.ctime.getTime() / 1000)|0;
4146
HEAP32[(((buf)+(76))>>2)]=0;
4147
(tempI64 = [stat.ino>>>0,(tempDouble=stat.ino,(+(Math_abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? ((Math_min((+(Math_floor((tempDouble)/4294967296.0))), 4294967295.0))|0)>>>0 : (~~((+(Math_ceil((tempDouble - +(((~~(tempDouble)))>>>0))/4294967296.0)))))>>>0) : 0)],HEAP32[(((buf)+(80))>>2)]=tempI64[0],HEAP32[(((buf)+(84))>>2)]=tempI64[1]);
4148
return 0;
4149
},doMsync:function(addr, stream, len, flags, offset) {
4150
var buffer = HEAPU8.slice(addr, addr + len);
4151
FS.msync(stream, buffer, offset, len, flags);
4152
},doMkdir:function(path, mode) {
4153
// remove a trailing slash, if one - /a/b/ has basename of '', but
4154
// we want to create b in the context of this function
4155
path = PATH.normalize(path);
4156
if (path[path.length-1] === '/') path = path.substr(0, path.length-1);
4157
FS.mkdir(path, mode, 0);
4158
return 0;
4159
},doMknod:function(path, mode, dev) {
4160
// we don't want this in the JS API as it uses mknod to create all nodes.
4161
switch (mode & 61440) {
4162
case 32768:
4163
case 8192:
4164
case 24576:
4165
case 4096:
4166
case 49152:
4167
break;
4168
default: return -28;
4169
}
4170
FS.mknod(path, mode, dev);
4171
return 0;
4172
},doReadlink:function(path, buf, bufsize) {
4173
if (bufsize <= 0) return -28;
4174
var ret = FS.readlink(path);
4175
4176
var len = Math.min(bufsize, lengthBytesUTF8(ret));
4177
var endChar = HEAP8[buf+len];
4178
stringToUTF8(ret, buf, bufsize+1);
4179
// readlink is one of the rare functions that write out a C string, but does never append a null to the output buffer(!)
4180
// stringToUTF8() always appends a null byte, so restore the character under the null byte after the write.
4181
HEAP8[buf+len] = endChar;
4182
4183
return len;
4184
},doAccess:function(path, amode) {
4185
if (amode & ~7) {
4186
// need a valid mode
4187
return -28;
4188
}
4189
var node;
4190
var lookup = FS.lookupPath(path, { follow: true });
4191
node = lookup.node;
4192
if (!node) {
4193
return -44;
4194
}
4195
var perms = '';
4196
if (amode & 4) perms += 'r';
4197
if (amode & 2) perms += 'w';
4198
if (amode & 1) perms += 'x';
4199
if (perms /* otherwise, they've just passed F_OK */ && FS.nodePermissions(node, perms)) {
4200
return -2;
4201
}
4202
return 0;
4203
},doDup:function(path, flags, suggestFD) {
4204
var suggest = FS.getStream(suggestFD);
4205
if (suggest) FS.close(suggest);
4206
return FS.open(path, flags, 0, suggestFD, suggestFD).fd;
4207
},doReadv:function(stream, iov, iovcnt, offset) {
4208
var ret = 0;
4209
for (var i = 0; i < iovcnt; i++) {
4210
var ptr = HEAP32[(((iov)+(i*8))>>2)];
4211
var len = HEAP32[(((iov)+(i*8 + 4))>>2)];
4212
var curr = FS.read(stream, HEAP8,ptr, len, offset);
4213
if (curr < 0) return -1;
4214
ret += curr;
4215
if (curr < len) break; // nothing more to read
4216
}
4217
return ret;
4218
},doWritev:function(stream, iov, iovcnt, offset) {
4219
var ret = 0;
4220
for (var i = 0; i < iovcnt; i++) {
4221
var ptr = HEAP32[(((iov)+(i*8))>>2)];
4222
var len = HEAP32[(((iov)+(i*8 + 4))>>2)];
4223
var curr = FS.write(stream, HEAP8,ptr, len, offset);
4224
if (curr < 0) return -1;
4225
ret += curr;
4226
}
4227
return ret;
4228
},varargs:undefined,get:function() {
4229
assert(SYSCALLS.varargs != undefined);
4230
SYSCALLS.varargs += 4;
4231
var ret = HEAP32[(((SYSCALLS.varargs)-(4))>>2)];
4232
return ret;
4233
},getStr:function(ptr) {
4234
var ret = UTF8ToString(ptr);
4235
return ret;
4236
},getStreamFromFD:function(fd) {
4237
var stream = FS.getStream(fd);
4238
if (!stream) throw new FS.ErrnoError(8);
4239
return stream;
4240
},get64:function(low, high) {
4241
if (low >= 0) assert(high === 0);
4242
else assert(high === -1);
4243
return low;
4244
}};function ___syscall221(fd, cmd, varargs) {SYSCALLS.varargs = varargs;
4245
try {
4246
// fcntl64
4247
var stream = SYSCALLS.getStreamFromFD(fd);
4248
switch (cmd) {
4249
case 0: {
4250
var arg = SYSCALLS.get();
4251
if (arg < 0) {
4252
return -28;
4253
}
4254
var newStream;
4255
newStream = FS.open(stream.path, stream.flags, 0, arg);
4256
return newStream.fd;
4257
}
4258
case 1:
4259
case 2:
4260
return 0; // FD_CLOEXEC makes no sense for a single process.
4261
case 3:
4262
return stream.flags;
4263
case 4: {
4264
var arg = SYSCALLS.get();
4265
stream.flags |= arg;
4266
return 0;
4267
}
4268
case 12:
4269
/* case 12: Currently in musl F_GETLK64 has same value as F_GETLK, so omitted to avoid duplicate case blocks. If that changes, uncomment this */ {
4270
4271
var arg = SYSCALLS.get();
4272
var offset = 0;
4273
// We're always unlocked.
4274
HEAP16[(((arg)+(offset))>>1)]=2;
4275
return 0;
4276
}
4277
case 13:
4278
case 14:
4279
/* case 13: Currently in musl F_SETLK64 has same value as F_SETLK, so omitted to avoid duplicate case blocks. If that changes, uncomment this */
4280
/* case 14: Currently in musl F_SETLKW64 has same value as F_SETLKW, so omitted to avoid duplicate case blocks. If that changes, uncomment this */
4281
4282
4283
return 0; // Pretend that the locking is successful.
4284
case 16:
4285
case 8:
4286
return -28; // These are for sockets. We don't have them fully implemented yet.
4287
case 9:
4288
// musl trusts getown return values, due to a bug where they must be, as they overlap with errors. just return -1 here, so fnctl() returns that, and we set errno ourselves.
4289
___setErrNo(28);
4290
return -1;
4291
default: {
4292
return -28;
4293
}
4294
}
4295
} catch (e) {
4296
if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
4297
return -e.errno;
4298
}
4299
}
4300
4301
function ___syscall5(path, flags, varargs) {SYSCALLS.varargs = varargs;
4302
try {
4303
// open
4304
var pathname = SYSCALLS.getStr(path);
4305
var mode = SYSCALLS.get();
4306
var stream = FS.open(pathname, flags, mode);
4307
return stream.fd;
4308
} catch (e) {
4309
if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
4310
return -e.errno;
4311
}
4312
}
4313
4314
function ___syscall54(fd, op, varargs) {SYSCALLS.varargs = varargs;
4315
try {
4316
// ioctl
4317
var stream = SYSCALLS.getStreamFromFD(fd);
4318
switch (op) {
4319
case 21509:
4320
case 21505: {
4321
if (!stream.tty) return -59;
4322
return 0;
4323
}
4324
case 21510:
4325
case 21511:
4326
case 21512:
4327
case 21506:
4328
case 21507:
4329
case 21508: {
4330
if (!stream.tty) return -59;
4331
return 0; // no-op, not actually adjusting terminal settings
4332
}
4333
case 21519: {
4334
if (!stream.tty) return -59;
4335
var argp = SYSCALLS.get();
4336
HEAP32[((argp)>>2)]=0;
4337
return 0;
4338
}
4339
case 21520: {
4340
if (!stream.tty) return -59;
4341
return -28; // not supported
4342
}
4343
case 21531: {
4344
var argp = SYSCALLS.get();
4345
return FS.ioctl(stream, op, argp);
4346
}
4347
case 21523: {
4348
// TODO: in theory we should write to the winsize struct that gets
4349
// passed in, but for now musl doesn't read anything on it
4350
if (!stream.tty) return -59;
4351
return 0;
4352
}
4353
case 21524: {
4354
// TODO: technically, this ioctl call should change the window size.
4355
// but, since emscripten doesn't have any concept of a terminal window
4356
// yet, we'll just silently throw it away as we do TIOCGWINSZ
4357
if (!stream.tty) return -59;
4358
return 0;
4359
}
4360
default: abort('bad ioctl syscall ' + op);
4361
}
4362
} catch (e) {
4363
if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
4364
return -e.errno;
4365
}
4366
}
4367
4368
function _abort() {
4369
abort();
4370
}
4371
4372
function _atexit(func, arg) {
4373
warnOnce('atexit() called, but EXIT_RUNTIME is not set, so atexits() will not be called. set EXIT_RUNTIME to 1 (see the FAQ)');
4374
__ATEXIT__.unshift({ func: func, arg: arg });
4375
}
4376
4377
4378
var _emscripten_get_now;if (ENVIRONMENT_IS_NODE) {
4379
_emscripten_get_now = function() {
4380
var t = process['hrtime']();
4381
return t[0] * 1e3 + t[1] / 1e6;
4382
};
4383
} else if (typeof dateNow !== 'undefined') {
4384
_emscripten_get_now = dateNow;
4385
} else _emscripten_get_now = function() { return performance.now(); }
4386
;
4387
4388
var _emscripten_get_now_is_monotonic=true;;function _clock_gettime(clk_id, tp) {
4389
// int clock_gettime(clockid_t clk_id, struct timespec *tp);
4390
var now;
4391
if (clk_id === 0) {
4392
now = Date.now();
4393
} else if ((clk_id === 1 || clk_id === 4) && _emscripten_get_now_is_monotonic) {
4394
now = _emscripten_get_now();
4395
} else {
4396
___setErrNo(28);
4397
return -1;
4398
}
4399
HEAP32[((tp)>>2)]=(now/1000)|0; // seconds
4400
HEAP32[(((tp)+(4))>>2)]=((now % 1000)*1000*1000)|0; // nanoseconds
4401
return 0;
4402
}
4403
4404
function _dlclose(handle) {
4405
abort("To use dlopen, you need to use Emscripten's linking support, see https://github.com/emscripten-core/emscripten/wiki/Linking");
4406
}
4407
4408
function _dlerror() {
4409
abort("To use dlopen, you need to use Emscripten's linking support, see https://github.com/emscripten-core/emscripten/wiki/Linking");
4410
}
4411
4412
function _dlsym(handle, symbol) {
4413
abort("To use dlopen, you need to use Emscripten's linking support, see https://github.com/emscripten-core/emscripten/wiki/Linking");
4414
}
4415
4416
4417
4418
4419
4420
function _emscripten_set_main_loop_timing(mode, value) {
4421
Browser.mainLoop.timingMode = mode;
4422
Browser.mainLoop.timingValue = value;
4423
4424
if (!Browser.mainLoop.func) {
4425
console.error('emscripten_set_main_loop_timing: Cannot set timing mode for main loop since a main loop does not exist! Call emscripten_set_main_loop first to set one up.');
4426
return 1; // Return non-zero on failure, can't set timing mode when there is no main loop.
4427
}
4428
4429
if (mode == 0 /*EM_TIMING_SETTIMEOUT*/) {
4430
Browser.mainLoop.scheduler = function Browser_mainLoop_scheduler_setTimeout() {
4431
var timeUntilNextTick = Math.max(0, Browser.mainLoop.tickStartTime + value - _emscripten_get_now())|0;
4432
setTimeout(Browser.mainLoop.runner, timeUntilNextTick); // doing this each time means that on exception, we stop
4433
};
4434
Browser.mainLoop.method = 'timeout';
4435
} else if (mode == 1 /*EM_TIMING_RAF*/) {
4436
Browser.mainLoop.scheduler = function Browser_mainLoop_scheduler_rAF() {
4437
Browser.requestAnimationFrame(Browser.mainLoop.runner);
4438
};
4439
Browser.mainLoop.method = 'rAF';
4440
} else if (mode == 2 /*EM_TIMING_SETIMMEDIATE*/) {
4441
if (typeof setImmediate === 'undefined') {
4442
// Emulate setImmediate. (note: not a complete polyfill, we don't emulate clearImmediate() to keep code size to minimum, since not needed)
4443
var setImmediates = [];
4444
var emscriptenMainLoopMessageId = 'setimmediate';
4445
var Browser_setImmediate_messageHandler = function(event) {
4446
// When called in current thread or Worker, the main loop ID is structured slightly different to accommodate for --proxy-to-worker runtime listening to Worker events,
4447
// so check for both cases.
4448
if (event.data === emscriptenMainLoopMessageId || event.data.target === emscriptenMainLoopMessageId) {
4449
event.stopPropagation();
4450
setImmediates.shift()();
4451
}
4452
}
4453
addEventListener("message", Browser_setImmediate_messageHandler, true);
4454
setImmediate = /** @type{function(function(): ?, ...?): number} */(function Browser_emulated_setImmediate(func) {
4455
setImmediates.push(func);
4456
if (ENVIRONMENT_IS_WORKER) {
4457
if (Module['setImmediates'] === undefined) Module['setImmediates'] = [];
4458
Module['setImmediates'].push(func);
4459
postMessage({target: emscriptenMainLoopMessageId}); // In --proxy-to-worker, route the message via proxyClient.js
4460
} else postMessage(emscriptenMainLoopMessageId, "*"); // On the main thread, can just send the message to itself.
4461
})
4462
}
4463
Browser.mainLoop.scheduler = function Browser_mainLoop_scheduler_setImmediate() {
4464
setImmediate(Browser.mainLoop.runner);
4465
};
4466
Browser.mainLoop.method = 'immediate';
4467
}
4468
return 0;
4469
}/** @param {number|boolean=} noSetTiming */
4470
function _emscripten_set_main_loop(func, fps, simulateInfiniteLoop, arg, noSetTiming) {
4471
noExitRuntime = true;
4472
4473
assert(!Browser.mainLoop.func, 'emscripten_set_main_loop: there can only be one main loop function at once: call emscripten_cancel_main_loop to cancel the previous one before setting a new one with different parameters.');
4474
4475
Browser.mainLoop.func = func;
4476
Browser.mainLoop.arg = arg;
4477
4478
var browserIterationFunc;
4479
if (typeof arg !== 'undefined') {
4480
browserIterationFunc = function() {
4481
Module['dynCall_vi'](func, arg);
4482
};
4483
} else {
4484
browserIterationFunc = function() {
4485
Module['dynCall_v'](func);
4486
};
4487
}
4488
4489
var thisMainLoopId = Browser.mainLoop.currentlyRunningMainloop;
4490
4491
Browser.mainLoop.runner = function Browser_mainLoop_runner() {
4492
if (ABORT) return;
4493
if (Browser.mainLoop.queue.length > 0) {
4494
var start = Date.now();
4495
var blocker = Browser.mainLoop.queue.shift();
4496
blocker.func(blocker.arg);
4497
if (Browser.mainLoop.remainingBlockers) {
4498
var remaining = Browser.mainLoop.remainingBlockers;
4499
var next = remaining%1 == 0 ? remaining-1 : Math.floor(remaining);
4500
if (blocker.counted) {
4501
Browser.mainLoop.remainingBlockers = next;
4502
} else {
4503
// not counted, but move the progress along a tiny bit
4504
next = next + 0.5; // do not steal all the next one's progress
4505
Browser.mainLoop.remainingBlockers = (8*remaining + next)/9;
4506
}
4507
}
4508
console.log('main loop blocker "' + blocker.name + '" took ' + (Date.now() - start) + ' ms'); //, left: ' + Browser.mainLoop.remainingBlockers);
4509
Browser.mainLoop.updateStatus();
4510
4511
// catches pause/resume main loop from blocker execution
4512
if (thisMainLoopId < Browser.mainLoop.currentlyRunningMainloop) return;
4513
4514
setTimeout(Browser.mainLoop.runner, 0);
4515
return;
4516
}
4517
4518
// catch pauses from non-main loop sources
4519
if (thisMainLoopId < Browser.mainLoop.currentlyRunningMainloop) return;
4520
4521
// Implement very basic swap interval control
4522
Browser.mainLoop.currentFrameNumber = Browser.mainLoop.currentFrameNumber + 1 | 0;
4523
if (Browser.mainLoop.timingMode == 1/*EM_TIMING_RAF*/ && Browser.mainLoop.timingValue > 1 && Browser.mainLoop.currentFrameNumber % Browser.mainLoop.timingValue != 0) {
4524
// Not the scheduled time to render this frame - skip.
4525
Browser.mainLoop.scheduler();
4526
return;
4527
} else if (Browser.mainLoop.timingMode == 0/*EM_TIMING_SETTIMEOUT*/) {
4528
Browser.mainLoop.tickStartTime = _emscripten_get_now();
4529
}
4530
4531
// Signal GL rendering layer that processing of a new frame is about to start. This helps it optimize
4532
// VBO double-buffering and reduce GPU stalls.
4533
4534
4535
4536
if (Browser.mainLoop.method === 'timeout' && Module.ctx) {
4537
warnOnce('Looks like you are rendering without using requestAnimationFrame for the main loop. You should use 0 for the frame rate in emscripten_set_main_loop in order to use requestAnimationFrame, as that can greatly improve your frame rates!');
4538
Browser.mainLoop.method = ''; // just warn once per call to set main loop
4539
}
4540
4541
Browser.mainLoop.runIter(browserIterationFunc);
4542
4543
checkStackCookie();
4544
4545
// catch pauses from the main loop itself
4546
if (thisMainLoopId < Browser.mainLoop.currentlyRunningMainloop) return;
4547
4548
// Queue new audio data. This is important to be right after the main loop invocation, so that we will immediately be able
4549
// to queue the newest produced audio samples.
4550
// TODO: Consider adding pre- and post- rAF callbacks so that GL.newRenderingFrameStarted() and SDL.audio.queueNewAudioData()
4551
// do not need to be hardcoded into this function, but can be more generic.
4552
if (typeof SDL === 'object' && SDL.audio && SDL.audio.queueNewAudioData) SDL.audio.queueNewAudioData();
4553
4554
Browser.mainLoop.scheduler();
4555
}
4556
4557
if (!noSetTiming) {
4558
if (fps && fps > 0) _emscripten_set_main_loop_timing(0/*EM_TIMING_SETTIMEOUT*/, 1000.0 / fps);
4559
else _emscripten_set_main_loop_timing(1/*EM_TIMING_RAF*/, 1); // Do rAF by rendering each frame (no decimating)
4560
4561
Browser.mainLoop.scheduler();
4562
}
4563
4564
if (simulateInfiniteLoop) {
4565
throw 'unwind';
4566
}
4567
}var Browser={mainLoop:{scheduler:null,method:"",currentlyRunningMainloop:0,func:null,arg:0,timingMode:0,timingValue:0,currentFrameNumber:0,queue:[],pause:function() {
4568
Browser.mainLoop.scheduler = null;
4569
Browser.mainLoop.currentlyRunningMainloop++; // Incrementing this signals the previous main loop that it's now become old, and it must return.
4570
},resume:function() {
4571
Browser.mainLoop.currentlyRunningMainloop++;
4572
var timingMode = Browser.mainLoop.timingMode;
4573
var timingValue = Browser.mainLoop.timingValue;
4574
var func = Browser.mainLoop.func;
4575
Browser.mainLoop.func = null;
4576
_emscripten_set_main_loop(func, 0, false, Browser.mainLoop.arg, true /* do not set timing and call scheduler, we will do it on the next lines */);
4577
_emscripten_set_main_loop_timing(timingMode, timingValue);
4578
Browser.mainLoop.scheduler();
4579
},updateStatus:function() {
4580
if (Module['setStatus']) {
4581
var message = Module['statusMessage'] || 'Please wait...';
4582
var remaining = Browser.mainLoop.remainingBlockers;
4583
var expected = Browser.mainLoop.expectedBlockers;
4584
if (remaining) {
4585
if (remaining < expected) {
4586
Module['setStatus'](message + ' (' + (expected - remaining) + '/' + expected + ')');
4587
} else {
4588
Module['setStatus'](message);
4589
}
4590
} else {
4591
Module['setStatus']('');
4592
}
4593
}
4594
},runIter:function(func) {
4595
if (ABORT) return;
4596
if (Module['preMainLoop']) {
4597
var preRet = Module['preMainLoop']();
4598
if (preRet === false) {
4599
return; // |return false| skips a frame
4600
}
4601
}
4602
try {
4603
func();
4604
} catch (e) {
4605
if (e instanceof ExitStatus) {
4606
return;
4607
} else {
4608
if (e && typeof e === 'object' && e.stack) err('exception thrown: ' + [e, e.stack]);
4609
throw e;
4610
}
4611
}
4612
if (Module['postMainLoop']) Module['postMainLoop']();
4613
}},isFullscreen:false,pointerLock:false,moduleContextCreatedCallbacks:[],workers:[],init:function() {
4614
if (!Module["preloadPlugins"]) Module["preloadPlugins"] = []; // needs to exist even in workers
4615
4616
if (Browser.initted) return;
4617
Browser.initted = true;
4618
4619
try {
4620
new Blob();
4621
Browser.hasBlobConstructor = true;
4622
} catch(e) {
4623
Browser.hasBlobConstructor = false;
4624
console.log("warning: no blob constructor, cannot create blobs with mimetypes");
4625
}
4626
Browser.BlobBuilder = typeof MozBlobBuilder != "undefined" ? MozBlobBuilder : (typeof WebKitBlobBuilder != "undefined" ? WebKitBlobBuilder : (!Browser.hasBlobConstructor ? console.log("warning: no BlobBuilder") : null));
4627
Browser.URLObject = typeof window != "undefined" ? (window.URL ? window.URL : window.webkitURL) : undefined;
4628
if (!Module.noImageDecoding && typeof Browser.URLObject === 'undefined') {
4629
console.log("warning: Browser does not support creating object URLs. Built-in browser image decoding will not be available.");
4630
Module.noImageDecoding = true;
4631
}
4632
4633
// Support for plugins that can process preloaded files. You can add more of these to
4634
// your app by creating and appending to Module.preloadPlugins.
4635
//
4636
// Each plugin is asked if it can handle a file based on the file's name. If it can,
4637
// it is given the file's raw data. When it is done, it calls a callback with the file's
4638
// (possibly modified) data. For example, a plugin might decompress a file, or it
4639
// might create some side data structure for use later (like an Image element, etc.).
4640
4641
var imagePlugin = {};
4642
imagePlugin['canHandle'] = function imagePlugin_canHandle(name) {
4643
return !Module.noImageDecoding && /\.(jpg|jpeg|png|bmp)$/i.test(name);
4644
};
4645
imagePlugin['handle'] = function imagePlugin_handle(byteArray, name, onload, onerror) {
4646
var b = null;
4647
if (Browser.hasBlobConstructor) {
4648
try {
4649
b = new Blob([byteArray], { type: Browser.getMimetype(name) });
4650
if (b.size !== byteArray.length) { // Safari bug #118630
4651
// Safari's Blob can only take an ArrayBuffer
4652
b = new Blob([(new Uint8Array(byteArray)).buffer], { type: Browser.getMimetype(name) });
4653
}
4654
} catch(e) {
4655
warnOnce('Blob constructor present but fails: ' + e + '; falling back to blob builder');
4656
}
4657
}
4658
if (!b) {
4659
var bb = new Browser.BlobBuilder();
4660
bb.append((new Uint8Array(byteArray)).buffer); // we need to pass a buffer, and must copy the array to get the right data range
4661
b = bb.getBlob();
4662
}
4663
var url = Browser.URLObject.createObjectURL(b);
4664
assert(typeof url == 'string', 'createObjectURL must return a url as a string');
4665
var img = new Image();
4666
img.onload = function img_onload() {
4667
assert(img.complete, 'Image ' + name + ' could not be decoded');
4668
var canvas = document.createElement('canvas');
4669
canvas.width = img.width;
4670
canvas.height = img.height;
4671
var ctx = canvas.getContext('2d');
4672
ctx.drawImage(img, 0, 0);
4673
Module["preloadedImages"][name] = canvas;
4674
Browser.URLObject.revokeObjectURL(url);
4675
if (onload) onload(byteArray);
4676
};
4677
img.onerror = function img_onerror(event) {
4678
console.log('Image ' + url + ' could not be decoded');
4679
if (onerror) onerror();
4680
};
4681
img.src = url;
4682
};
4683
Module['preloadPlugins'].push(imagePlugin);
4684
4685
var audioPlugin = {};
4686
audioPlugin['canHandle'] = function audioPlugin_canHandle(name) {
4687
return !Module.noAudioDecoding && name.substr(-4) in { '.ogg': 1, '.wav': 1, '.mp3': 1 };
4688
};
4689
audioPlugin['handle'] = function audioPlugin_handle(byteArray, name, onload, onerror) {
4690
var done = false;
4691
function finish(audio) {
4692
if (done) return;
4693
done = true;
4694
Module["preloadedAudios"][name] = audio;
4695
if (onload) onload(byteArray);
4696
}
4697
function fail() {
4698
if (done) return;
4699
done = true;
4700
Module["preloadedAudios"][name] = new Audio(); // empty shim
4701
if (onerror) onerror();
4702
}
4703
if (Browser.hasBlobConstructor) {
4704
try {
4705
var b = new Blob([byteArray], { type: Browser.getMimetype(name) });
4706
} catch(e) {
4707
return fail();
4708
}
4709
var url = Browser.URLObject.createObjectURL(b); // XXX we never revoke this!
4710
assert(typeof url == 'string', 'createObjectURL must return a url as a string');
4711
var audio = new Audio();
4712
audio.addEventListener('canplaythrough', function() { finish(audio) }, false); // use addEventListener due to chromium bug 124926
4713
audio.onerror = function audio_onerror(event) {
4714
if (done) return;
4715
console.log('warning: browser could not fully decode audio ' + name + ', trying slower base64 approach');
4716
function encode64(data) {
4717
var BASE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
4718
var PAD = '=';
4719
var ret = '';
4720
var leftchar = 0;
4721
var leftbits = 0;
4722
for (var i = 0; i < data.length; i++) {
4723
leftchar = (leftchar << 8) | data[i];
4724
leftbits += 8;
4725
while (leftbits >= 6) {
4726
var curr = (leftchar >> (leftbits-6)) & 0x3f;
4727
leftbits -= 6;
4728
ret += BASE[curr];
4729
}
4730
}
4731
if (leftbits == 2) {
4732
ret += BASE[(leftchar&3) << 4];
4733
ret += PAD + PAD;
4734
} else if (leftbits == 4) {
4735
ret += BASE[(leftchar&0xf) << 2];
4736
ret += PAD;
4737
}
4738
return ret;
4739
}
4740
audio.src = 'data:audio/x-' + name.substr(-3) + ';base64,' + encode64(byteArray);
4741
finish(audio); // we don't wait for confirmation this worked - but it's worth trying
4742
};
4743
audio.src = url;
4744
// workaround for chrome bug 124926 - we do not always get oncanplaythrough or onerror
4745
Browser.safeSetTimeout(function() {
4746
finish(audio); // try to use it even though it is not necessarily ready to play
4747
}, 10000);
4748
} else {
4749
return fail();
4750
}
4751
};
4752
Module['preloadPlugins'].push(audioPlugin);
4753
4754
4755
// Canvas event setup
4756
4757
function pointerLockChange() {
4758
Browser.pointerLock = document['pointerLockElement'] === Module['canvas'] ||
4759
document['mozPointerLockElement'] === Module['canvas'] ||
4760
document['webkitPointerLockElement'] === Module['canvas'] ||
4761
document['msPointerLockElement'] === Module['canvas'];
4762
}
4763
var canvas = Module['canvas'];
4764
if (canvas) {
4765
// forced aspect ratio can be enabled by defining 'forcedAspectRatio' on Module
4766
// Module['forcedAspectRatio'] = 4 / 3;
4767
4768
canvas.requestPointerLock = canvas['requestPointerLock'] ||
4769
canvas['mozRequestPointerLock'] ||
4770
canvas['webkitRequestPointerLock'] ||
4771
canvas['msRequestPointerLock'] ||
4772
function(){};
4773
canvas.exitPointerLock = document['exitPointerLock'] ||
4774
document['mozExitPointerLock'] ||
4775
document['webkitExitPointerLock'] ||
4776
document['msExitPointerLock'] ||
4777
function(){}; // no-op if function does not exist
4778
canvas.exitPointerLock = canvas.exitPointerLock.bind(document);
4779
4780
document.addEventListener('pointerlockchange', pointerLockChange, false);
4781
document.addEventListener('mozpointerlockchange', pointerLockChange, false);
4782
document.addEventListener('webkitpointerlockchange', pointerLockChange, false);
4783
document.addEventListener('mspointerlockchange', pointerLockChange, false);
4784
4785
if (Module['elementPointerLock']) {
4786
canvas.addEventListener("click", function(ev) {
4787
if (!Browser.pointerLock && Module['canvas'].requestPointerLock) {
4788
Module['canvas'].requestPointerLock();
4789
ev.preventDefault();
4790
}
4791
}, false);
4792
}
4793
}
4794
},createContext:function(canvas, useWebGL, setInModule, webGLContextAttributes) {
4795
if (useWebGL && Module.ctx && canvas == Module.canvas) return Module.ctx; // no need to recreate GL context if it's already been created for this canvas.
4796
4797
var ctx;
4798
var contextHandle;
4799
if (useWebGL) {
4800
// For GLES2/desktop GL compatibility, adjust a few defaults to be different to WebGL defaults, so that they align better with the desktop defaults.
4801
var contextAttributes = {
4802
antialias: false,
4803
alpha: false,
4804
majorVersion: 1,
4805
};
4806
4807
if (webGLContextAttributes) {
4808
for (var attribute in webGLContextAttributes) {
4809
contextAttributes[attribute] = webGLContextAttributes[attribute];
4810
}
4811
}
4812
4813
// This check of existence of GL is here to satisfy Closure compiler, which yells if variable GL is referenced below but GL object is not
4814
// actually compiled in because application is not doing any GL operations. TODO: Ideally if GL is not being used, this function
4815
// Browser.createContext() should not even be emitted.
4816
if (typeof GL !== 'undefined') {
4817
contextHandle = GL.createContext(canvas, contextAttributes);
4818
if (contextHandle) {
4819
ctx = GL.getContext(contextHandle).GLctx;
4820
}
4821
}
4822
} else {
4823
ctx = canvas.getContext('2d');
4824
}
4825
4826
if (!ctx) return null;
4827
4828
if (setInModule) {
4829
if (!useWebGL) assert(typeof GLctx === 'undefined', 'cannot set in module if GLctx is used, but we are a non-GL context that would replace it');
4830
4831
Module.ctx = ctx;
4832
if (useWebGL) GL.makeContextCurrent(contextHandle);
4833
Module.useWebGL = useWebGL;
4834
Browser.moduleContextCreatedCallbacks.forEach(function(callback) { callback() });
4835
Browser.init();
4836
}
4837
return ctx;
4838
},destroyContext:function(canvas, useWebGL, setInModule) {},fullscreenHandlersInstalled:false,lockPointer:undefined,resizeCanvas:undefined,requestFullscreen:function(lockPointer, resizeCanvas) {
4839
Browser.lockPointer = lockPointer;
4840
Browser.resizeCanvas = resizeCanvas;
4841
if (typeof Browser.lockPointer === 'undefined') Browser.lockPointer = true;
4842
if (typeof Browser.resizeCanvas === 'undefined') Browser.resizeCanvas = false;
4843
4844
var canvas = Module['canvas'];
4845
function fullscreenChange() {
4846
Browser.isFullscreen = false;
4847
var canvasContainer = canvas.parentNode;
4848
if ((document['fullscreenElement'] || document['mozFullScreenElement'] ||
4849
document['msFullscreenElement'] || document['webkitFullscreenElement'] ||
4850
document['webkitCurrentFullScreenElement']) === canvasContainer) {
4851
canvas.exitFullscreen = Browser.exitFullscreen;
4852
if (Browser.lockPointer) canvas.requestPointerLock();
4853
Browser.isFullscreen = true;
4854
if (Browser.resizeCanvas) {
4855
Browser.setFullscreenCanvasSize();
4856
} else {
4857
Browser.updateCanvasDimensions(canvas);
4858
}
4859
} else {
4860
// remove the full screen specific parent of the canvas again to restore the HTML structure from before going full screen
4861
canvasContainer.parentNode.insertBefore(canvas, canvasContainer);
4862
canvasContainer.parentNode.removeChild(canvasContainer);
4863
4864
if (Browser.resizeCanvas) {
4865
Browser.setWindowedCanvasSize();
4866
} else {
4867
Browser.updateCanvasDimensions(canvas);
4868
}
4869
}
4870
if (Module['onFullScreen']) Module['onFullScreen'](Browser.isFullscreen);
4871
if (Module['onFullscreen']) Module['onFullscreen'](Browser.isFullscreen);
4872
}
4873
4874
if (!Browser.fullscreenHandlersInstalled) {
4875
Browser.fullscreenHandlersInstalled = true;
4876
document.addEventListener('fullscreenchange', fullscreenChange, false);
4877
document.addEventListener('mozfullscreenchange', fullscreenChange, false);
4878
document.addEventListener('webkitfullscreenchange', fullscreenChange, false);
4879
document.addEventListener('MSFullscreenChange', fullscreenChange, false);
4880
}
4881
4882
// create a new parent to ensure the canvas has no siblings. this allows browsers to optimize full screen performance when its parent is the full screen root
4883
var canvasContainer = document.createElement("div");
4884
canvas.parentNode.insertBefore(canvasContainer, canvas);
4885
canvasContainer.appendChild(canvas);
4886
4887
// use parent of canvas as full screen root to allow aspect ratio correction (Firefox stretches the root to screen size)
4888
canvasContainer.requestFullscreen = canvasContainer['requestFullscreen'] ||
4889
canvasContainer['mozRequestFullScreen'] ||
4890
canvasContainer['msRequestFullscreen'] ||
4891
(canvasContainer['webkitRequestFullscreen'] ? function() { canvasContainer['webkitRequestFullscreen'](Element['ALLOW_KEYBOARD_INPUT']) } : null) ||
4892
(canvasContainer['webkitRequestFullScreen'] ? function() { canvasContainer['webkitRequestFullScreen'](Element['ALLOW_KEYBOARD_INPUT']) } : null);
4893
4894
canvasContainer.requestFullscreen();
4895
},requestFullScreen:function() {
4896
abort('Module.requestFullScreen has been replaced by Module.requestFullscreen (without a capital S)');
4897
},exitFullscreen:function() {
4898
// This is workaround for chrome. Trying to exit from fullscreen
4899
// not in fullscreen state will cause "TypeError: Document not active"
4900
// in chrome. See https://github.com/emscripten-core/emscripten/pull/8236
4901
if (!Browser.isFullscreen) {
4902
return false;
4903
}
4904
4905
var CFS = document['exitFullscreen'] ||
4906
document['cancelFullScreen'] ||
4907
document['mozCancelFullScreen'] ||
4908
document['msExitFullscreen'] ||
4909
document['webkitCancelFullScreen'] ||
4910
(function() {});
4911
CFS.apply(document, []);
4912
return true;
4913
},nextRAF:0,fakeRequestAnimationFrame:function(func) {
4914
// try to keep 60fps between calls to here
4915
var now = Date.now();
4916
if (Browser.nextRAF === 0) {
4917
Browser.nextRAF = now + 1000/60;
4918
} else {
4919
while (now + 2 >= Browser.nextRAF) { // fudge a little, to avoid timer jitter causing us to do lots of delay:0
4920
Browser.nextRAF += 1000/60;
4921
}
4922
}
4923
var delay = Math.max(Browser.nextRAF - now, 0);
4924
setTimeout(func, delay);
4925
},requestAnimationFrame:function(func) {
4926
if (typeof requestAnimationFrame === 'function') {
4927
requestAnimationFrame(func);
4928
return;
4929
}
4930
var RAF = Browser.fakeRequestAnimationFrame;
4931
RAF(func);
4932
},safeCallback:function(func) {
4933
return function() {
4934
if (!ABORT) return func.apply(null, arguments);
4935
};
4936
},allowAsyncCallbacks:true,queuedAsyncCallbacks:[],pauseAsyncCallbacks:function() {
4937
Browser.allowAsyncCallbacks = false;
4938
},resumeAsyncCallbacks:function() { // marks future callbacks as ok to execute, and synchronously runs any remaining ones right now
4939
Browser.allowAsyncCallbacks = true;
4940
if (Browser.queuedAsyncCallbacks.length > 0) {
4941
var callbacks = Browser.queuedAsyncCallbacks;
4942
Browser.queuedAsyncCallbacks = [];
4943
callbacks.forEach(function(func) {
4944
func();
4945
});
4946
}
4947
},safeRequestAnimationFrame:function(func) {
4948
return Browser.requestAnimationFrame(function() {
4949
if (ABORT) return;
4950
if (Browser.allowAsyncCallbacks) {
4951
func();
4952
} else {
4953
Browser.queuedAsyncCallbacks.push(func);
4954
}
4955
});
4956
},safeSetTimeout:function(func, timeout) {
4957
noExitRuntime = true;
4958
return setTimeout(function() {
4959
if (ABORT) return;
4960
if (Browser.allowAsyncCallbacks) {
4961
func();
4962
} else {
4963
Browser.queuedAsyncCallbacks.push(func);
4964
}
4965
}, timeout);
4966
},safeSetInterval:function(func, timeout) {
4967
noExitRuntime = true;
4968
return setInterval(function() {
4969
if (ABORT) return;
4970
if (Browser.allowAsyncCallbacks) {
4971
func();
4972
} // drop it on the floor otherwise, next interval will kick in
4973
}, timeout);
4974
},getMimetype:function(name) {
4975
return {
4976
'jpg': 'image/jpeg',
4977
'jpeg': 'image/jpeg',
4978
'png': 'image/png',
4979
'bmp': 'image/bmp',
4980
'ogg': 'audio/ogg',
4981
'wav': 'audio/wav',
4982
'mp3': 'audio/mpeg'
4983
}[name.substr(name.lastIndexOf('.')+1)];
4984
},getUserMedia:function(func) {
4985
if(!window.getUserMedia) {
4986
window.getUserMedia = navigator['getUserMedia'] ||
4987
navigator['mozGetUserMedia'];
4988
}
4989
window.getUserMedia(func);
4990
},getMovementX:function(event) {
4991
return event['movementX'] ||
4992
event['mozMovementX'] ||
4993
event['webkitMovementX'] ||
4994
0;
4995
},getMovementY:function(event) {
4996
return event['movementY'] ||
4997
event['mozMovementY'] ||
4998
event['webkitMovementY'] ||
4999
0;
5000
},getMouseWheelDelta:function(event) {
5001
var delta = 0;
5002
switch (event.type) {
5003
case 'DOMMouseScroll':
5004
// 3 lines make up a step
5005
delta = event.detail / 3;
5006
break;
5007
case 'mousewheel':
5008
// 120 units make up a step
5009
delta = event.wheelDelta / 120;
5010
break;
5011
case 'wheel':
5012
delta = event.deltaY
5013
switch(event.deltaMode) {
5014
case 0:
5015
// DOM_DELTA_PIXEL: 100 pixels make up a step
5016
delta /= 100;
5017
break;
5018
case 1:
5019
// DOM_DELTA_LINE: 3 lines make up a step
5020
delta /= 3;
5021
break;
5022
case 2:
5023
// DOM_DELTA_PAGE: A page makes up 80 steps
5024
delta *= 80;
5025
break;
5026
default:
5027
throw 'unrecognized mouse wheel delta mode: ' + event.deltaMode;
5028
}
5029
break;
5030
default:
5031
throw 'unrecognized mouse wheel event: ' + event.type;
5032
}
5033
return delta;
5034
},mouseX:0,mouseY:0,mouseMovementX:0,mouseMovementY:0,touches:{},lastTouches:{},calculateMouseEvent:function(event) { // event should be mousemove, mousedown or mouseup
5035
if (Browser.pointerLock) {
5036
// When the pointer is locked, calculate the coordinates
5037
// based on the movement of the mouse.
5038
// Workaround for Firefox bug 764498
5039
if (event.type != 'mousemove' &&
5040
('mozMovementX' in event)) {
5041
Browser.mouseMovementX = Browser.mouseMovementY = 0;
5042
} else {
5043
Browser.mouseMovementX = Browser.getMovementX(event);
5044
Browser.mouseMovementY = Browser.getMovementY(event);
5045
}
5046
5047
// check if SDL is available
5048
if (typeof SDL != "undefined") {
5049
Browser.mouseX = SDL.mouseX + Browser.mouseMovementX;
5050
Browser.mouseY = SDL.mouseY + Browser.mouseMovementY;
5051
} else {
5052
// just add the mouse delta to the current absolut mouse position
5053
// FIXME: ideally this should be clamped against the canvas size and zero
5054
Browser.mouseX += Browser.mouseMovementX;
5055
Browser.mouseY += Browser.mouseMovementY;
5056
}
5057
} else {
5058
// Otherwise, calculate the movement based on the changes
5059
// in the coordinates.
5060
var rect = Module["canvas"].getBoundingClientRect();
5061
var cw = Module["canvas"].width;
5062
var ch = Module["canvas"].height;
5063
5064
// Neither .scrollX or .pageXOffset are defined in a spec, but
5065
// we prefer .scrollX because it is currently in a spec draft.
5066
// (see: http://www.w3.org/TR/2013/WD-cssom-view-20131217/)
5067
var scrollX = ((typeof window.scrollX !== 'undefined') ? window.scrollX : window.pageXOffset);
5068
var scrollY = ((typeof window.scrollY !== 'undefined') ? window.scrollY : window.pageYOffset);
5069
// If this assert lands, it's likely because the browser doesn't support scrollX or pageXOffset
5070
// and we have no viable fallback.
5071
assert((typeof scrollX !== 'undefined') && (typeof scrollY !== 'undefined'), 'Unable to retrieve scroll position, mouse positions likely broken.');
5072
5073
if (event.type === 'touchstart' || event.type === 'touchend' || event.type === 'touchmove') {
5074
var touch = event.touch;
5075
if (touch === undefined) {
5076
return; // the "touch" property is only defined in SDL
5077
5078
}
5079
var adjustedX = touch.pageX - (scrollX + rect.left);
5080
var adjustedY = touch.pageY - (scrollY + rect.top);
5081
5082
adjustedX = adjustedX * (cw / rect.width);
5083
adjustedY = adjustedY * (ch / rect.height);
5084
5085
var coords = { x: adjustedX, y: adjustedY };
5086
5087
if (event.type === 'touchstart') {
5088
Browser.lastTouches[touch.identifier] = coords;
5089
Browser.touches[touch.identifier] = coords;
5090
} else if (event.type === 'touchend' || event.type === 'touchmove') {
5091
var last = Browser.touches[touch.identifier];
5092
if (!last) last = coords;
5093
Browser.lastTouches[touch.identifier] = last;
5094
Browser.touches[touch.identifier] = coords;
5095
}
5096
return;
5097
}
5098
5099
var x = event.pageX - (scrollX + rect.left);
5100
var y = event.pageY - (scrollY + rect.top);
5101
5102
// the canvas might be CSS-scaled compared to its backbuffer;
5103
// SDL-using content will want mouse coordinates in terms
5104
// of backbuffer units.
5105
x = x * (cw / rect.width);
5106
y = y * (ch / rect.height);
5107
5108
Browser.mouseMovementX = x - Browser.mouseX;
5109
Browser.mouseMovementY = y - Browser.mouseY;
5110
Browser.mouseX = x;
5111
Browser.mouseY = y;
5112
}
5113
},asyncLoad:function(url, onload, onerror, noRunDep) {
5114
var dep = !noRunDep ? getUniqueRunDependency('al ' + url) : '';
5115
readAsync(url, function(arrayBuffer) {
5116
assert(arrayBuffer, 'Loading data file "' + url + '" failed (no arrayBuffer).');
5117
onload(new Uint8Array(arrayBuffer));
5118
if (dep) removeRunDependency(dep);
5119
}, function(event) {
5120
if (onerror) {
5121
onerror();
5122
} else {
5123
throw 'Loading data file "' + url + '" failed.';
5124
}
5125
});
5126
if (dep) addRunDependency(dep);
5127
},resizeListeners:[],updateResizeListeners:function() {
5128
var canvas = Module['canvas'];
5129
Browser.resizeListeners.forEach(function(listener) {
5130
listener(canvas.width, canvas.height);
5131
});
5132
},setCanvasSize:function(width, height, noUpdates) {
5133
var canvas = Module['canvas'];
5134
Browser.updateCanvasDimensions(canvas, width, height);
5135
if (!noUpdates) Browser.updateResizeListeners();
5136
},windowedWidth:0,windowedHeight:0,setFullscreenCanvasSize:function() {
5137
// check if SDL is available
5138
if (typeof SDL != "undefined") {
5139
var flags = HEAPU32[((SDL.screen)>>2)];
5140
flags = flags | 0x00800000; // set SDL_FULLSCREEN flag
5141
HEAP32[((SDL.screen)>>2)]=flags
5142
}
5143
Browser.updateCanvasDimensions(Module['canvas']);
5144
Browser.updateResizeListeners();
5145
},setWindowedCanvasSize:function() {
5146
// check if SDL is available
5147
if (typeof SDL != "undefined") {
5148
var flags = HEAPU32[((SDL.screen)>>2)];
5149
flags = flags & ~0x00800000; // clear SDL_FULLSCREEN flag
5150
HEAP32[((SDL.screen)>>2)]=flags
5151
}
5152
Browser.updateCanvasDimensions(Module['canvas']);
5153
Browser.updateResizeListeners();
5154
},updateCanvasDimensions:function(canvas, wNative, hNative) {
5155
if (wNative && hNative) {
5156
canvas.widthNative = wNative;
5157
canvas.heightNative = hNative;
5158
} else {
5159
wNative = canvas.widthNative;
5160
hNative = canvas.heightNative;
5161
}
5162
var w = wNative;
5163
var h = hNative;
5164
if (Module['forcedAspectRatio'] && Module['forcedAspectRatio'] > 0) {
5165
if (w/h < Module['forcedAspectRatio']) {
5166
w = Math.round(h * Module['forcedAspectRatio']);
5167
} else {
5168
h = Math.round(w / Module['forcedAspectRatio']);
5169
}
5170
}
5171
if (((document['fullscreenElement'] || document['mozFullScreenElement'] ||
5172
document['msFullscreenElement'] || document['webkitFullscreenElement'] ||
5173
document['webkitCurrentFullScreenElement']) === canvas.parentNode) && (typeof screen != 'undefined')) {
5174
var factor = Math.min(screen.width / w, screen.height / h);
5175
w = Math.round(w * factor);
5176
h = Math.round(h * factor);
5177
}
5178
if (Browser.resizeCanvas) {
5179
if (canvas.width != w) canvas.width = w;
5180
if (canvas.height != h) canvas.height = h;
5181
if (typeof canvas.style != 'undefined') {
5182
canvas.style.removeProperty( "width");
5183
canvas.style.removeProperty("height");
5184
}
5185
} else {
5186
if (canvas.width != wNative) canvas.width = wNative;
5187
if (canvas.height != hNative) canvas.height = hNative;
5188
if (typeof canvas.style != 'undefined') {
5189
if (w != wNative || h != hNative) {
5190
canvas.style.setProperty( "width", w + "px", "important");
5191
canvas.style.setProperty("height", h + "px", "important");
5192
} else {
5193
canvas.style.removeProperty( "width");
5194
canvas.style.removeProperty("height");
5195
}
5196
}
5197
}
5198
},wgetRequests:{},nextWgetRequestHandle:0,getNextWgetRequestHandle:function() {
5199
var handle = Browser.nextWgetRequestHandle;
5200
Browser.nextWgetRequestHandle++;
5201
return handle;
5202
}};var EGL={errorCode:12288,defaultDisplayInitialized:false,currentContext:0,currentReadSurface:0,currentDrawSurface:0,contextAttributes:{alpha:false,depth:false,stencil:false,antialias:false},stringCache:{},setErrorCode:function(code) {
5203
EGL.errorCode = code;
5204
},chooseConfig:function(display, attribList, config, config_size, numConfigs) {
5205
if (display != 62000 /* Magic ID for Emscripten 'default display' */) {
5206
EGL.setErrorCode(0x3008 /* EGL_BAD_DISPLAY */);
5207
return 0;
5208
}
5209
5210
if (attribList) {
5211
// read attribList if it is non-null
5212
for(;;) {
5213
var param = HEAP32[((attribList)>>2)];
5214
if (param == 0x3021 /*EGL_ALPHA_SIZE*/) {
5215
var alphaSize = HEAP32[(((attribList)+(4))>>2)];
5216
EGL.contextAttributes.alpha = (alphaSize > 0);
5217
} else if (param == 0x3025 /*EGL_DEPTH_SIZE*/) {
5218
var depthSize = HEAP32[(((attribList)+(4))>>2)];
5219
EGL.contextAttributes.depth = (depthSize > 0);
5220
} else if (param == 0x3026 /*EGL_STENCIL_SIZE*/) {
5221
var stencilSize = HEAP32[(((attribList)+(4))>>2)];
5222
EGL.contextAttributes.stencil = (stencilSize > 0);
5223
} else if (param == 0x3031 /*EGL_SAMPLES*/) {
5224
var samples = HEAP32[(((attribList)+(4))>>2)];
5225
EGL.contextAttributes.antialias = (samples > 0);
5226
} else if (param == 0x3032 /*EGL_SAMPLE_BUFFERS*/) {
5227
var samples = HEAP32[(((attribList)+(4))>>2)];
5228
EGL.contextAttributes.antialias = (samples == 1);
5229
} else if (param == 0x3100 /*EGL_CONTEXT_PRIORITY_LEVEL_IMG*/) {
5230
var requestedPriority = HEAP32[(((attribList)+(4))>>2)];
5231
EGL.contextAttributes.lowLatency = (requestedPriority != 0x3103 /*EGL_CONTEXT_PRIORITY_LOW_IMG*/);
5232
} else if (param == 0x3038 /*EGL_NONE*/) {
5233
break;
5234
}
5235
attribList += 8;
5236
}
5237
}
5238
5239
if ((!config || !config_size) && !numConfigs) {
5240
EGL.setErrorCode(0x300C /* EGL_BAD_PARAMETER */);
5241
return 0;
5242
}
5243
if (numConfigs) {
5244
HEAP32[((numConfigs)>>2)]=1; // Total number of supported configs: 1.
5245
}
5246
if (config && config_size > 0) {
5247
HEAP32[((config)>>2)]=62002;
5248
}
5249
5250
EGL.setErrorCode(0x3000 /* EGL_SUCCESS */);
5251
return 1;
5252
}};function _eglBindAPI(api) {
5253
if (api == 0x30A0 /* EGL_OPENGL_ES_API */) {
5254
EGL.setErrorCode(0x3000 /* EGL_SUCCESS */);
5255
return 1;
5256
} else { // if (api == 0x30A1 /* EGL_OPENVG_API */ || api == 0x30A2 /* EGL_OPENGL_API */) {
5257
EGL.setErrorCode(0x300C /* EGL_BAD_PARAMETER */);
5258
return 0;
5259
}
5260
}
5261
5262
function _eglChooseConfig(display, attrib_list, configs, config_size, numConfigs) {
5263
return EGL.chooseConfig(display, attrib_list, configs, config_size, numConfigs);
5264
}
5265
5266
5267
5268
function __webgl_acquireInstancedArraysExtension(ctx) {
5269
// Extension available in WebGL 1 from Firefox 26 and Google Chrome 30 onwards. Core feature in WebGL 2.
5270
var ext = ctx.getExtension('ANGLE_instanced_arrays');
5271
if (ext) {
5272
ctx['vertexAttribDivisor'] = function(index, divisor) { ext['vertexAttribDivisorANGLE'](index, divisor); };
5273
ctx['drawArraysInstanced'] = function(mode, first, count, primcount) { ext['drawArraysInstancedANGLE'](mode, first, count, primcount); };
5274
ctx['drawElementsInstanced'] = function(mode, count, type, indices, primcount) { ext['drawElementsInstancedANGLE'](mode, count, type, indices, primcount); };
5275
}
5276
}
5277
5278
function __webgl_acquireVertexArrayObjectExtension(ctx) {
5279
// Extension available in WebGL 1 from Firefox 25 and WebKit 536.28/desktop Safari 6.0.3 onwards. Core feature in WebGL 2.
5280
var ext = ctx.getExtension('OES_vertex_array_object');
5281
if (ext) {
5282
ctx['createVertexArray'] = function() { return ext['createVertexArrayOES'](); };
5283
ctx['deleteVertexArray'] = function(vao) { ext['deleteVertexArrayOES'](vao); };
5284
ctx['bindVertexArray'] = function(vao) { ext['bindVertexArrayOES'](vao); };
5285
ctx['isVertexArray'] = function(vao) { return ext['isVertexArrayOES'](vao); };
5286
}
5287
}
5288
5289
function __webgl_acquireDrawBuffersExtension(ctx) {
5290
// Extension available in WebGL 1 from Firefox 28 onwards. Core feature in WebGL 2.
5291
var ext = ctx.getExtension('WEBGL_draw_buffers');
5292
if (ext) {
5293
ctx['drawBuffers'] = function(n, bufs) { ext['drawBuffersWEBGL'](n, bufs); };
5294
}
5295
}var GL={counter:1,lastError:0,buffers:[],mappedBuffers:{},programs:[],framebuffers:[],renderbuffers:[],textures:[],uniforms:[],shaders:[],vaos:[],contexts:{},currentContext:null,offscreenCanvases:{},timerQueriesEXT:[],programInfos:{},stringCache:{},unpackAlignment:4,init:function() {
5296
var miniTempFloatBuffer = new Float32Array(GL.MINI_TEMP_BUFFER_SIZE);
5297
for (var i = 0; i < GL.MINI_TEMP_BUFFER_SIZE; i++) {
5298
GL.miniTempBufferFloatViews[i] = miniTempFloatBuffer.subarray(0, i+1);
5299
}
5300
5301
var miniTempIntBuffer = new Int32Array(GL.MINI_TEMP_BUFFER_SIZE);
5302
for (var i = 0; i < GL.MINI_TEMP_BUFFER_SIZE; i++) {
5303
GL.miniTempBufferIntViews[i] = miniTempIntBuffer.subarray(0, i+1);
5304
}
5305
},recordError:function recordError(errorCode) {
5306
if (!GL.lastError) {
5307
GL.lastError = errorCode;
5308
}
5309
},getNewId:function(table) {
5310
var ret = GL.counter++;
5311
for (var i = table.length; i < ret; i++) {
5312
table[i] = null;
5313
}
5314
return ret;
5315
},MINI_TEMP_BUFFER_SIZE:256,miniTempBufferFloatViews:[0],miniTempBufferIntViews:[0],getSource:function(shader, count, string, length) {
5316
var source = '';
5317
for (var i = 0; i < count; ++i) {
5318
var len = length ? HEAP32[(((length)+(i*4))>>2)] : -1;
5319
source += UTF8ToString(HEAP32[(((string)+(i*4))>>2)], len < 0 ? undefined : len);
5320
}
5321
return source;
5322
},createContext:function(canvas, webGLContextAttributes) {
5323
5324
5325
5326
5327
5328
var ctx =
5329
(canvas.getContext("webgl", webGLContextAttributes)
5330
// https://caniuse.com/#feat=webgl
5331
);
5332
5333
5334
if (!ctx) return 0;
5335
5336
var handle = GL.registerContext(ctx, webGLContextAttributes);
5337
5338
5339
5340
return handle;
5341
},registerContext:function(ctx, webGLContextAttributes) {
5342
var handle = _malloc(8); // Make space on the heap to store GL context attributes that need to be accessible as shared between threads.
5343
var context = {
5344
handle: handle,
5345
attributes: webGLContextAttributes,
5346
version: webGLContextAttributes.majorVersion,
5347
GLctx: ctx
5348
};
5349
5350
5351
// Store the created context object so that we can access the context given a canvas without having to pass the parameters again.
5352
if (ctx.canvas) ctx.canvas.GLctxObject = context;
5353
GL.contexts[handle] = context;
5354
if (typeof webGLContextAttributes.enableExtensionsByDefault === 'undefined' || webGLContextAttributes.enableExtensionsByDefault) {
5355
GL.initExtensions(context);
5356
}
5357
5358
5359
5360
5361
return handle;
5362
},makeContextCurrent:function(contextHandle) {
5363
5364
GL.currentContext = GL.contexts[contextHandle]; // Active Emscripten GL layer context object.
5365
Module.ctx = GLctx = GL.currentContext && GL.currentContext.GLctx; // Active WebGL context object.
5366
return !(contextHandle && !GLctx);
5367
},getContext:function(contextHandle) {
5368
return GL.contexts[contextHandle];
5369
},deleteContext:function(contextHandle) {
5370
if (GL.currentContext === GL.contexts[contextHandle]) GL.currentContext = null;
5371
if (typeof JSEvents === 'object') JSEvents.removeAllHandlersOnTarget(GL.contexts[contextHandle].GLctx.canvas); // Release all JS event handlers on the DOM element that the GL context is associated with since the context is now deleted.
5372
if (GL.contexts[contextHandle] && GL.contexts[contextHandle].GLctx.canvas) GL.contexts[contextHandle].GLctx.canvas.GLctxObject = undefined; // Make sure the canvas object no longer refers to the context object so there are no GC surprises.
5373
_free(GL.contexts[contextHandle].handle);
5374
GL.contexts[contextHandle] = null;
5375
},initExtensions:function(context) {
5376
// If this function is called without a specific context object, init the extensions of the currently active context.
5377
if (!context) context = GL.currentContext;
5378
5379
if (context.initExtensionsDone) return;
5380
context.initExtensionsDone = true;
5381
5382
var GLctx = context.GLctx;
5383
5384
// Detect the presence of a few extensions manually, this GL interop layer itself will need to know if they exist.
5385
5386
if (context.version < 2) {
5387
__webgl_acquireInstancedArraysExtension(GLctx);
5388
__webgl_acquireVertexArrayObjectExtension(GLctx);
5389
__webgl_acquireDrawBuffersExtension(GLctx);
5390
}
5391
5392
GLctx.disjointTimerQueryExt = GLctx.getExtension("EXT_disjoint_timer_query");
5393
5394
// These are the 'safe' feature-enabling extensions that don't add any performance impact related to e.g. debugging, and
5395
// should be enabled by default so that client GLES2/GL code will not need to go through extra hoops to get its stuff working.
5396
// As new extensions are ratified at http://www.khronos.org/registry/webgl/extensions/ , feel free to add your new extensions
5397
// here, as long as they don't produce a performance impact for users that might not be using those extensions.
5398
// E.g. debugging-related extensions should probably be off by default.
5399
var automaticallyEnabledExtensions = [ // Khronos ratified WebGL extensions ordered by number (no debug extensions):
5400
"OES_texture_float", "OES_texture_half_float", "OES_standard_derivatives",
5401
"OES_vertex_array_object", "WEBGL_compressed_texture_s3tc", "WEBGL_depth_texture",
5402
"OES_element_index_uint", "EXT_texture_filter_anisotropic", "EXT_frag_depth",
5403
"WEBGL_draw_buffers", "ANGLE_instanced_arrays", "OES_texture_float_linear",
5404
"OES_texture_half_float_linear", "EXT_blend_minmax", "EXT_shader_texture_lod",
5405
"EXT_texture_norm16",
5406
// Community approved WebGL extensions ordered by number:
5407
"WEBGL_compressed_texture_pvrtc", "EXT_color_buffer_half_float", "WEBGL_color_buffer_float",
5408
"EXT_sRGB", "WEBGL_compressed_texture_etc1", "EXT_disjoint_timer_query",
5409
"WEBGL_compressed_texture_etc", "WEBGL_compressed_texture_astc", "EXT_color_buffer_float",
5410
"WEBGL_compressed_texture_s3tc_srgb", "EXT_disjoint_timer_query_webgl2",
5411
// Old style prefixed forms of extensions (but still currently used on e.g. iPhone Xs as
5412
// tested on iOS 12.4.1):
5413
"WEBKIT_WEBGL_compressed_texture_pvrtc"];
5414
5415
function shouldEnableAutomatically(extension) {
5416
var ret = false;
5417
automaticallyEnabledExtensions.forEach(function(include) {
5418
if (extension.indexOf(include) != -1) {
5419
ret = true;
5420
}
5421
});
5422
return ret;
5423
}
5424
5425
var exts = GLctx.getSupportedExtensions() || []; // .getSupportedExtensions() can return null if context is lost, so coerce to empty array.
5426
exts.forEach(function(ext) {
5427
if (automaticallyEnabledExtensions.indexOf(ext) != -1) {
5428
GLctx.getExtension(ext); // Calling .getExtension enables that extension permanently, no need to store the return value to be enabled.
5429
}
5430
});
5431
},populateUniformTable:function(program) {
5432
var p = GL.programs[program];
5433
var ptable = GL.programInfos[program] = {
5434
uniforms: {},
5435
maxUniformLength: 0, // This is eagerly computed below, since we already enumerate all uniforms anyway.
5436
maxAttributeLength: -1, // This is lazily computed and cached, computed when/if first asked, "-1" meaning not computed yet.
5437
maxUniformBlockNameLength: -1 // Lazily computed as well
5438
};
5439
5440
var utable = ptable.uniforms;
5441
// A program's uniform table maps the string name of an uniform to an integer location of that uniform.
5442
// The global GL.uniforms map maps integer locations to WebGLUniformLocations.
5443
var numUniforms = GLctx.getProgramParameter(p, 0x8B86/*GL_ACTIVE_UNIFORMS*/);
5444
for (var i = 0; i < numUniforms; ++i) {
5445
var u = GLctx.getActiveUniform(p, i);
5446
5447
var name = u.name;
5448
ptable.maxUniformLength = Math.max(ptable.maxUniformLength, name.length+1);
5449
5450
// If we are dealing with an array, e.g. vec4 foo[3], strip off the array index part to canonicalize that "foo", "foo[]",
5451
// and "foo[0]" will mean the same. Loop below will populate foo[1] and foo[2].
5452
if (name.slice(-1) == ']') {
5453
name = name.slice(0, name.lastIndexOf('['));
5454
}
5455
5456
// Optimize memory usage slightly: If we have an array of uniforms, e.g. 'vec3 colors[3];', then
5457
// only store the string 'colors' in utable, and 'colors[0]', 'colors[1]' and 'colors[2]' will be parsed as 'colors'+i.
5458
// Note that for the GL.uniforms table, we still need to fetch the all WebGLUniformLocations for all the indices.
5459
var loc = GLctx.getUniformLocation(p, name);
5460
if (loc) {
5461
var id = GL.getNewId(GL.uniforms);
5462
utable[name] = [u.size, id];
5463
GL.uniforms[id] = loc;
5464
5465
for (var j = 1; j < u.size; ++j) {
5466
var n = name + '['+j+']';
5467
loc = GLctx.getUniformLocation(p, n);
5468
id = GL.getNewId(GL.uniforms);
5469
5470
GL.uniforms[id] = loc;
5471
}
5472
}
5473
}
5474
}};function _eglCreateContext(display, config, hmm, contextAttribs) {
5475
if (display != 62000 /* Magic ID for Emscripten 'default display' */) {
5476
EGL.setErrorCode(0x3008 /* EGL_BAD_DISPLAY */);
5477
return 0;
5478
}
5479
5480
// EGL 1.4 spec says default EGL_CONTEXT_CLIENT_VERSION is GLES1, but this is not supported by Emscripten.
5481
// So user must pass EGL_CONTEXT_CLIENT_VERSION == 2 to initialize EGL.
5482
var glesContextVersion = 1;
5483
for(;;) {
5484
var param = HEAP32[((contextAttribs)>>2)];
5485
if (param == 0x3098 /*EGL_CONTEXT_CLIENT_VERSION*/) {
5486
glesContextVersion = HEAP32[(((contextAttribs)+(4))>>2)];
5487
} else if (param == 0x3038 /*EGL_NONE*/) {
5488
break;
5489
} else {
5490
/* EGL1.4 specifies only EGL_CONTEXT_CLIENT_VERSION as supported attribute */
5491
EGL.setErrorCode(0x3004 /*EGL_BAD_ATTRIBUTE*/);
5492
return 0;
5493
}
5494
contextAttribs += 8;
5495
}
5496
if (glesContextVersion != 2) {
5497
EGL.setErrorCode(0x3005 /* EGL_BAD_CONFIG */);
5498
return 0; /* EGL_NO_CONTEXT */
5499
}
5500
5501
EGL.contextAttributes.majorVersion = glesContextVersion - 1; // WebGL 1 is GLES 2, WebGL2 is GLES3
5502
EGL.contextAttributes.minorVersion = 0;
5503
5504
EGL.context = GL.createContext(Module['canvas'], EGL.contextAttributes);
5505
5506
if (EGL.context != 0) {
5507
EGL.setErrorCode(0x3000 /* EGL_SUCCESS */);
5508
5509
// Run callbacks so that GL emulation works
5510
GL.makeContextCurrent(EGL.context);
5511
Module.useWebGL = true;
5512
Browser.moduleContextCreatedCallbacks.forEach(function(callback) { callback() });
5513
5514
// Note: This function only creates a context, but it shall not make it active.
5515
GL.makeContextCurrent(null);
5516
return 62004; // Magic ID for Emscripten EGLContext
5517
} else {
5518
EGL.setErrorCode(0x3009 /* EGL_BAD_MATCH */); // By the EGL 1.4 spec, an implementation that does not support GLES2 (WebGL in this case), this error code is set.
5519
return 0; /* EGL_NO_CONTEXT */
5520
}
5521
}
5522
5523
function _eglCreateWindowSurface(display, config, win, attrib_list) {
5524
if (display != 62000 /* Magic ID for Emscripten 'default display' */) {
5525
EGL.setErrorCode(0x3008 /* EGL_BAD_DISPLAY */);
5526
return 0;
5527
}
5528
if (config != 62002 /* Magic ID for the only EGLConfig supported by Emscripten */) {
5529
EGL.setErrorCode(0x3005 /* EGL_BAD_CONFIG */);
5530
return 0;
5531
}
5532
// TODO: Examine attrib_list! Parameters that can be present there are:
5533
// - EGL_RENDER_BUFFER (must be EGL_BACK_BUFFER)
5534
// - EGL_VG_COLORSPACE (can't be set)
5535
// - EGL_VG_ALPHA_FORMAT (can't be set)
5536
EGL.setErrorCode(0x3000 /* EGL_SUCCESS */);
5537
return 62006; /* Magic ID for Emscripten 'default surface' */
5538
}
5539
5540
function _eglDestroyContext(display, context) {
5541
if (display != 62000 /* Magic ID for Emscripten 'default display' */) {
5542
EGL.setErrorCode(0x3008 /* EGL_BAD_DISPLAY */);
5543
return 0;
5544
}
5545
if (context != 62004 /* Magic ID for Emscripten EGLContext */) {
5546
EGL.setErrorCode(0x3006 /* EGL_BAD_CONTEXT */);
5547
return 0;
5548
}
5549
5550
GL.deleteContext(EGL.context);
5551
EGL.setErrorCode(0x3000 /* EGL_SUCCESS */);
5552
if (EGL.currentContext == context) {
5553
EGL.currentContext = 0;
5554
}
5555
return 1 /* EGL_TRUE */;
5556
}
5557
5558
function _eglDestroySurface(display, surface) {
5559
if (display != 62000 /* Magic ID for Emscripten 'default display' */) {
5560
EGL.setErrorCode(0x3008 /* EGL_BAD_DISPLAY */);
5561
return 0;
5562
}
5563
if (surface != 62006 /* Magic ID for the only EGLSurface supported by Emscripten */) {
5564
EGL.setErrorCode(0x300D /* EGL_BAD_SURFACE */);
5565
return 1;
5566
}
5567
if (EGL.currentReadSurface == surface) {
5568
EGL.currentReadSurface = 0;
5569
}
5570
if (EGL.currentDrawSurface == surface) {
5571
EGL.currentDrawSurface = 0;
5572
}
5573
EGL.setErrorCode(0x3000 /* EGL_SUCCESS */);
5574
return 1; /* Magic ID for Emscripten 'default surface' */
5575
}
5576
5577
function _eglGetConfigAttrib(display, config, attribute, value) {
5578
if (display != 62000 /* Magic ID for Emscripten 'default display' */) {
5579
EGL.setErrorCode(0x3008 /* EGL_BAD_DISPLAY */);
5580
return 0;
5581
}
5582
if (config != 62002 /* Magic ID for the only EGLConfig supported by Emscripten */) {
5583
EGL.setErrorCode(0x3005 /* EGL_BAD_CONFIG */);
5584
return 0;
5585
}
5586
if (!value) {
5587
EGL.setErrorCode(0x300C /* EGL_BAD_PARAMETER */);
5588
return 0;
5589
}
5590
EGL.setErrorCode(0x3000 /* EGL_SUCCESS */);
5591
switch(attribute) {
5592
case 0x3020: // EGL_BUFFER_SIZE
5593
HEAP32[((value)>>2)]=EGL.contextAttributes.alpha ? 32 : 24;
5594
return 1;
5595
case 0x3021: // EGL_ALPHA_SIZE
5596
HEAP32[((value)>>2)]=EGL.contextAttributes.alpha ? 8 : 0;
5597
return 1;
5598
case 0x3022: // EGL_BLUE_SIZE
5599
HEAP32[((value)>>2)]=8;
5600
return 1;
5601
case 0x3023: // EGL_GREEN_SIZE
5602
HEAP32[((value)>>2)]=8;
5603
return 1;
5604
case 0x3024: // EGL_RED_SIZE
5605
HEAP32[((value)>>2)]=8;
5606
return 1;
5607
case 0x3025: // EGL_DEPTH_SIZE
5608
HEAP32[((value)>>2)]=EGL.contextAttributes.depth ? 24 : 0;
5609
return 1;
5610
case 0x3026: // EGL_STENCIL_SIZE
5611
HEAP32[((value)>>2)]=EGL.contextAttributes.stencil ? 8 : 0;
5612
return 1;
5613
case 0x3027: // EGL_CONFIG_CAVEAT
5614
// We can return here one of EGL_NONE (0x3038), EGL_SLOW_CONFIG (0x3050) or EGL_NON_CONFORMANT_CONFIG (0x3051).
5615
HEAP32[((value)>>2)]=0x3038;
5616
return 1;
5617
case 0x3028: // EGL_CONFIG_ID
5618
HEAP32[((value)>>2)]=62002;
5619
return 1;
5620
case 0x3029: // EGL_LEVEL
5621
HEAP32[((value)>>2)]=0;
5622
return 1;
5623
case 0x302A: // EGL_MAX_PBUFFER_HEIGHT
5624
HEAP32[((value)>>2)]=4096;
5625
return 1;
5626
case 0x302B: // EGL_MAX_PBUFFER_PIXELS
5627
HEAP32[((value)>>2)]=16777216;
5628
return 1;
5629
case 0x302C: // EGL_MAX_PBUFFER_WIDTH
5630
HEAP32[((value)>>2)]=4096;
5631
return 1;
5632
case 0x302D: // EGL_NATIVE_RENDERABLE
5633
HEAP32[((value)>>2)]=0;
5634
return 1;
5635
case 0x302E: // EGL_NATIVE_VISUAL_ID
5636
HEAP32[((value)>>2)]=0;
5637
return 1;
5638
case 0x302F: // EGL_NATIVE_VISUAL_TYPE
5639
HEAP32[((value)>>2)]=0x3038;
5640
return 1;
5641
case 0x3031: // EGL_SAMPLES
5642
HEAP32[((value)>>2)]=EGL.contextAttributes.antialias ? 4 : 0;
5643
return 1;
5644
case 0x3032: // EGL_SAMPLE_BUFFERS
5645
HEAP32[((value)>>2)]=EGL.contextAttributes.antialias ? 1 : 0;
5646
return 1;
5647
case 0x3033: // EGL_SURFACE_TYPE
5648
HEAP32[((value)>>2)]=0x4;
5649
return 1;
5650
case 0x3034: // EGL_TRANSPARENT_TYPE
5651
// If this returns EGL_TRANSPARENT_RGB (0x3052), transparency is used through color-keying. No such thing applies to Emscripten canvas.
5652
HEAP32[((value)>>2)]=0x3038;
5653
return 1;
5654
case 0x3035: // EGL_TRANSPARENT_BLUE_VALUE
5655
case 0x3036: // EGL_TRANSPARENT_GREEN_VALUE
5656
case 0x3037: // EGL_TRANSPARENT_RED_VALUE
5657
// "If EGL_TRANSPARENT_TYPE is EGL_NONE, then the values for EGL_TRANSPARENT_RED_VALUE, EGL_TRANSPARENT_GREEN_VALUE, and EGL_TRANSPARENT_BLUE_VALUE are undefined."
5658
HEAP32[((value)>>2)]=-1;
5659
return 1;
5660
case 0x3039: // EGL_BIND_TO_TEXTURE_RGB
5661
case 0x303A: // EGL_BIND_TO_TEXTURE_RGBA
5662
HEAP32[((value)>>2)]=0;
5663
return 1;
5664
case 0x303B: // EGL_MIN_SWAP_INTERVAL
5665
HEAP32[((value)>>2)]=0;
5666
return 1;
5667
case 0x303C: // EGL_MAX_SWAP_INTERVAL
5668
HEAP32[((value)>>2)]=1;
5669
return 1;
5670
case 0x303D: // EGL_LUMINANCE_SIZE
5671
case 0x303E: // EGL_ALPHA_MASK_SIZE
5672
HEAP32[((value)>>2)]=0;
5673
return 1;
5674
case 0x303F: // EGL_COLOR_BUFFER_TYPE
5675
// EGL has two types of buffers: EGL_RGB_BUFFER and EGL_LUMINANCE_BUFFER.
5676
HEAP32[((value)>>2)]=0x308E;
5677
return 1;
5678
case 0x3040: // EGL_RENDERABLE_TYPE
5679
// A bit combination of EGL_OPENGL_ES_BIT,EGL_OPENVG_BIT,EGL_OPENGL_ES2_BIT and EGL_OPENGL_BIT.
5680
HEAP32[((value)>>2)]=0x4;
5681
return 1;
5682
case 0x3042: // EGL_CONFORMANT
5683
// "EGL_CONFORMANT is a mask indicating if a client API context created with respect to the corresponding EGLConfig will pass the required conformance tests for that API."
5684
HEAP32[((value)>>2)]=0;
5685
return 1;
5686
default:
5687
EGL.setErrorCode(0x3004 /* EGL_BAD_ATTRIBUTE */);
5688
return 0;
5689
}
5690
}
5691
5692
function _eglGetDisplay(nativeDisplayType) {
5693
EGL.setErrorCode(0x3000 /* EGL_SUCCESS */);
5694
// Note: As a 'conformant' implementation of EGL, we would prefer to init here only if the user
5695
// calls this function with EGL_DEFAULT_DISPLAY. Other display IDs would be preferred to be unsupported
5696
// and EGL_NO_DISPLAY returned. Uncomment the following code lines to do this.
5697
// Instead, an alternative route has been preferred, namely that the Emscripten EGL implementation
5698
// "emulates" X11, and eglGetDisplay is expected to accept/receive a pointer to an X11 Display object.
5699
// Therefore, be lax and allow anything to be passed in, and return the magic handle to our default EGLDisplay object.
5700
5701
// if (nativeDisplayType == 0 /* EGL_DEFAULT_DISPLAY */) {
5702
return 62000; // Magic ID for Emscripten 'default display'
5703
// }
5704
// else
5705
// return 0; // EGL_NO_DISPLAY
5706
}
5707
5708
function _eglGetError() {
5709
return EGL.errorCode;
5710
}
5711
5712
function _eglGetProcAddress(name_) {
5713
return _emscripten_GetProcAddress(name_);
5714
}
5715
5716
function _eglInitialize(display, majorVersion, minorVersion) {
5717
if (display == 62000 /* Magic ID for Emscripten 'default display' */) {
5718
if (majorVersion) {
5719
HEAP32[((majorVersion)>>2)]=1; // Advertise EGL Major version: '1'
5720
}
5721
if (minorVersion) {
5722
HEAP32[((minorVersion)>>2)]=4; // Advertise EGL Minor version: '4'
5723
}
5724
EGL.defaultDisplayInitialized = true;
5725
EGL.setErrorCode(0x3000 /* EGL_SUCCESS */);
5726
return 1;
5727
}
5728
else {
5729
EGL.setErrorCode(0x3008 /* EGL_BAD_DISPLAY */);
5730
return 0;
5731
}
5732
}
5733
5734
function _eglMakeCurrent(display, draw, read, context) {
5735
if (display != 62000 /* Magic ID for Emscripten 'default display' */) {
5736
EGL.setErrorCode(0x3008 /* EGL_BAD_DISPLAY */);
5737
return 0 /* EGL_FALSE */;
5738
}
5739
//\todo An EGL_NOT_INITIALIZED error is generated if EGL is not initialized for dpy.
5740
if (context != 0 && context != 62004 /* Magic ID for Emscripten EGLContext */) {
5741
EGL.setErrorCode(0x3006 /* EGL_BAD_CONTEXT */);
5742
return 0;
5743
}
5744
if ((read != 0 && read != 62006) || (draw != 0 && draw != 62006 /* Magic ID for Emscripten 'default surface' */)) {
5745
EGL.setErrorCode(0x300D /* EGL_BAD_SURFACE */);
5746
return 0;
5747
}
5748
5749
GL.makeContextCurrent(context ? EGL.context : null);
5750
5751
EGL.currentContext = context;
5752
EGL.currentDrawSurface = draw;
5753
EGL.currentReadSurface = read;
5754
EGL.setErrorCode(0x3000 /* EGL_SUCCESS */);
5755
return 1 /* EGL_TRUE */;
5756
}
5757
5758
function _eglQueryString(display, name) {
5759
if (display != 62000 /* Magic ID for Emscripten 'default display' */) {
5760
EGL.setErrorCode(0x3008 /* EGL_BAD_DISPLAY */);
5761
return 0;
5762
}
5763
//\todo An EGL_NOT_INITIALIZED error is generated if EGL is not initialized for dpy.
5764
EGL.setErrorCode(0x3000 /* EGL_SUCCESS */);
5765
if (EGL.stringCache[name]) return EGL.stringCache[name];
5766
var ret;
5767
switch(name) {
5768
case 0x3053 /* EGL_VENDOR */: ret = allocateUTF8("Emscripten"); break;
5769
case 0x3054 /* EGL_VERSION */: ret = allocateUTF8("1.4 Emscripten EGL"); break;
5770
case 0x3055 /* EGL_EXTENSIONS */: ret = allocateUTF8(""); break; // Currently not supporting any EGL extensions.
5771
case 0x308D /* EGL_CLIENT_APIS */: ret = allocateUTF8("OpenGL_ES"); break;
5772
default:
5773
EGL.setErrorCode(0x300C /* EGL_BAD_PARAMETER */);
5774
return 0;
5775
}
5776
EGL.stringCache[name] = ret;
5777
return ret;
5778
}
5779
5780
function _eglSwapBuffers() {
5781
5782
if (!EGL.defaultDisplayInitialized) {
5783
EGL.setErrorCode(0x3001 /* EGL_NOT_INITIALIZED */);
5784
} else if (!Module.ctx) {
5785
EGL.setErrorCode(0x3002 /* EGL_BAD_ACCESS */);
5786
} else if (Module.ctx.isContextLost()) {
5787
EGL.setErrorCode(0x300E /* EGL_CONTEXT_LOST */);
5788
} else {
5789
// According to documentation this does an implicit flush.
5790
// Due to discussion at https://github.com/emscripten-core/emscripten/pull/1871
5791
// the flush was removed since this _may_ result in slowing code down.
5792
//_glFlush();
5793
EGL.setErrorCode(0x3000 /* EGL_SUCCESS */);
5794
return 1 /* EGL_TRUE */;
5795
}
5796
return 0 /* EGL_FALSE */;
5797
}
5798
5799
function _eglSwapInterval(display, interval) {
5800
if (display != 62000 /* Magic ID for Emscripten 'default display' */) {
5801
EGL.setErrorCode(0x3008 /* EGL_BAD_DISPLAY */);
5802
return 0;
5803
}
5804
if (interval == 0) _emscripten_set_main_loop_timing(0/*EM_TIMING_SETTIMEOUT*/, 0);
5805
else _emscripten_set_main_loop_timing(1/*EM_TIMING_RAF*/, interval);
5806
5807
EGL.setErrorCode(0x3000 /* EGL_SUCCESS */);
5808
return 1;
5809
}
5810
5811
function _eglTerminate(display) {
5812
if (display != 62000 /* Magic ID for Emscripten 'default display' */) {
5813
EGL.setErrorCode(0x3008 /* EGL_BAD_DISPLAY */);
5814
return 0;
5815
}
5816
EGL.currentContext = 0;
5817
EGL.currentReadSurface = 0;
5818
EGL.currentDrawSurface = 0;
5819
EGL.defaultDisplayInitialized = false;
5820
EGL.setErrorCode(0x3000 /* EGL_SUCCESS */);
5821
return 1;
5822
}
5823
5824
5825
function _eglWaitClient() {
5826
EGL.setErrorCode(0x3000 /* EGL_SUCCESS */);
5827
return 1;
5828
}function _eglWaitGL(
5829
) {
5830
return _eglWaitClient();
5831
}
5832
5833
function _eglWaitNative(nativeEngineId) {
5834
EGL.setErrorCode(0x3000 /* EGL_SUCCESS */);
5835
return 1;
5836
}
5837
5838
5839
var JSEvents={keyEvent:0,mouseEvent:0,wheelEvent:0,uiEvent:0,focusEvent:0,deviceOrientationEvent:0,deviceMotionEvent:0,fullscreenChangeEvent:0,pointerlockChangeEvent:0,visibilityChangeEvent:0,touchEvent:0,previousFullscreenElement:null,previousScreenX:null,previousScreenY:null,removeEventListenersRegistered:false,removeAllEventListeners:function() {
5840
for(var i = JSEvents.eventHandlers.length-1; i >= 0; --i) {
5841
JSEvents._removeHandler(i);
5842
}
5843
JSEvents.eventHandlers = [];
5844
JSEvents.deferredCalls = [];
5845
},registerRemoveEventListeners:function() {
5846
if (!JSEvents.removeEventListenersRegistered) {
5847
__ATEXIT__.push(JSEvents.removeAllEventListeners);
5848
JSEvents.removeEventListenersRegistered = true;
5849
}
5850
},deferredCalls:[],deferCall:function(targetFunction, precedence, argsList) {
5851
function arraysHaveEqualContent(arrA, arrB) {
5852
if (arrA.length != arrB.length) return false;
5853
5854
for(var i in arrA) {
5855
if (arrA[i] != arrB[i]) return false;
5856
}
5857
return true;
5858
}
5859
// Test if the given call was already queued, and if so, don't add it again.
5860
for(var i in JSEvents.deferredCalls) {
5861
var call = JSEvents.deferredCalls[i];
5862
if (call.targetFunction == targetFunction && arraysHaveEqualContent(call.argsList, argsList)) {
5863
return;
5864
}
5865
}
5866
JSEvents.deferredCalls.push({
5867
targetFunction: targetFunction,
5868
precedence: precedence,
5869
argsList: argsList
5870
});
5871
5872
JSEvents.deferredCalls.sort(function(x,y) { return x.precedence < y.precedence; });
5873
},removeDeferredCalls:function(targetFunction) {
5874
for(var i = 0; i < JSEvents.deferredCalls.length; ++i) {
5875
if (JSEvents.deferredCalls[i].targetFunction == targetFunction) {
5876
JSEvents.deferredCalls.splice(i, 1);
5877
--i;
5878
}
5879
}
5880
},canPerformEventHandlerRequests:function() {
5881
return JSEvents.inEventHandler && JSEvents.currentEventHandler.allowsDeferredCalls;
5882
},runDeferredCalls:function() {
5883
if (!JSEvents.canPerformEventHandlerRequests()) {
5884
return;
5885
}
5886
for(var i = 0; i < JSEvents.deferredCalls.length; ++i) {
5887
var call = JSEvents.deferredCalls[i];
5888
JSEvents.deferredCalls.splice(i, 1);
5889
--i;
5890
call.targetFunction.apply(null, call.argsList);
5891
}
5892
},inEventHandler:0,currentEventHandler:null,eventHandlers:[],removeAllHandlersOnTarget:function(target, eventTypeString) {
5893
for(var i = 0; i < JSEvents.eventHandlers.length; ++i) {
5894
if (JSEvents.eventHandlers[i].target == target &&
5895
(!eventTypeString || eventTypeString == JSEvents.eventHandlers[i].eventTypeString)) {
5896
JSEvents._removeHandler(i--);
5897
}
5898
}
5899
},_removeHandler:function(i) {
5900
var h = JSEvents.eventHandlers[i];
5901
h.target.removeEventListener(h.eventTypeString, h.eventListenerFunc, h.useCapture);
5902
JSEvents.eventHandlers.splice(i, 1);
5903
},registerOrRemoveHandler:function(eventHandler) {
5904
var jsEventHandler = function jsEventHandler(event) {
5905
// Increment nesting count for the event handler.
5906
++JSEvents.inEventHandler;
5907
JSEvents.currentEventHandler = eventHandler;
5908
// Process any old deferred calls the user has placed.
5909
JSEvents.runDeferredCalls();
5910
// Process the actual event, calls back to user C code handler.
5911
eventHandler.handlerFunc(event);
5912
// Process any new deferred calls that were placed right now from this event handler.
5913
JSEvents.runDeferredCalls();
5914
// Out of event handler - restore nesting count.
5915
--JSEvents.inEventHandler;
5916
};
5917
5918
if (eventHandler.callbackfunc) {
5919
eventHandler.eventListenerFunc = jsEventHandler;
5920
eventHandler.target.addEventListener(eventHandler.eventTypeString, jsEventHandler, eventHandler.useCapture);
5921
JSEvents.eventHandlers.push(eventHandler);
5922
JSEvents.registerRemoveEventListeners();
5923
} else {
5924
for(var i = 0; i < JSEvents.eventHandlers.length; ++i) {
5925
if (JSEvents.eventHandlers[i].target == eventHandler.target
5926
&& JSEvents.eventHandlers[i].eventTypeString == eventHandler.eventTypeString) {
5927
JSEvents._removeHandler(i--);
5928
}
5929
}
5930
}
5931
},getNodeNameForTarget:function(target) {
5932
if (!target) return '';
5933
if (target == window) return '#window';
5934
if (target == screen) return '#screen';
5935
return (target && target.nodeName) ? target.nodeName : '';
5936
},fullscreenEnabled:function() {
5937
return document.fullscreenEnabled
5938
// Safari 13.0.3 on macOS Catalina 10.15.1 still ships with prefixed webkitFullscreenEnabled.
5939
// TODO: If Safari at some point ships with unprefixed version, update the version check above.
5940
|| document.webkitFullscreenEnabled
5941
;
5942
}};
5943
5944
var __currentFullscreenStrategy={};
5945
5946
5947
5948
5949
5950
5951
5952
5953
function __maybeCStringToJsString(cString) {
5954
return cString === cString + 0 ? UTF8ToString(cString) : cString;
5955
}
5956
5957
var __specialEventTargets=[0, typeof document !== 'undefined' ? document : 0, typeof window !== 'undefined' ? window : 0];function __findEventTarget(target) {
5958
var domElement = __specialEventTargets[target] || (typeof document !== 'undefined' ? document.querySelector(__maybeCStringToJsString(target)) : undefined);
5959
return domElement;
5960
}function __findCanvasEventTarget(target) { return __findEventTarget(target); }function _emscripten_get_canvas_element_size(target, width, height) {
5961
var canvas = __findCanvasEventTarget(target);
5962
if (!canvas) return -4;
5963
HEAP32[((width)>>2)]=canvas.width;
5964
HEAP32[((height)>>2)]=canvas.height;
5965
}function __get_canvas_element_size(target) {
5966
var stackTop = stackSave();
5967
var w = stackAlloc(8);
5968
var h = w + 4;
5969
5970
var targetInt = stackAlloc(target.id.length+1);
5971
stringToUTF8(target.id, targetInt, target.id.length+1);
5972
var ret = _emscripten_get_canvas_element_size(targetInt, w, h);
5973
var size = [HEAP32[((w)>>2)], HEAP32[((h)>>2)]];
5974
stackRestore(stackTop);
5975
return size;
5976
}
5977
5978
5979
function _emscripten_set_canvas_element_size(target, width, height) {
5980
var canvas = __findCanvasEventTarget(target);
5981
if (!canvas) return -4;
5982
canvas.width = width;
5983
canvas.height = height;
5984
return 0;
5985
}function __set_canvas_element_size(target, width, height) {
5986
if (!target.controlTransferredOffscreen) {
5987
target.width = width;
5988
target.height = height;
5989
} else {
5990
// This function is being called from high-level JavaScript code instead of asm.js/Wasm,
5991
// and it needs to synchronously proxy over to another thread, so marshal the string onto the heap to do the call.
5992
var stackTop = stackSave();
5993
var targetInt = stackAlloc(target.id.length+1);
5994
stringToUTF8(target.id, targetInt, target.id.length+1);
5995
_emscripten_set_canvas_element_size(targetInt, width, height);
5996
stackRestore(stackTop);
5997
}
5998
}function __registerRestoreOldStyle(canvas) {
5999
var canvasSize = __get_canvas_element_size(canvas);
6000
var oldWidth = canvasSize[0];
6001
var oldHeight = canvasSize[1];
6002
var oldCssWidth = canvas.style.width;
6003
var oldCssHeight = canvas.style.height;
6004
var oldBackgroundColor = canvas.style.backgroundColor; // Chrome reads color from here.
6005
var oldDocumentBackgroundColor = document.body.style.backgroundColor; // IE11 reads color from here.
6006
// Firefox always has black background color.
6007
var oldPaddingLeft = canvas.style.paddingLeft; // Chrome, FF, Safari
6008
var oldPaddingRight = canvas.style.paddingRight;
6009
var oldPaddingTop = canvas.style.paddingTop;
6010
var oldPaddingBottom = canvas.style.paddingBottom;
6011
var oldMarginLeft = canvas.style.marginLeft; // IE11
6012
var oldMarginRight = canvas.style.marginRight;
6013
var oldMarginTop = canvas.style.marginTop;
6014
var oldMarginBottom = canvas.style.marginBottom;
6015
var oldDocumentBodyMargin = document.body.style.margin;
6016
var oldDocumentOverflow = document.documentElement.style.overflow; // Chrome, Firefox
6017
var oldDocumentScroll = document.body.scroll; // IE
6018
var oldImageRendering = canvas.style.imageRendering;
6019
6020
function restoreOldStyle() {
6021
var fullscreenElement = document.fullscreenElement
6022
|| document.webkitFullscreenElement
6023
|| document.msFullscreenElement
6024
;
6025
if (!fullscreenElement) {
6026
document.removeEventListener('fullscreenchange', restoreOldStyle);
6027
6028
6029
// Unprefixed Fullscreen API shipped in Chromium 71 (https://bugs.chromium.org/p/chromium/issues/detail?id=383813)
6030
// As of Safari 13.0.3 on macOS Catalina 10.15.1 still ships with prefixed webkitfullscreenchange. TODO: revisit this check once Safari ships unprefixed version.
6031
document.removeEventListener('webkitfullscreenchange', restoreOldStyle);
6032
6033
6034
__set_canvas_element_size(canvas, oldWidth, oldHeight);
6035
6036
canvas.style.width = oldCssWidth;
6037
canvas.style.height = oldCssHeight;
6038
canvas.style.backgroundColor = oldBackgroundColor; // Chrome
6039
// IE11 hack: assigning 'undefined' or an empty string to document.body.style.backgroundColor has no effect, so first assign back the default color
6040
// before setting the undefined value. Setting undefined value is also important, or otherwise we would later treat that as something that the user
6041
// had explicitly set so subsequent fullscreen transitions would not set background color properly.
6042
if (!oldDocumentBackgroundColor) document.body.style.backgroundColor = 'white';
6043
document.body.style.backgroundColor = oldDocumentBackgroundColor; // IE11
6044
canvas.style.paddingLeft = oldPaddingLeft; // Chrome, FF, Safari
6045
canvas.style.paddingRight = oldPaddingRight;
6046
canvas.style.paddingTop = oldPaddingTop;
6047
canvas.style.paddingBottom = oldPaddingBottom;
6048
canvas.style.marginLeft = oldMarginLeft; // IE11
6049
canvas.style.marginRight = oldMarginRight;
6050
canvas.style.marginTop = oldMarginTop;
6051
canvas.style.marginBottom = oldMarginBottom;
6052
document.body.style.margin = oldDocumentBodyMargin;
6053
document.documentElement.style.overflow = oldDocumentOverflow; // Chrome, Firefox
6054
document.body.scroll = oldDocumentScroll; // IE
6055
canvas.style.imageRendering = oldImageRendering;
6056
if (canvas.GLctxObject) canvas.GLctxObject.GLctx.viewport(0, 0, oldWidth, oldHeight);
6057
6058
if (__currentFullscreenStrategy.canvasResizedCallback) {
6059
dynCall_iiii(__currentFullscreenStrategy.canvasResizedCallback, 37, 0, __currentFullscreenStrategy.canvasResizedCallbackUserData);
6060
}
6061
}
6062
}
6063
document.addEventListener('fullscreenchange', restoreOldStyle);
6064
// Unprefixed Fullscreen API shipped in Chromium 71 (https://bugs.chromium.org/p/chromium/issues/detail?id=383813)
6065
// As of Safari 13.0.3 on macOS Catalina 10.15.1 still ships with prefixed webkitfullscreenchange. TODO: revisit this check once Safari ships unprefixed version.
6066
document.addEventListener('webkitfullscreenchange', restoreOldStyle);
6067
return restoreOldStyle;
6068
}
6069
6070
function __setLetterbox(element, topBottom, leftRight) {
6071
// Cannot use margin to specify letterboxes in FF or Chrome, since those ignore margins in fullscreen mode.
6072
element.style.paddingLeft = element.style.paddingRight = leftRight + 'px';
6073
element.style.paddingTop = element.style.paddingBottom = topBottom + 'px';
6074
}
6075
6076
function __getBoundingClientRect(e) {
6077
return __specialEventTargets.indexOf(e) < 0 ? e.getBoundingClientRect() : {'left':0,'top':0};
6078
}function _JSEvents_resizeCanvasForFullscreen(target, strategy) {
6079
var restoreOldStyle = __registerRestoreOldStyle(target);
6080
var cssWidth = strategy.softFullscreen ? innerWidth : screen.width;
6081
var cssHeight = strategy.softFullscreen ? innerHeight : screen.height;
6082
var rect = __getBoundingClientRect(target);
6083
var windowedCssWidth = rect.width;
6084
var windowedCssHeight = rect.height;
6085
var canvasSize = __get_canvas_element_size(target);
6086
var windowedRttWidth = canvasSize[0];
6087
var windowedRttHeight = canvasSize[1];
6088
6089
if (strategy.scaleMode == 3) {
6090
__setLetterbox(target, (cssHeight - windowedCssHeight) / 2, (cssWidth - windowedCssWidth) / 2);
6091
cssWidth = windowedCssWidth;
6092
cssHeight = windowedCssHeight;
6093
} else if (strategy.scaleMode == 2) {
6094
if (cssWidth*windowedRttHeight < windowedRttWidth*cssHeight) {
6095
var desiredCssHeight = windowedRttHeight * cssWidth / windowedRttWidth;
6096
__setLetterbox(target, (cssHeight - desiredCssHeight) / 2, 0);
6097
cssHeight = desiredCssHeight;
6098
} else {
6099
var desiredCssWidth = windowedRttWidth * cssHeight / windowedRttHeight;
6100
__setLetterbox(target, 0, (cssWidth - desiredCssWidth) / 2);
6101
cssWidth = desiredCssWidth;
6102
}
6103
}
6104
6105
// If we are adding padding, must choose a background color or otherwise Chrome will give the
6106
// padding a default white color. Do it only if user has not customized their own background color.
6107
if (!target.style.backgroundColor) target.style.backgroundColor = 'black';
6108
// IE11 does the same, but requires the color to be set in the document body.
6109
if (!document.body.style.backgroundColor) document.body.style.backgroundColor = 'black'; // IE11
6110
// Firefox always shows black letterboxes independent of style color.
6111
6112
target.style.width = cssWidth + 'px';
6113
target.style.height = cssHeight + 'px';
6114
6115
if (strategy.filteringMode == 1) {
6116
target.style.imageRendering = 'optimizeSpeed';
6117
target.style.imageRendering = '-moz-crisp-edges';
6118
target.style.imageRendering = '-o-crisp-edges';
6119
target.style.imageRendering = '-webkit-optimize-contrast';
6120
target.style.imageRendering = 'optimize-contrast';
6121
target.style.imageRendering = 'crisp-edges';
6122
target.style.imageRendering = 'pixelated';
6123
}
6124
6125
var dpiScale = (strategy.canvasResolutionScaleMode == 2) ? devicePixelRatio : 1;
6126
if (strategy.canvasResolutionScaleMode != 0) {
6127
var newWidth = (cssWidth * dpiScale)|0;
6128
var newHeight = (cssHeight * dpiScale)|0;
6129
__set_canvas_element_size(target, newWidth, newHeight);
6130
if (target.GLctxObject) target.GLctxObject.GLctx.viewport(0, 0, newWidth, newHeight);
6131
}
6132
return restoreOldStyle;
6133
}function _JSEvents_requestFullscreen(target, strategy) {
6134
// EMSCRIPTEN_FULLSCREEN_SCALE_DEFAULT + EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_NONE is a mode where no extra logic is performed to the DOM elements.
6135
if (strategy.scaleMode != 0 || strategy.canvasResolutionScaleMode != 0) {
6136
_JSEvents_resizeCanvasForFullscreen(target, strategy);
6137
}
6138
6139
if (target.requestFullscreen) {
6140
target.requestFullscreen();
6141
} else if (target.webkitRequestFullscreen) {
6142
target.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
6143
} else {
6144
return JSEvents.fullscreenEnabled() ? -3 : -1;
6145
}
6146
6147
if (strategy.canvasResizedCallback) {
6148
dynCall_iiii(strategy.canvasResizedCallback, 37, 0, strategy.canvasResizedCallbackUserData);
6149
}
6150
6151
return 0;
6152
}function _emscripten_exit_fullscreen() {
6153
if (!JSEvents.fullscreenEnabled()) return -1;
6154
// Make sure no queued up calls will fire after this.
6155
JSEvents.removeDeferredCalls(_JSEvents_requestFullscreen);
6156
6157
var d = __specialEventTargets[1];
6158
if (d.exitFullscreen) {
6159
d.fullscreenElement && d.exitFullscreen();
6160
} else if (d.webkitExitFullscreen) {
6161
d.webkitFullscreenElement && d.webkitExitFullscreen();
6162
} else {
6163
return -1;
6164
}
6165
6166
return 0;
6167
}
6168
6169
6170
function __requestPointerLock(target) {
6171
if (target.requestPointerLock) {
6172
target.requestPointerLock();
6173
} else if (target.msRequestPointerLock) {
6174
target.msRequestPointerLock();
6175
} else {
6176
// document.body is known to accept pointer lock, so use that to differentiate if the user passed a bad element,
6177
// or if the whole browser just doesn't support the feature.
6178
if (document.body.requestPointerLock
6179
|| document.body.msRequestPointerLock
6180
) {
6181
return -3;
6182
} else {
6183
return -1;
6184
}
6185
}
6186
return 0;
6187
}function _emscripten_exit_pointerlock() {
6188
// Make sure no queued up calls will fire after this.
6189
JSEvents.removeDeferredCalls(__requestPointerLock);
6190
6191
if (document.exitPointerLock) {
6192
document.exitPointerLock();
6193
} else if (document.msExitPointerLock) {
6194
document.msExitPointerLock();
6195
} else {
6196
return -1;
6197
}
6198
return 0;
6199
}
6200
6201
function _emscripten_get_device_pixel_ratio() {
6202
return (typeof devicePixelRatio === 'number' && devicePixelRatio) || 1.0;
6203
}
6204
6205
function _emscripten_get_element_css_size(target, width, height) {
6206
target = __findEventTarget(target);
6207
if (!target) return -4;
6208
6209
var rect = __getBoundingClientRect(target);
6210
HEAPF64[((width)>>3)]=rect.width;
6211
HEAPF64[((height)>>3)]=rect.height;
6212
6213
return 0;
6214
}
6215
6216
6217
function __fillGamepadEventData(eventStruct, e) {
6218
HEAPF64[((eventStruct)>>3)]=e.timestamp;
6219
for(var i = 0; i < e.axes.length; ++i) {
6220
HEAPF64[(((eventStruct+i*8)+(16))>>3)]=e.axes[i];
6221
}
6222
for(var i = 0; i < e.buttons.length; ++i) {
6223
if (typeof(e.buttons[i]) === 'object') {
6224
HEAPF64[(((eventStruct+i*8)+(528))>>3)]=e.buttons[i].value;
6225
} else {
6226
HEAPF64[(((eventStruct+i*8)+(528))>>3)]=e.buttons[i];
6227
}
6228
}
6229
for(var i = 0; i < e.buttons.length; ++i) {
6230
if (typeof(e.buttons[i]) === 'object') {
6231
HEAP32[(((eventStruct+i*4)+(1040))>>2)]=e.buttons[i].pressed;
6232
} else {
6233
// Assigning a boolean to HEAP32, that's ok, but Closure would like to warn about it:
6234
/** @suppress {checkTypes} */
6235
HEAP32[(((eventStruct+i*4)+(1040))>>2)]=e.buttons[i] == 1;
6236
}
6237
}
6238
HEAP32[(((eventStruct)+(1296))>>2)]=e.connected;
6239
HEAP32[(((eventStruct)+(1300))>>2)]=e.index;
6240
HEAP32[(((eventStruct)+(8))>>2)]=e.axes.length;
6241
HEAP32[(((eventStruct)+(12))>>2)]=e.buttons.length;
6242
stringToUTF8(e.id, eventStruct + 1304, 64);
6243
stringToUTF8(e.mapping, eventStruct + 1368, 64);
6244
}function _emscripten_get_gamepad_status(index, gamepadState) {
6245
if (!JSEvents.lastGamepadState) throw 'emscripten_get_gamepad_status() can only be called after having first called emscripten_sample_gamepad_data() and that function has returned EMSCRIPTEN_RESULT_SUCCESS!';
6246
6247
// INVALID_PARAM is returned on a Gamepad index that never was there.
6248
if (index < 0 || index >= JSEvents.lastGamepadState.length) return -5;
6249
6250
// NO_DATA is returned on a Gamepad index that was removed.
6251
// For previously disconnected gamepads there should be an empty slot (null/undefined/false) at the index.
6252
// This is because gamepads must keep their original position in the array.
6253
// For example, removing the first of two gamepads produces [null/undefined/false, gamepad].
6254
if (!JSEvents.lastGamepadState[index]) return -7;
6255
6256
__fillGamepadEventData(gamepadState, JSEvents.lastGamepadState[index]);
6257
return 0;
6258
}
6259
6260
function _emscripten_get_num_gamepads() {
6261
if (!JSEvents.lastGamepadState) throw 'emscripten_get_num_gamepads() can only be called after having first called emscripten_sample_gamepad_data() and that function has returned EMSCRIPTEN_RESULT_SUCCESS!';
6262
// N.B. Do not call emscripten_get_num_gamepads() unless having first called emscripten_sample_gamepad_data(), and that has returned EMSCRIPTEN_RESULT_SUCCESS.
6263
// Otherwise the following line will throw an exception.
6264
return JSEvents.lastGamepadState.length;
6265
}
6266
6267
function _emscripten_get_sbrk_ptr() {
6268
return 14350080;
6269
}
6270
6271
function _emscripten_glActiveTexture(x0) { GLctx['activeTexture'](x0) }
6272
6273
function _emscripten_glAttachShader(program, shader) {
6274
GLctx.attachShader(GL.programs[program],
6275
GL.shaders[shader]);
6276
}
6277
6278
function _emscripten_glBeginQueryEXT(target, id) {
6279
GLctx.disjointTimerQueryExt['beginQueryEXT'](target, GL.timerQueriesEXT[id]);
6280
}
6281
6282
function _emscripten_glBindAttribLocation(program, index, name) {
6283
GLctx.bindAttribLocation(GL.programs[program], index, UTF8ToString(name));
6284
}
6285
6286
function _emscripten_glBindBuffer(target, buffer) {
6287
6288
GLctx.bindBuffer(target, GL.buffers[buffer]);
6289
}
6290
6291
function _emscripten_glBindFramebuffer(target, framebuffer) {
6292
6293
GLctx.bindFramebuffer(target, GL.framebuffers[framebuffer]);
6294
6295
}
6296
6297
function _emscripten_glBindRenderbuffer(target, renderbuffer) {
6298
GLctx.bindRenderbuffer(target, GL.renderbuffers[renderbuffer]);
6299
}
6300
6301
function _emscripten_glBindTexture(target, texture) {
6302
GLctx.bindTexture(target, GL.textures[texture]);
6303
}
6304
6305
function _emscripten_glBindVertexArrayOES(vao) {
6306
GLctx['bindVertexArray'](GL.vaos[vao]);
6307
}
6308
6309
function _emscripten_glBlendColor(x0, x1, x2, x3) { GLctx['blendColor'](x0, x1, x2, x3) }
6310
6311
function _emscripten_glBlendEquation(x0) { GLctx['blendEquation'](x0) }
6312
6313
function _emscripten_glBlendEquationSeparate(x0, x1) { GLctx['blendEquationSeparate'](x0, x1) }
6314
6315
function _emscripten_glBlendFunc(x0, x1) { GLctx['blendFunc'](x0, x1) }
6316
6317
function _emscripten_glBlendFuncSeparate(x0, x1, x2, x3) { GLctx['blendFuncSeparate'](x0, x1, x2, x3) }
6318
6319
function _emscripten_glBufferData(target, size, data, usage) {
6320
// N.b. here first form specifies a heap subarray, second form an integer size, so the ?: code here is polymorphic. It is advised to avoid
6321
// randomly mixing both uses in calling code, to avoid any potential JS engine JIT issues.
6322
GLctx.bufferData(target, data ? HEAPU8.subarray(data, data+size) : size, usage);
6323
}
6324
6325
function _emscripten_glBufferSubData(target, offset, size, data) {
6326
GLctx.bufferSubData(target, offset, HEAPU8.subarray(data, data+size));
6327
}
6328
6329
function _emscripten_glCheckFramebufferStatus(x0) { return GLctx['checkFramebufferStatus'](x0) }
6330
6331
function _emscripten_glClear(x0) { GLctx['clear'](x0) }
6332
6333
function _emscripten_glClearColor(x0, x1, x2, x3) { GLctx['clearColor'](x0, x1, x2, x3) }
6334
6335
function _emscripten_glClearDepthf(x0) { GLctx['clearDepth'](x0) }
6336
6337
function _emscripten_glClearStencil(x0) { GLctx['clearStencil'](x0) }
6338
6339
function _emscripten_glColorMask(red, green, blue, alpha) {
6340
GLctx.colorMask(!!red, !!green, !!blue, !!alpha);
6341
}
6342
6343
function _emscripten_glCompileShader(shader) {
6344
GLctx.compileShader(GL.shaders[shader]);
6345
}
6346
6347
function _emscripten_glCompressedTexImage2D(target, level, internalFormat, width, height, border, imageSize, data) {
6348
GLctx['compressedTexImage2D'](target, level, internalFormat, width, height, border, data ? HEAPU8.subarray((data),(data+imageSize)) : null);
6349
}
6350
6351
function _emscripten_glCompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, imageSize, data) {
6352
GLctx['compressedTexSubImage2D'](target, level, xoffset, yoffset, width, height, format, data ? HEAPU8.subarray((data),(data+imageSize)) : null);
6353
}
6354
6355
function _emscripten_glCopyTexImage2D(x0, x1, x2, x3, x4, x5, x6, x7) { GLctx['copyTexImage2D'](x0, x1, x2, x3, x4, x5, x6, x7) }
6356
6357
function _emscripten_glCopyTexSubImage2D(x0, x1, x2, x3, x4, x5, x6, x7) { GLctx['copyTexSubImage2D'](x0, x1, x2, x3, x4, x5, x6, x7) }
6358
6359
function _emscripten_glCreateProgram() {
6360
var id = GL.getNewId(GL.programs);
6361
var program = GLctx.createProgram();
6362
program.name = id;
6363
GL.programs[id] = program;
6364
return id;
6365
}
6366
6367
function _emscripten_glCreateShader(shaderType) {
6368
var id = GL.getNewId(GL.shaders);
6369
GL.shaders[id] = GLctx.createShader(shaderType);
6370
return id;
6371
}
6372
6373
function _emscripten_glCullFace(x0) { GLctx['cullFace'](x0) }
6374
6375
function _emscripten_glDeleteBuffers(n, buffers) {
6376
for (var i = 0; i < n; i++) {
6377
var id = HEAP32[(((buffers)+(i*4))>>2)];
6378
var buffer = GL.buffers[id];
6379
6380
// From spec: "glDeleteBuffers silently ignores 0's and names that do not
6381
// correspond to existing buffer objects."
6382
if (!buffer) continue;
6383
6384
GLctx.deleteBuffer(buffer);
6385
buffer.name = 0;
6386
GL.buffers[id] = null;
6387
6388
if (id == GL.currArrayBuffer) GL.currArrayBuffer = 0;
6389
if (id == GL.currElementArrayBuffer) GL.currElementArrayBuffer = 0;
6390
}
6391
}
6392
6393
function _emscripten_glDeleteFramebuffers(n, framebuffers) {
6394
for (var i = 0; i < n; ++i) {
6395
var id = HEAP32[(((framebuffers)+(i*4))>>2)];
6396
var framebuffer = GL.framebuffers[id];
6397
if (!framebuffer) continue; // GL spec: "glDeleteFramebuffers silently ignores 0s and names that do not correspond to existing framebuffer objects".
6398
GLctx.deleteFramebuffer(framebuffer);
6399
framebuffer.name = 0;
6400
GL.framebuffers[id] = null;
6401
}
6402
}
6403
6404
function _emscripten_glDeleteProgram(id) {
6405
if (!id) return;
6406
var program = GL.programs[id];
6407
if (!program) { // glDeleteProgram actually signals an error when deleting a nonexisting object, unlike some other GL delete functions.
6408
GL.recordError(0x501 /* GL_INVALID_VALUE */);
6409
return;
6410
}
6411
GLctx.deleteProgram(program);
6412
program.name = 0;
6413
GL.programs[id] = null;
6414
GL.programInfos[id] = null;
6415
}
6416
6417
function _emscripten_glDeleteQueriesEXT(n, ids) {
6418
for (var i = 0; i < n; i++) {
6419
var id = HEAP32[(((ids)+(i*4))>>2)];
6420
var query = GL.timerQueriesEXT[id];
6421
if (!query) continue; // GL spec: "unused names in ids are ignored, as is the name zero."
6422
GLctx.disjointTimerQueryExt['deleteQueryEXT'](query);
6423
GL.timerQueriesEXT[id] = null;
6424
}
6425
}
6426
6427
function _emscripten_glDeleteRenderbuffers(n, renderbuffers) {
6428
for (var i = 0; i < n; i++) {
6429
var id = HEAP32[(((renderbuffers)+(i*4))>>2)];
6430
var renderbuffer = GL.renderbuffers[id];
6431
if (!renderbuffer) continue; // GL spec: "glDeleteRenderbuffers silently ignores 0s and names that do not correspond to existing renderbuffer objects".
6432
GLctx.deleteRenderbuffer(renderbuffer);
6433
renderbuffer.name = 0;
6434
GL.renderbuffers[id] = null;
6435
}
6436
}
6437
6438
function _emscripten_glDeleteShader(id) {
6439
if (!id) return;
6440
var shader = GL.shaders[id];
6441
if (!shader) { // glDeleteShader actually signals an error when deleting a nonexisting object, unlike some other GL delete functions.
6442
GL.recordError(0x501 /* GL_INVALID_VALUE */);
6443
return;
6444
}
6445
GLctx.deleteShader(shader);
6446
GL.shaders[id] = null;
6447
}
6448
6449
function _emscripten_glDeleteTextures(n, textures) {
6450
for (var i = 0; i < n; i++) {
6451
var id = HEAP32[(((textures)+(i*4))>>2)];
6452
var texture = GL.textures[id];
6453
if (!texture) continue; // GL spec: "glDeleteTextures silently ignores 0s and names that do not correspond to existing textures".
6454
GLctx.deleteTexture(texture);
6455
texture.name = 0;
6456
GL.textures[id] = null;
6457
}
6458
}
6459
6460
function _emscripten_glDeleteVertexArraysOES(n, vaos) {
6461
for (var i = 0; i < n; i++) {
6462
var id = HEAP32[(((vaos)+(i*4))>>2)];
6463
GLctx['deleteVertexArray'](GL.vaos[id]);
6464
GL.vaos[id] = null;
6465
}
6466
}
6467
6468
function _emscripten_glDepthFunc(x0) { GLctx['depthFunc'](x0) }
6469
6470
function _emscripten_glDepthMask(flag) {
6471
GLctx.depthMask(!!flag);
6472
}
6473
6474
function _emscripten_glDepthRangef(x0, x1) { GLctx['depthRange'](x0, x1) }
6475
6476
function _emscripten_glDetachShader(program, shader) {
6477
GLctx.detachShader(GL.programs[program],
6478
GL.shaders[shader]);
6479
}
6480
6481
function _emscripten_glDisable(x0) { GLctx['disable'](x0) }
6482
6483
function _emscripten_glDisableVertexAttribArray(index) {
6484
GLctx.disableVertexAttribArray(index);
6485
}
6486
6487
function _emscripten_glDrawArrays(mode, first, count) {
6488
6489
GLctx.drawArrays(mode, first, count);
6490
6491
}
6492
6493
function _emscripten_glDrawArraysInstancedANGLE(mode, first, count, primcount) {
6494
GLctx['drawArraysInstanced'](mode, first, count, primcount);
6495
}
6496
6497
6498
var __tempFixedLengthArray=[];function _emscripten_glDrawBuffersWEBGL(n, bufs) {
6499
6500
var bufArray = __tempFixedLengthArray[n];
6501
for (var i = 0; i < n; i++) {
6502
bufArray[i] = HEAP32[(((bufs)+(i*4))>>2)];
6503
}
6504
6505
GLctx['drawBuffers'](bufArray);
6506
}
6507
6508
function _emscripten_glDrawElements(mode, count, type, indices) {
6509
6510
GLctx.drawElements(mode, count, type, indices);
6511
6512
}
6513
6514
function _emscripten_glDrawElementsInstancedANGLE(mode, count, type, indices, primcount) {
6515
GLctx['drawElementsInstanced'](mode, count, type, indices, primcount);
6516
}
6517
6518
function _emscripten_glEnable(x0) { GLctx['enable'](x0) }
6519
6520
function _emscripten_glEnableVertexAttribArray(index) {
6521
GLctx.enableVertexAttribArray(index);
6522
}
6523
6524
function _emscripten_glEndQueryEXT(target) {
6525
GLctx.disjointTimerQueryExt['endQueryEXT'](target);
6526
}
6527
6528
function _emscripten_glFinish() { GLctx['finish']() }
6529
6530
function _emscripten_glFlush() { GLctx['flush']() }
6531
6532
function _emscripten_glFramebufferRenderbuffer(target, attachment, renderbuffertarget, renderbuffer) {
6533
GLctx.framebufferRenderbuffer(target, attachment, renderbuffertarget,
6534
GL.renderbuffers[renderbuffer]);
6535
}
6536
6537
function _emscripten_glFramebufferTexture2D(target, attachment, textarget, texture, level) {
6538
GLctx.framebufferTexture2D(target, attachment, textarget,
6539
GL.textures[texture], level);
6540
}
6541
6542
function _emscripten_glFrontFace(x0) { GLctx['frontFace'](x0) }
6543
6544
6545
function __glGenObject(n, buffers, createFunction, objectTable
6546
) {
6547
for (var i = 0; i < n; i++) {
6548
var buffer = GLctx[createFunction]();
6549
var id = buffer && GL.getNewId(objectTable);
6550
if (buffer) {
6551
buffer.name = id;
6552
objectTable[id] = buffer;
6553
} else {
6554
GL.recordError(0x502 /* GL_INVALID_OPERATION */);
6555
}
6556
HEAP32[(((buffers)+(i*4))>>2)]=id;
6557
}
6558
}function _emscripten_glGenBuffers(n, buffers) {
6559
__glGenObject(n, buffers, 'createBuffer', GL.buffers
6560
);
6561
}
6562
6563
function _emscripten_glGenFramebuffers(n, ids) {
6564
__glGenObject(n, ids, 'createFramebuffer', GL.framebuffers
6565
);
6566
}
6567
6568
function _emscripten_glGenQueriesEXT(n, ids) {
6569
for (var i = 0; i < n; i++) {
6570
var query = GLctx.disjointTimerQueryExt['createQueryEXT']();
6571
if (!query) {
6572
GL.recordError(0x502 /* GL_INVALID_OPERATION */);
6573
while(i < n) HEAP32[(((ids)+(i++*4))>>2)]=0;
6574
return;
6575
}
6576
var id = GL.getNewId(GL.timerQueriesEXT);
6577
query.name = id;
6578
GL.timerQueriesEXT[id] = query;
6579
HEAP32[(((ids)+(i*4))>>2)]=id;
6580
}
6581
}
6582
6583
function _emscripten_glGenRenderbuffers(n, renderbuffers) {
6584
__glGenObject(n, renderbuffers, 'createRenderbuffer', GL.renderbuffers
6585
);
6586
}
6587
6588
function _emscripten_glGenTextures(n, textures) {
6589
__glGenObject(n, textures, 'createTexture', GL.textures
6590
);
6591
}
6592
6593
function _emscripten_glGenVertexArraysOES(n, arrays) {
6594
__glGenObject(n, arrays, 'createVertexArray', GL.vaos
6595
);
6596
}
6597
6598
function _emscripten_glGenerateMipmap(x0) { GLctx['generateMipmap'](x0) }
6599
6600
function _emscripten_glGetActiveAttrib(program, index, bufSize, length, size, type, name) {
6601
program = GL.programs[program];
6602
var info = GLctx.getActiveAttrib(program, index);
6603
if (!info) return; // If an error occurs, nothing will be written to length, size and type and name.
6604
6605
var numBytesWrittenExclNull = (bufSize > 0 && name) ? stringToUTF8(info.name, name, bufSize) : 0;
6606
if (length) HEAP32[((length)>>2)]=numBytesWrittenExclNull;
6607
if (size) HEAP32[((size)>>2)]=info.size;
6608
if (type) HEAP32[((type)>>2)]=info.type;
6609
}
6610
6611
function _emscripten_glGetActiveUniform(program, index, bufSize, length, size, type, name) {
6612
program = GL.programs[program];
6613
var info = GLctx.getActiveUniform(program, index);
6614
if (!info) return; // If an error occurs, nothing will be written to length, size, type and name.
6615
6616
var numBytesWrittenExclNull = (bufSize > 0 && name) ? stringToUTF8(info.name, name, bufSize) : 0;
6617
if (length) HEAP32[((length)>>2)]=numBytesWrittenExclNull;
6618
if (size) HEAP32[((size)>>2)]=info.size;
6619
if (type) HEAP32[((type)>>2)]=info.type;
6620
}
6621
6622
function _emscripten_glGetAttachedShaders(program, maxCount, count, shaders) {
6623
var result = GLctx.getAttachedShaders(GL.programs[program]);
6624
var len = result.length;
6625
if (len > maxCount) {
6626
len = maxCount;
6627
}
6628
HEAP32[((count)>>2)]=len;
6629
for (var i = 0; i < len; ++i) {
6630
var id = GL.shaders.indexOf(result[i]);
6631
HEAP32[(((shaders)+(i*4))>>2)]=id;
6632
}
6633
}
6634
6635
function _emscripten_glGetAttribLocation(program, name) {
6636
return GLctx.getAttribLocation(GL.programs[program], UTF8ToString(name));
6637
}
6638
6639
6640
6641
6642
function readI53FromI64(ptr) {
6643
return HEAPU32[ptr>>2] + HEAP32[ptr+4>>2] * 4294967296;
6644
}
6645
6646
function readI53FromU64(ptr) {
6647
return HEAPU32[ptr>>2] + HEAPU32[ptr+4>>2] * 4294967296;
6648
}function writeI53ToI64(ptr, num) {
6649
HEAPU32[ptr>>2] = num;
6650
HEAPU32[ptr+4>>2] = (num - HEAPU32[ptr>>2])/4294967296;
6651
var deserialized = (num >= 0) ? readI53FromU64(ptr) : readI53FromI64(ptr);
6652
if (deserialized != num) warnOnce('writeI53ToI64() out of range: serialized JS Number ' + num + ' to Wasm heap as bytes lo=0x' + HEAPU32[ptr>>2].toString(16) + ', hi=0x' + HEAPU32[ptr+4>>2].toString(16) + ', which deserializes back to ' + deserialized + ' instead!');
6653
}function emscriptenWebGLGet(name_, p, type) {
6654
// Guard against user passing a null pointer.
6655
// Note that GLES2 spec does not say anything about how passing a null pointer should be treated.
6656
// Testing on desktop core GL 3, the application crashes on glGetIntegerv to a null pointer, but
6657
// better to report an error instead of doing anything random.
6658
if (!p) {
6659
GL.recordError(0x501 /* GL_INVALID_VALUE */);
6660
return;
6661
}
6662
var ret = undefined;
6663
switch(name_) { // Handle a few trivial GLES values
6664
case 0x8DFA: // GL_SHADER_COMPILER
6665
ret = 1;
6666
break;
6667
case 0x8DF8: // GL_SHADER_BINARY_FORMATS
6668
if (type != 0 && type != 1) {
6669
GL.recordError(0x500); // GL_INVALID_ENUM
6670
}
6671
return; // Do not write anything to the out pointer, since no binary formats are supported.
6672
case 0x8DF9: // GL_NUM_SHADER_BINARY_FORMATS
6673
ret = 0;
6674
break;
6675
case 0x86A2: // GL_NUM_COMPRESSED_TEXTURE_FORMATS
6676
// WebGL doesn't have GL_NUM_COMPRESSED_TEXTURE_FORMATS (it's obsolete since GL_COMPRESSED_TEXTURE_FORMATS returns a JS array that can be queried for length),
6677
// so implement it ourselves to allow C++ GLES2 code get the length.
6678
var formats = GLctx.getParameter(0x86A3 /*GL_COMPRESSED_TEXTURE_FORMATS*/);
6679
ret = formats ? formats.length : 0;
6680
break;
6681
}
6682
6683
if (ret === undefined) {
6684
var result = GLctx.getParameter(name_);
6685
switch (typeof(result)) {
6686
case "number":
6687
ret = result;
6688
break;
6689
case "boolean":
6690
ret = result ? 1 : 0;
6691
break;
6692
case "string":
6693
GL.recordError(0x500); // GL_INVALID_ENUM
6694
return;
6695
case "object":
6696
if (result === null) {
6697
// null is a valid result for some (e.g., which buffer is bound - perhaps nothing is bound), but otherwise
6698
// can mean an invalid name_, which we need to report as an error
6699
switch(name_) {
6700
case 0x8894: // ARRAY_BUFFER_BINDING
6701
case 0x8B8D: // CURRENT_PROGRAM
6702
case 0x8895: // ELEMENT_ARRAY_BUFFER_BINDING
6703
case 0x8CA6: // FRAMEBUFFER_BINDING
6704
case 0x8CA7: // RENDERBUFFER_BINDING
6705
case 0x8069: // TEXTURE_BINDING_2D
6706
case 0x85B5: // WebGL 2 GL_VERTEX_ARRAY_BINDING, or WebGL 1 extension OES_vertex_array_object GL_VERTEX_ARRAY_BINDING_OES
6707
case 0x8514: { // TEXTURE_BINDING_CUBE_MAP
6708
ret = 0;
6709
break;
6710
}
6711
default: {
6712
GL.recordError(0x500); // GL_INVALID_ENUM
6713
return;
6714
}
6715
}
6716
} else if (result instanceof Float32Array ||
6717
result instanceof Uint32Array ||
6718
result instanceof Int32Array ||
6719
result instanceof Array) {
6720
for (var i = 0; i < result.length; ++i) {
6721
switch (type) {
6722
case 0: HEAP32[(((p)+(i*4))>>2)]=result[i]; break;
6723
case 2: HEAPF32[(((p)+(i*4))>>2)]=result[i]; break;
6724
case 4: HEAP8[(((p)+(i))>>0)]=result[i] ? 1 : 0; break;
6725
}
6726
}
6727
return;
6728
} else {
6729
try {
6730
ret = result.name | 0;
6731
} catch(e) {
6732
GL.recordError(0x500); // GL_INVALID_ENUM
6733
err('GL_INVALID_ENUM in glGet' + type + 'v: Unknown object returned from WebGL getParameter(' + name_ + ')! (error: ' + e + ')');
6734
return;
6735
}
6736
}
6737
break;
6738
default:
6739
GL.recordError(0x500); // GL_INVALID_ENUM
6740
err('GL_INVALID_ENUM in glGet' + type + 'v: Native code calling glGet' + type + 'v(' + name_ + ') and it returns ' + result + ' of type ' + typeof(result) + '!');
6741
return;
6742
}
6743
}
6744
6745
switch (type) {
6746
case 1: writeI53ToI64(p, ret); break;
6747
case 0: HEAP32[((p)>>2)]=ret; break;
6748
case 2: HEAPF32[((p)>>2)]=ret; break;
6749
case 4: HEAP8[((p)>>0)]=ret ? 1 : 0; break;
6750
}
6751
}function _emscripten_glGetBooleanv(name_, p) {
6752
emscriptenWebGLGet(name_, p, 4);
6753
}
6754
6755
function _emscripten_glGetBufferParameteriv(target, value, data) {
6756
if (!data) {
6757
// GLES2 specification does not specify how to behave if data is a null pointer. Since calling this function does not make sense
6758
// if data == null, issue a GL error to notify user about it.
6759
GL.recordError(0x501 /* GL_INVALID_VALUE */);
6760
return;
6761
}
6762
HEAP32[((data)>>2)]=GLctx.getBufferParameter(target, value);
6763
}
6764
6765
function _emscripten_glGetError() {
6766
var error = GLctx.getError() || GL.lastError;
6767
GL.lastError = 0/*GL_NO_ERROR*/;
6768
return error;
6769
}
6770
6771
function _emscripten_glGetFloatv(name_, p) {
6772
emscriptenWebGLGet(name_, p, 2);
6773
}
6774
6775
function _emscripten_glGetFramebufferAttachmentParameteriv(target, attachment, pname, params) {
6776
var result = GLctx.getFramebufferAttachmentParameter(target, attachment, pname);
6777
if (result instanceof WebGLRenderbuffer ||
6778
result instanceof WebGLTexture) {
6779
result = result.name | 0;
6780
}
6781
HEAP32[((params)>>2)]=result;
6782
}
6783
6784
function _emscripten_glGetIntegerv(name_, p) {
6785
emscriptenWebGLGet(name_, p, 0);
6786
}
6787
6788
function _emscripten_glGetProgramInfoLog(program, maxLength, length, infoLog) {
6789
var log = GLctx.getProgramInfoLog(GL.programs[program]);
6790
if (log === null) log = '(unknown error)';
6791
var numBytesWrittenExclNull = (maxLength > 0 && infoLog) ? stringToUTF8(log, infoLog, maxLength) : 0;
6792
if (length) HEAP32[((length)>>2)]=numBytesWrittenExclNull;
6793
}
6794
6795
function _emscripten_glGetProgramiv(program, pname, p) {
6796
if (!p) {
6797
// GLES2 specification does not specify how to behave if p is a null pointer. Since calling this function does not make sense
6798
// if p == null, issue a GL error to notify user about it.
6799
GL.recordError(0x501 /* GL_INVALID_VALUE */);
6800
return;
6801
}
6802
6803
if (program >= GL.counter) {
6804
GL.recordError(0x501 /* GL_INVALID_VALUE */);
6805
return;
6806
}
6807
6808
var ptable = GL.programInfos[program];
6809
if (!ptable) {
6810
GL.recordError(0x502 /* GL_INVALID_OPERATION */);
6811
return;
6812
}
6813
6814
if (pname == 0x8B84) { // GL_INFO_LOG_LENGTH
6815
var log = GLctx.getProgramInfoLog(GL.programs[program]);
6816
if (log === null) log = '(unknown error)';
6817
HEAP32[((p)>>2)]=log.length + 1;
6818
} else if (pname == 0x8B87 /* GL_ACTIVE_UNIFORM_MAX_LENGTH */) {
6819
HEAP32[((p)>>2)]=ptable.maxUniformLength;
6820
} else if (pname == 0x8B8A /* GL_ACTIVE_ATTRIBUTE_MAX_LENGTH */) {
6821
if (ptable.maxAttributeLength == -1) {
6822
program = GL.programs[program];
6823
var numAttribs = GLctx.getProgramParameter(program, 0x8B89/*GL_ACTIVE_ATTRIBUTES*/);
6824
ptable.maxAttributeLength = 0; // Spec says if there are no active attribs, 0 must be returned.
6825
for (var i = 0; i < numAttribs; ++i) {
6826
var activeAttrib = GLctx.getActiveAttrib(program, i);
6827
ptable.maxAttributeLength = Math.max(ptable.maxAttributeLength, activeAttrib.name.length+1);
6828
}
6829
}
6830
HEAP32[((p)>>2)]=ptable.maxAttributeLength;
6831
} else if (pname == 0x8A35 /* GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH */) {
6832
if (ptable.maxUniformBlockNameLength == -1) {
6833
program = GL.programs[program];
6834
var numBlocks = GLctx.getProgramParameter(program, 0x8A36/*GL_ACTIVE_UNIFORM_BLOCKS*/);
6835
ptable.maxUniformBlockNameLength = 0;
6836
for (var i = 0; i < numBlocks; ++i) {
6837
var activeBlockName = GLctx.getActiveUniformBlockName(program, i);
6838
ptable.maxUniformBlockNameLength = Math.max(ptable.maxUniformBlockNameLength, activeBlockName.length+1);
6839
}
6840
}
6841
HEAP32[((p)>>2)]=ptable.maxUniformBlockNameLength;
6842
} else {
6843
HEAP32[((p)>>2)]=GLctx.getProgramParameter(GL.programs[program], pname);
6844
}
6845
}
6846
6847
function _emscripten_glGetQueryObjecti64vEXT(id, pname, params) {
6848
if (!params) {
6849
// GLES2 specification does not specify how to behave if params is a null pointer. Since calling this function does not make sense
6850
// if p == null, issue a GL error to notify user about it.
6851
GL.recordError(0x501 /* GL_INVALID_VALUE */);
6852
return;
6853
}
6854
var query = GL.timerQueriesEXT[id];
6855
var param = GLctx.disjointTimerQueryExt['getQueryObjectEXT'](query, pname);
6856
var ret;
6857
if (typeof param == 'boolean') {
6858
ret = param ? 1 : 0;
6859
} else {
6860
ret = param;
6861
}
6862
writeI53ToI64(params, ret);
6863
}
6864
6865
function _emscripten_glGetQueryObjectivEXT(id, pname, params) {
6866
if (!params) {
6867
// GLES2 specification does not specify how to behave if params is a null pointer. Since calling this function does not make sense
6868
// if p == null, issue a GL error to notify user about it.
6869
GL.recordError(0x501 /* GL_INVALID_VALUE */);
6870
return;
6871
}
6872
var query = GL.timerQueriesEXT[id];
6873
var param = GLctx.disjointTimerQueryExt['getQueryObjectEXT'](query, pname);
6874
var ret;
6875
if (typeof param == 'boolean') {
6876
ret = param ? 1 : 0;
6877
} else {
6878
ret = param;
6879
}
6880
HEAP32[((params)>>2)]=ret;
6881
}
6882
6883
function _emscripten_glGetQueryObjectui64vEXT(id, pname, params) {
6884
if (!params) {
6885
// GLES2 specification does not specify how to behave if params is a null pointer. Since calling this function does not make sense
6886
// if p == null, issue a GL error to notify user about it.
6887
GL.recordError(0x501 /* GL_INVALID_VALUE */);
6888
return;
6889
}
6890
var query = GL.timerQueriesEXT[id];
6891
var param = GLctx.disjointTimerQueryExt['getQueryObjectEXT'](query, pname);
6892
var ret;
6893
if (typeof param == 'boolean') {
6894
ret = param ? 1 : 0;
6895
} else {
6896
ret = param;
6897
}
6898
writeI53ToI64(params, ret);
6899
}
6900
6901
function _emscripten_glGetQueryObjectuivEXT(id, pname, params) {
6902
if (!params) {
6903
// GLES2 specification does not specify how to behave if params is a null pointer. Since calling this function does not make sense
6904
// if p == null, issue a GL error to notify user about it.
6905
GL.recordError(0x501 /* GL_INVALID_VALUE */);
6906
return;
6907
}
6908
var query = GL.timerQueriesEXT[id];
6909
var param = GLctx.disjointTimerQueryExt['getQueryObjectEXT'](query, pname);
6910
var ret;
6911
if (typeof param == 'boolean') {
6912
ret = param ? 1 : 0;
6913
} else {
6914
ret = param;
6915
}
6916
HEAP32[((params)>>2)]=ret;
6917
}
6918
6919
function _emscripten_glGetQueryivEXT(target, pname, params) {
6920
if (!params) {
6921
// GLES2 specification does not specify how to behave if params is a null pointer. Since calling this function does not make sense
6922
// if p == null, issue a GL error to notify user about it.
6923
GL.recordError(0x501 /* GL_INVALID_VALUE */);
6924
return;
6925
}
6926
HEAP32[((params)>>2)]=GLctx.disjointTimerQueryExt['getQueryEXT'](target, pname);
6927
}
6928
6929
function _emscripten_glGetRenderbufferParameteriv(target, pname, params) {
6930
if (!params) {
6931
// GLES2 specification does not specify how to behave if params is a null pointer. Since calling this function does not make sense
6932
// if params == null, issue a GL error to notify user about it.
6933
GL.recordError(0x501 /* GL_INVALID_VALUE */);
6934
return;
6935
}
6936
HEAP32[((params)>>2)]=GLctx.getRenderbufferParameter(target, pname);
6937
}
6938
6939
function _emscripten_glGetShaderInfoLog(shader, maxLength, length, infoLog) {
6940
var log = GLctx.getShaderInfoLog(GL.shaders[shader]);
6941
if (log === null) log = '(unknown error)';
6942
var numBytesWrittenExclNull = (maxLength > 0 && infoLog) ? stringToUTF8(log, infoLog, maxLength) : 0;
6943
if (length) HEAP32[((length)>>2)]=numBytesWrittenExclNull;
6944
}
6945
6946
function _emscripten_glGetShaderPrecisionFormat(shaderType, precisionType, range, precision) {
6947
var result = GLctx.getShaderPrecisionFormat(shaderType, precisionType);
6948
HEAP32[((range)>>2)]=result.rangeMin;
6949
HEAP32[(((range)+(4))>>2)]=result.rangeMax;
6950
HEAP32[((precision)>>2)]=result.precision;
6951
}
6952
6953
function _emscripten_glGetShaderSource(shader, bufSize, length, source) {
6954
var result = GLctx.getShaderSource(GL.shaders[shader]);
6955
if (!result) return; // If an error occurs, nothing will be written to length or source.
6956
var numBytesWrittenExclNull = (bufSize > 0 && source) ? stringToUTF8(result, source, bufSize) : 0;
6957
if (length) HEAP32[((length)>>2)]=numBytesWrittenExclNull;
6958
}
6959
6960
function _emscripten_glGetShaderiv(shader, pname, p) {
6961
if (!p) {
6962
// GLES2 specification does not specify how to behave if p is a null pointer. Since calling this function does not make sense
6963
// if p == null, issue a GL error to notify user about it.
6964
GL.recordError(0x501 /* GL_INVALID_VALUE */);
6965
return;
6966
}
6967
if (pname == 0x8B84) { // GL_INFO_LOG_LENGTH
6968
var log = GLctx.getShaderInfoLog(GL.shaders[shader]);
6969
if (log === null) log = '(unknown error)';
6970
HEAP32[((p)>>2)]=log.length + 1;
6971
} else if (pname == 0x8B88) { // GL_SHADER_SOURCE_LENGTH
6972
var source = GLctx.getShaderSource(GL.shaders[shader]);
6973
var sourceLength = (source === null || source.length == 0) ? 0 : source.length + 1;
6974
HEAP32[((p)>>2)]=sourceLength;
6975
} else {
6976
HEAP32[((p)>>2)]=GLctx.getShaderParameter(GL.shaders[shader], pname);
6977
}
6978
}
6979
6980
6981
function stringToNewUTF8(jsString) {
6982
var length = lengthBytesUTF8(jsString)+1;
6983
var cString = _malloc(length);
6984
stringToUTF8(jsString, cString, length);
6985
return cString;
6986
}function _emscripten_glGetString(name_) {
6987
if (GL.stringCache[name_]) return GL.stringCache[name_];
6988
var ret;
6989
switch(name_) {
6990
case 0x1F03 /* GL_EXTENSIONS */:
6991
var exts = GLctx.getSupportedExtensions() || []; // .getSupportedExtensions() can return null if context is lost, so coerce to empty array.
6992
exts = exts.concat(exts.map(function(e) { return "GL_" + e; }));
6993
ret = stringToNewUTF8(exts.join(' '));
6994
break;
6995
case 0x1F00 /* GL_VENDOR */:
6996
case 0x1F01 /* GL_RENDERER */:
6997
case 0x9245 /* UNMASKED_VENDOR_WEBGL */:
6998
case 0x9246 /* UNMASKED_RENDERER_WEBGL */:
6999
var s = GLctx.getParameter(name_);
7000
if (!s) {
7001
GL.recordError(0x500/*GL_INVALID_ENUM*/);
7002
}
7003
ret = stringToNewUTF8(s);
7004
break;
7005
7006
case 0x1F02 /* GL_VERSION */:
7007
var glVersion = GLctx.getParameter(0x1F02 /*GL_VERSION*/);
7008
// return GLES version string corresponding to the version of the WebGL context
7009
{
7010
glVersion = 'OpenGL ES 2.0 (' + glVersion + ')';
7011
}
7012
ret = stringToNewUTF8(glVersion);
7013
break;
7014
case 0x8B8C /* GL_SHADING_LANGUAGE_VERSION */:
7015
var glslVersion = GLctx.getParameter(0x8B8C /*GL_SHADING_LANGUAGE_VERSION*/);
7016
// extract the version number 'N.M' from the string 'WebGL GLSL ES N.M ...'
7017
var ver_re = /^WebGL GLSL ES ([0-9]\.[0-9][0-9]?)(?:$| .*)/;
7018
var ver_num = glslVersion.match(ver_re);
7019
if (ver_num !== null) {
7020
if (ver_num[1].length == 3) ver_num[1] = ver_num[1] + '0'; // ensure minor version has 2 digits
7021
glslVersion = 'OpenGL ES GLSL ES ' + ver_num[1] + ' (' + glslVersion + ')';
7022
}
7023
ret = stringToNewUTF8(glslVersion);
7024
break;
7025
default:
7026
GL.recordError(0x500/*GL_INVALID_ENUM*/);
7027
return 0;
7028
}
7029
GL.stringCache[name_] = ret;
7030
return ret;
7031
}
7032
7033
function _emscripten_glGetTexParameterfv(target, pname, params) {
7034
if (!params) {
7035
// GLES2 specification does not specify how to behave if params is a null pointer. Since calling this function does not make sense
7036
// if p == null, issue a GL error to notify user about it.
7037
GL.recordError(0x501 /* GL_INVALID_VALUE */);
7038
return;
7039
}
7040
HEAPF32[((params)>>2)]=GLctx.getTexParameter(target, pname);
7041
}
7042
7043
function _emscripten_glGetTexParameteriv(target, pname, params) {
7044
if (!params) {
7045
// GLES2 specification does not specify how to behave if params is a null pointer. Since calling this function does not make sense
7046
// if p == null, issue a GL error to notify user about it.
7047
GL.recordError(0x501 /* GL_INVALID_VALUE */);
7048
return;
7049
}
7050
HEAP32[((params)>>2)]=GLctx.getTexParameter(target, pname);
7051
}
7052
7053
7054
function jstoi_q(str) {
7055
// TODO: If issues below are resolved, add a suitable suppression or remove this comment.
7056
return parseInt(str, undefined /* https://github.com/google/closure-compiler/issues/3230 / https://github.com/google/closure-compiler/issues/3548 */);
7057
}function _emscripten_glGetUniformLocation(program, name) {
7058
name = UTF8ToString(name);
7059
7060
var arrayIndex = 0;
7061
// If user passed an array accessor "[index]", parse the array index off the accessor.
7062
if (name[name.length - 1] == ']') {
7063
var leftBrace = name.lastIndexOf('[');
7064
arrayIndex = name[leftBrace+1] != ']' ? jstoi_q(name.slice(leftBrace + 1)) : 0; // "index]", parseInt will ignore the ']' at the end; but treat "foo[]" as "foo[0]"
7065
name = name.slice(0, leftBrace);
7066
}
7067
7068
var uniformInfo = GL.programInfos[program] && GL.programInfos[program].uniforms[name]; // returns pair [ dimension_of_uniform_array, uniform_location ]
7069
if (uniformInfo && arrayIndex >= 0 && arrayIndex < uniformInfo[0]) { // Check if user asked for an out-of-bounds element, i.e. for 'vec4 colors[3];' user could ask for 'colors[10]' which should return -1.
7070
return uniformInfo[1] + arrayIndex;
7071
} else {
7072
return -1;
7073
}
7074
}
7075
7076
7077
/** @suppress{checkTypes} */
7078
function emscriptenWebGLGetUniform(program, location, params, type) {
7079
if (!params) {
7080
// GLES2 specification does not specify how to behave if params is a null pointer. Since calling this function does not make sense
7081
// if params == null, issue a GL error to notify user about it.
7082
GL.recordError(0x501 /* GL_INVALID_VALUE */);
7083
return;
7084
}
7085
var data = GLctx.getUniform(GL.programs[program], GL.uniforms[location]);
7086
if (typeof data == 'number' || typeof data == 'boolean') {
7087
switch (type) {
7088
case 0: HEAP32[((params)>>2)]=data; break;
7089
case 2: HEAPF32[((params)>>2)]=data; break;
7090
default: throw 'internal emscriptenWebGLGetUniform() error, bad type: ' + type;
7091
}
7092
} else {
7093
for (var i = 0; i < data.length; i++) {
7094
switch (type) {
7095
case 0: HEAP32[(((params)+(i*4))>>2)]=data[i]; break;
7096
case 2: HEAPF32[(((params)+(i*4))>>2)]=data[i]; break;
7097
default: throw 'internal emscriptenWebGLGetUniform() error, bad type: ' + type;
7098
}
7099
}
7100
}
7101
}function _emscripten_glGetUniformfv(program, location, params) {
7102
emscriptenWebGLGetUniform(program, location, params, 2);
7103
}
7104
7105
function _emscripten_glGetUniformiv(program, location, params) {
7106
emscriptenWebGLGetUniform(program, location, params, 0);
7107
}
7108
7109
function _emscripten_glGetVertexAttribPointerv(index, pname, pointer) {
7110
if (!pointer) {
7111
// GLES2 specification does not specify how to behave if pointer is a null pointer. Since calling this function does not make sense
7112
// if pointer == null, issue a GL error to notify user about it.
7113
GL.recordError(0x501 /* GL_INVALID_VALUE */);
7114
return;
7115
}
7116
HEAP32[((pointer)>>2)]=GLctx.getVertexAttribOffset(index, pname);
7117
}
7118
7119
7120
/** @suppress{checkTypes} */
7121
function emscriptenWebGLGetVertexAttrib(index, pname, params, type) {
7122
if (!params) {
7123
// GLES2 specification does not specify how to behave if params is a null pointer. Since calling this function does not make sense
7124
// if params == null, issue a GL error to notify user about it.
7125
GL.recordError(0x501 /* GL_INVALID_VALUE */);
7126
return;
7127
}
7128
var data = GLctx.getVertexAttrib(index, pname);
7129
if (pname == 0x889F/*VERTEX_ATTRIB_ARRAY_BUFFER_BINDING*/) {
7130
HEAP32[((params)>>2)]=data["name"];
7131
} else if (typeof data == 'number' || typeof data == 'boolean') {
7132
switch (type) {
7133
case 0: HEAP32[((params)>>2)]=data; break;
7134
case 2: HEAPF32[((params)>>2)]=data; break;
7135
case 5: HEAP32[((params)>>2)]=Math.fround(data); break;
7136
default: throw 'internal emscriptenWebGLGetVertexAttrib() error, bad type: ' + type;
7137
}
7138
} else {
7139
for (var i = 0; i < data.length; i++) {
7140
switch (type) {
7141
case 0: HEAP32[(((params)+(i*4))>>2)]=data[i]; break;
7142
case 2: HEAPF32[(((params)+(i*4))>>2)]=data[i]; break;
7143
case 5: HEAP32[(((params)+(i*4))>>2)]=Math.fround(data[i]); break;
7144
default: throw 'internal emscriptenWebGLGetVertexAttrib() error, bad type: ' + type;
7145
}
7146
}
7147
}
7148
}function _emscripten_glGetVertexAttribfv(index, pname, params) {
7149
// N.B. This function may only be called if the vertex attribute was specified using the function glVertexAttrib*f(),
7150
// otherwise the results are undefined. (GLES3 spec 6.1.12)
7151
emscriptenWebGLGetVertexAttrib(index, pname, params, 2);
7152
}
7153
7154
function _emscripten_glGetVertexAttribiv(index, pname, params) {
7155
// N.B. This function may only be called if the vertex attribute was specified using the function glVertexAttrib*f(),
7156
// otherwise the results are undefined. (GLES3 spec 6.1.12)
7157
emscriptenWebGLGetVertexAttrib(index, pname, params, 5);
7158
}
7159
7160
function _emscripten_glHint(x0, x1) { GLctx['hint'](x0, x1) }
7161
7162
function _emscripten_glIsBuffer(buffer) {
7163
var b = GL.buffers[buffer];
7164
if (!b) return 0;
7165
return GLctx.isBuffer(b);
7166
}
7167
7168
function _emscripten_glIsEnabled(x0) { return GLctx['isEnabled'](x0) }
7169
7170
function _emscripten_glIsFramebuffer(framebuffer) {
7171
var fb = GL.framebuffers[framebuffer];
7172
if (!fb) return 0;
7173
return GLctx.isFramebuffer(fb);
7174
}
7175
7176
function _emscripten_glIsProgram(program) {
7177
program = GL.programs[program];
7178
if (!program) return 0;
7179
return GLctx.isProgram(program);
7180
}
7181
7182
function _emscripten_glIsQueryEXT(id) {
7183
var query = GL.timerQueriesEXT[id];
7184
if (!query) return 0;
7185
return GLctx.disjointTimerQueryExt['isQueryEXT'](query);
7186
}
7187
7188
function _emscripten_glIsRenderbuffer(renderbuffer) {
7189
var rb = GL.renderbuffers[renderbuffer];
7190
if (!rb) return 0;
7191
return GLctx.isRenderbuffer(rb);
7192
}
7193
7194
function _emscripten_glIsShader(shader) {
7195
var s = GL.shaders[shader];
7196
if (!s) return 0;
7197
return GLctx.isShader(s);
7198
}
7199
7200
function _emscripten_glIsTexture(id) {
7201
var texture = GL.textures[id];
7202
if (!texture) return 0;
7203
return GLctx.isTexture(texture);
7204
}
7205
7206
function _emscripten_glIsVertexArrayOES(array) {
7207
7208
var vao = GL.vaos[array];
7209
if (!vao) return 0;
7210
return GLctx['isVertexArray'](vao);
7211
}
7212
7213
function _emscripten_glLineWidth(x0) { GLctx['lineWidth'](x0) }
7214
7215
function _emscripten_glLinkProgram(program) {
7216
GLctx.linkProgram(GL.programs[program]);
7217
GL.populateUniformTable(program);
7218
}
7219
7220
function _emscripten_glPixelStorei(pname, param) {
7221
if (pname == 0xCF5 /* GL_UNPACK_ALIGNMENT */) {
7222
GL.unpackAlignment = param;
7223
}
7224
GLctx.pixelStorei(pname, param);
7225
}
7226
7227
function _emscripten_glPolygonOffset(x0, x1) { GLctx['polygonOffset'](x0, x1) }
7228
7229
function _emscripten_glQueryCounterEXT(id, target) {
7230
GLctx.disjointTimerQueryExt['queryCounterEXT'](GL.timerQueriesEXT[id], target);
7231
}
7232
7233
7234
7235
function __computeUnpackAlignedImageSize(width, height, sizePerPixel, alignment) {
7236
function roundedToNextMultipleOf(x, y) {
7237
return (x + y - 1) & -y;
7238
}
7239
var plainRowSize = width * sizePerPixel;
7240
var alignedRowSize = roundedToNextMultipleOf(plainRowSize, alignment);
7241
return height * alignedRowSize;
7242
}
7243
7244
function __colorChannelsInGlTextureFormat(format) {
7245
// Micro-optimizations for size: map format to size by subtracting smallest enum value (0x1902) from all values first.
7246
// Also omit the most common size value (1) from the list, which is assumed by formats not on the list.
7247
var colorChannels = {
7248
// 0x1902 /* GL_DEPTH_COMPONENT */ - 0x1902: 1,
7249
// 0x1906 /* GL_ALPHA */ - 0x1902: 1,
7250
5: 3,
7251
6: 4,
7252
// 0x1909 /* GL_LUMINANCE */ - 0x1902: 1,
7253
8: 2,
7254
29502: 3,
7255
29504: 4,
7256
};
7257
return colorChannels[format - 0x1902]||1;
7258
}
7259
7260
function __heapObjectForWebGLType(type) {
7261
// Micro-optimization for size: Subtract lowest GL enum number (0x1400/* GL_BYTE */) from type to compare
7262
// smaller values for the heap, for shorter generated code size.
7263
// Also the type HEAPU16 is not tested for explicitly, but any unrecognized type will return out HEAPU16.
7264
// (since most types are HEAPU16)
7265
type -= 0x1400;
7266
7267
if (type == 1) return HEAPU8;
7268
7269
7270
if (type == 4) return HEAP32;
7271
7272
if (type == 6) return HEAPF32;
7273
7274
if (type == 5
7275
|| type == 28922
7276
)
7277
return HEAPU32;
7278
7279
return HEAPU16;
7280
}
7281
7282
function __heapAccessShiftForWebGLHeap(heap) {
7283
return 31 - Math.clz32(heap.BYTES_PER_ELEMENT);
7284
}function emscriptenWebGLGetTexPixelData(type, format, width, height, pixels, internalFormat) {
7285
var heap = __heapObjectForWebGLType(type);
7286
var shift = __heapAccessShiftForWebGLHeap(heap);
7287
var byteSize = 1<<shift;
7288
var sizePerPixel = __colorChannelsInGlTextureFormat(format) * byteSize;
7289
var bytes = __computeUnpackAlignedImageSize(width, height, sizePerPixel, GL.unpackAlignment);
7290
return heap.subarray(pixels >> shift, pixels + bytes >> shift);
7291
}function _emscripten_glReadPixels(x, y, width, height, format, type, pixels) {
7292
var pixelData = emscriptenWebGLGetTexPixelData(type, format, width, height, pixels, format);
7293
if (!pixelData) {
7294
GL.recordError(0x500/*GL_INVALID_ENUM*/);
7295
return;
7296
}
7297
GLctx.readPixels(x, y, width, height, format, type, pixelData);
7298
}
7299
7300
function _emscripten_glReleaseShaderCompiler() {
7301
// NOP (as allowed by GLES 2.0 spec)
7302
}
7303
7304
function _emscripten_glRenderbufferStorage(x0, x1, x2, x3) { GLctx['renderbufferStorage'](x0, x1, x2, x3) }
7305
7306
function _emscripten_glSampleCoverage(value, invert) {
7307
GLctx.sampleCoverage(value, !!invert);
7308
}
7309
7310
function _emscripten_glScissor(x0, x1, x2, x3) { GLctx['scissor'](x0, x1, x2, x3) }
7311
7312
function _emscripten_glShaderBinary() {
7313
GL.recordError(0x500/*GL_INVALID_ENUM*/);
7314
}
7315
7316
function _emscripten_glShaderSource(shader, count, string, length) {
7317
var source = GL.getSource(shader, count, string, length);
7318
7319
7320
GLctx.shaderSource(GL.shaders[shader], source);
7321
}
7322
7323
function _emscripten_glStencilFunc(x0, x1, x2) { GLctx['stencilFunc'](x0, x1, x2) }
7324
7325
function _emscripten_glStencilFuncSeparate(x0, x1, x2, x3) { GLctx['stencilFuncSeparate'](x0, x1, x2, x3) }
7326
7327
function _emscripten_glStencilMask(x0) { GLctx['stencilMask'](x0) }
7328
7329
function _emscripten_glStencilMaskSeparate(x0, x1) { GLctx['stencilMaskSeparate'](x0, x1) }
7330
7331
function _emscripten_glStencilOp(x0, x1, x2) { GLctx['stencilOp'](x0, x1, x2) }
7332
7333
function _emscripten_glStencilOpSeparate(x0, x1, x2, x3) { GLctx['stencilOpSeparate'](x0, x1, x2, x3) }
7334
7335
function _emscripten_glTexImage2D(target, level, internalFormat, width, height, border, format, type, pixels) {
7336
GLctx.texImage2D(target, level, internalFormat, width, height, border, format, type, pixels ? emscriptenWebGLGetTexPixelData(type, format, width, height, pixels, internalFormat) : null);
7337
}
7338
7339
function _emscripten_glTexParameterf(x0, x1, x2) { GLctx['texParameterf'](x0, x1, x2) }
7340
7341
function _emscripten_glTexParameterfv(target, pname, params) {
7342
var param = HEAPF32[((params)>>2)];
7343
GLctx.texParameterf(target, pname, param);
7344
}
7345
7346
function _emscripten_glTexParameteri(x0, x1, x2) { GLctx['texParameteri'](x0, x1, x2) }
7347
7348
function _emscripten_glTexParameteriv(target, pname, params) {
7349
var param = HEAP32[((params)>>2)];
7350
GLctx.texParameteri(target, pname, param);
7351
}
7352
7353
function _emscripten_glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels) {
7354
var pixelData = null;
7355
if (pixels) pixelData = emscriptenWebGLGetTexPixelData(type, format, width, height, pixels, 0);
7356
GLctx.texSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixelData);
7357
}
7358
7359
function _emscripten_glUniform1f(location, v0) {
7360
GLctx.uniform1f(GL.uniforms[location], v0);
7361
}
7362
7363
function _emscripten_glUniform1fv(location, count, value) {
7364
7365
7366
if (count <= GL.MINI_TEMP_BUFFER_SIZE) {
7367
// avoid allocation when uploading few enough uniforms
7368
var view = GL.miniTempBufferFloatViews[count-1];
7369
for (var i = 0; i < count; ++i) {
7370
view[i] = HEAPF32[(((value)+(4*i))>>2)];
7371
}
7372
} else
7373
{
7374
var view = HEAPF32.subarray((value)>>2,(value+count*4)>>2);
7375
}
7376
GLctx.uniform1fv(GL.uniforms[location], view);
7377
}
7378
7379
function _emscripten_glUniform1i(location, v0) {
7380
GLctx.uniform1i(GL.uniforms[location], v0);
7381
}
7382
7383
function _emscripten_glUniform1iv(location, count, value) {
7384
7385
7386
if (count <= GL.MINI_TEMP_BUFFER_SIZE) {
7387
// avoid allocation when uploading few enough uniforms
7388
var view = GL.miniTempBufferIntViews[count-1];
7389
for (var i = 0; i < count; ++i) {
7390
view[i] = HEAP32[(((value)+(4*i))>>2)];
7391
}
7392
} else
7393
{
7394
var view = HEAP32.subarray((value)>>2,(value+count*4)>>2);
7395
}
7396
GLctx.uniform1iv(GL.uniforms[location], view);
7397
}
7398
7399
function _emscripten_glUniform2f(location, v0, v1) {
7400
GLctx.uniform2f(GL.uniforms[location], v0, v1);
7401
}
7402
7403
function _emscripten_glUniform2fv(location, count, value) {
7404
7405
7406
if (2*count <= GL.MINI_TEMP_BUFFER_SIZE) {
7407
// avoid allocation when uploading few enough uniforms
7408
var view = GL.miniTempBufferFloatViews[2*count-1];
7409
for (var i = 0; i < 2*count; i += 2) {
7410
view[i] = HEAPF32[(((value)+(4*i))>>2)];
7411
view[i+1] = HEAPF32[(((value)+(4*i+4))>>2)];
7412
}
7413
} else
7414
{
7415
var view = HEAPF32.subarray((value)>>2,(value+count*8)>>2);
7416
}
7417
GLctx.uniform2fv(GL.uniforms[location], view);
7418
}
7419
7420
function _emscripten_glUniform2i(location, v0, v1) {
7421
GLctx.uniform2i(GL.uniforms[location], v0, v1);
7422
}
7423
7424
function _emscripten_glUniform2iv(location, count, value) {
7425
7426
7427
if (2*count <= GL.MINI_TEMP_BUFFER_SIZE) {
7428
// avoid allocation when uploading few enough uniforms
7429
var view = GL.miniTempBufferIntViews[2*count-1];
7430
for (var i = 0; i < 2*count; i += 2) {
7431
view[i] = HEAP32[(((value)+(4*i))>>2)];
7432
view[i+1] = HEAP32[(((value)+(4*i+4))>>2)];
7433
}
7434
} else
7435
{
7436
var view = HEAP32.subarray((value)>>2,(value+count*8)>>2);
7437
}
7438
GLctx.uniform2iv(GL.uniforms[location], view);
7439
}
7440
7441
function _emscripten_glUniform3f(location, v0, v1, v2) {
7442
GLctx.uniform3f(GL.uniforms[location], v0, v1, v2);
7443
}
7444
7445
function _emscripten_glUniform3fv(location, count, value) {
7446
7447
7448
if (3*count <= GL.MINI_TEMP_BUFFER_SIZE) {
7449
// avoid allocation when uploading few enough uniforms
7450
var view = GL.miniTempBufferFloatViews[3*count-1];
7451
for (var i = 0; i < 3*count; i += 3) {
7452
view[i] = HEAPF32[(((value)+(4*i))>>2)];
7453
view[i+1] = HEAPF32[(((value)+(4*i+4))>>2)];
7454
view[i+2] = HEAPF32[(((value)+(4*i+8))>>2)];
7455
}
7456
} else
7457
{
7458
var view = HEAPF32.subarray((value)>>2,(value+count*12)>>2);
7459
}
7460
GLctx.uniform3fv(GL.uniforms[location], view);
7461
}
7462
7463
function _emscripten_glUniform3i(location, v0, v1, v2) {
7464
GLctx.uniform3i(GL.uniforms[location], v0, v1, v2);
7465
}
7466
7467
function _emscripten_glUniform3iv(location, count, value) {
7468
7469
7470
if (3*count <= GL.MINI_TEMP_BUFFER_SIZE) {
7471
// avoid allocation when uploading few enough uniforms
7472
var view = GL.miniTempBufferIntViews[3*count-1];
7473
for (var i = 0; i < 3*count; i += 3) {
7474
view[i] = HEAP32[(((value)+(4*i))>>2)];
7475
view[i+1] = HEAP32[(((value)+(4*i+4))>>2)];
7476
view[i+2] = HEAP32[(((value)+(4*i+8))>>2)];
7477
}
7478
} else
7479
{
7480
var view = HEAP32.subarray((value)>>2,(value+count*12)>>2);
7481
}
7482
GLctx.uniform3iv(GL.uniforms[location], view);
7483
}
7484
7485
function _emscripten_glUniform4f(location, v0, v1, v2, v3) {
7486
GLctx.uniform4f(GL.uniforms[location], v0, v1, v2, v3);
7487
}
7488
7489
function _emscripten_glUniform4fv(location, count, value) {
7490
7491
7492
if (4*count <= GL.MINI_TEMP_BUFFER_SIZE) {
7493
// avoid allocation when uploading few enough uniforms
7494
var view = GL.miniTempBufferFloatViews[4*count-1];
7495
// hoist the heap out of the loop for size and for pthreads+growth.
7496
var heap = HEAPF32;
7497
value >>= 2;
7498
for (var i = 0; i < 4 * count; i += 4) {
7499
var dst = value + i;
7500
view[i] = heap[dst];
7501
view[i + 1] = heap[dst + 1];
7502
view[i + 2] = heap[dst + 2];
7503
view[i + 3] = heap[dst + 3];
7504
}
7505
} else
7506
{
7507
var view = HEAPF32.subarray((value)>>2,(value+count*16)>>2);
7508
}
7509
GLctx.uniform4fv(GL.uniforms[location], view);
7510
}
7511
7512
function _emscripten_glUniform4i(location, v0, v1, v2, v3) {
7513
GLctx.uniform4i(GL.uniforms[location], v0, v1, v2, v3);
7514
}
7515
7516
function _emscripten_glUniform4iv(location, count, value) {
7517
7518
7519
if (4*count <= GL.MINI_TEMP_BUFFER_SIZE) {
7520
// avoid allocation when uploading few enough uniforms
7521
var view = GL.miniTempBufferIntViews[4*count-1];
7522
for (var i = 0; i < 4*count; i += 4) {
7523
view[i] = HEAP32[(((value)+(4*i))>>2)];
7524
view[i+1] = HEAP32[(((value)+(4*i+4))>>2)];
7525
view[i+2] = HEAP32[(((value)+(4*i+8))>>2)];
7526
view[i+3] = HEAP32[(((value)+(4*i+12))>>2)];
7527
}
7528
} else
7529
{
7530
var view = HEAP32.subarray((value)>>2,(value+count*16)>>2);
7531
}
7532
GLctx.uniform4iv(GL.uniforms[location], view);
7533
}
7534
7535
function _emscripten_glUniformMatrix2fv(location, count, transpose, value) {
7536
7537
7538
if (4*count <= GL.MINI_TEMP_BUFFER_SIZE) {
7539
// avoid allocation when uploading few enough uniforms
7540
var view = GL.miniTempBufferFloatViews[4*count-1];
7541
for (var i = 0; i < 4*count; i += 4) {
7542
view[i] = HEAPF32[(((value)+(4*i))>>2)];
7543
view[i+1] = HEAPF32[(((value)+(4*i+4))>>2)];
7544
view[i+2] = HEAPF32[(((value)+(4*i+8))>>2)];
7545
view[i+3] = HEAPF32[(((value)+(4*i+12))>>2)];
7546
}
7547
} else
7548
{
7549
var view = HEAPF32.subarray((value)>>2,(value+count*16)>>2);
7550
}
7551
GLctx.uniformMatrix2fv(GL.uniforms[location], !!transpose, view);
7552
}
7553
7554
function _emscripten_glUniformMatrix3fv(location, count, transpose, value) {
7555
7556
7557
if (9*count <= GL.MINI_TEMP_BUFFER_SIZE) {
7558
// avoid allocation when uploading few enough uniforms
7559
var view = GL.miniTempBufferFloatViews[9*count-1];
7560
for (var i = 0; i < 9*count; i += 9) {
7561
view[i] = HEAPF32[(((value)+(4*i))>>2)];
7562
view[i+1] = HEAPF32[(((value)+(4*i+4))>>2)];
7563
view[i+2] = HEAPF32[(((value)+(4*i+8))>>2)];
7564
view[i+3] = HEAPF32[(((value)+(4*i+12))>>2)];
7565
view[i+4] = HEAPF32[(((value)+(4*i+16))>>2)];
7566
view[i+5] = HEAPF32[(((value)+(4*i+20))>>2)];
7567
view[i+6] = HEAPF32[(((value)+(4*i+24))>>2)];
7568
view[i+7] = HEAPF32[(((value)+(4*i+28))>>2)];
7569
view[i+8] = HEAPF32[(((value)+(4*i+32))>>2)];
7570
}
7571
} else
7572
{
7573
var view = HEAPF32.subarray((value)>>2,(value+count*36)>>2);
7574
}
7575
GLctx.uniformMatrix3fv(GL.uniforms[location], !!transpose, view);
7576
}
7577
7578
function _emscripten_glUniformMatrix4fv(location, count, transpose, value) {
7579
7580
7581
if (16*count <= GL.MINI_TEMP_BUFFER_SIZE) {
7582
// avoid allocation when uploading few enough uniforms
7583
var view = GL.miniTempBufferFloatViews[16*count-1];
7584
// hoist the heap out of the loop for size and for pthreads+growth.
7585
var heap = HEAPF32;
7586
value >>= 2;
7587
for (var i = 0; i < 16 * count; i += 16) {
7588
var dst = value + i;
7589
view[i] = heap[dst];
7590
view[i + 1] = heap[dst + 1];
7591
view[i + 2] = heap[dst + 2];
7592
view[i + 3] = heap[dst + 3];
7593
view[i + 4] = heap[dst + 4];
7594
view[i + 5] = heap[dst + 5];
7595
view[i + 6] = heap[dst + 6];
7596
view[i + 7] = heap[dst + 7];
7597
view[i + 8] = heap[dst + 8];
7598
view[i + 9] = heap[dst + 9];
7599
view[i + 10] = heap[dst + 10];
7600
view[i + 11] = heap[dst + 11];
7601
view[i + 12] = heap[dst + 12];
7602
view[i + 13] = heap[dst + 13];
7603
view[i + 14] = heap[dst + 14];
7604
view[i + 15] = heap[dst + 15];
7605
}
7606
} else
7607
{
7608
var view = HEAPF32.subarray((value)>>2,(value+count*64)>>2);
7609
}
7610
GLctx.uniformMatrix4fv(GL.uniforms[location], !!transpose, view);
7611
}
7612
7613
function _emscripten_glUseProgram(program) {
7614
GLctx.useProgram(GL.programs[program]);
7615
}
7616
7617
function _emscripten_glValidateProgram(program) {
7618
GLctx.validateProgram(GL.programs[program]);
7619
}
7620
7621
function _emscripten_glVertexAttrib1f(x0, x1) { GLctx['vertexAttrib1f'](x0, x1) }
7622
7623
function _emscripten_glVertexAttrib1fv(index, v) {
7624
7625
GLctx.vertexAttrib1f(index, HEAPF32[v>>2]);
7626
}
7627
7628
function _emscripten_glVertexAttrib2f(x0, x1, x2) { GLctx['vertexAttrib2f'](x0, x1, x2) }
7629
7630
function _emscripten_glVertexAttrib2fv(index, v) {
7631
7632
GLctx.vertexAttrib2f(index, HEAPF32[v>>2], HEAPF32[v+4>>2]);
7633
}
7634
7635
function _emscripten_glVertexAttrib3f(x0, x1, x2, x3) { GLctx['vertexAttrib3f'](x0, x1, x2, x3) }
7636
7637
function _emscripten_glVertexAttrib3fv(index, v) {
7638
7639
GLctx.vertexAttrib3f(index, HEAPF32[v>>2], HEAPF32[v+4>>2], HEAPF32[v+8>>2]);
7640
}
7641
7642
function _emscripten_glVertexAttrib4f(x0, x1, x2, x3, x4) { GLctx['vertexAttrib4f'](x0, x1, x2, x3, x4) }
7643
7644
function _emscripten_glVertexAttrib4fv(index, v) {
7645
7646
GLctx.vertexAttrib4f(index, HEAPF32[v>>2], HEAPF32[v+4>>2], HEAPF32[v+8>>2], HEAPF32[v+12>>2]);
7647
}
7648
7649
function _emscripten_glVertexAttribDivisorANGLE(index, divisor) {
7650
GLctx['vertexAttribDivisor'](index, divisor);
7651
}
7652
7653
function _emscripten_glVertexAttribPointer(index, size, type, normalized, stride, ptr) {
7654
GLctx.vertexAttribPointer(index, size, type, !!normalized, stride, ptr);
7655
}
7656
7657
function _emscripten_glViewport(x0, x1, x2, x3) { GLctx['viewport'](x0, x1, x2, x3) }
7658
7659
function _emscripten_has_asyncify() {
7660
return 0;
7661
}
7662
7663
function _emscripten_memcpy_big(dest, src, num) {
7664
HEAPU8.copyWithin(dest, src, src + num);
7665
}
7666
7667
7668
function __emscripten_do_request_fullscreen(target, strategy) {
7669
if (!JSEvents.fullscreenEnabled()) return -1;
7670
target = __findEventTarget(target);
7671
if (!target) return -4;
7672
7673
if (!target.requestFullscreen
7674
&& !target.webkitRequestFullscreen
7675
) {
7676
return -3;
7677
}
7678
7679
var canPerformRequests = JSEvents.canPerformEventHandlerRequests();
7680
7681
// Queue this function call if we're not currently in an event handler and the user saw it appropriate to do so.
7682
if (!canPerformRequests) {
7683
if (strategy.deferUntilInEventHandler) {
7684
JSEvents.deferCall(_JSEvents_requestFullscreen, 1 /* priority over pointer lock */, [target, strategy]);
7685
return 1;
7686
} else {
7687
return -2;
7688
}
7689
}
7690
7691
return _JSEvents_requestFullscreen(target, strategy);
7692
}function _emscripten_request_fullscreen_strategy(target, deferUntilInEventHandler, fullscreenStrategy) {
7693
var strategy = {
7694
scaleMode: HEAP32[((fullscreenStrategy)>>2)],
7695
canvasResolutionScaleMode: HEAP32[(((fullscreenStrategy)+(4))>>2)],
7696
filteringMode: HEAP32[(((fullscreenStrategy)+(8))>>2)],
7697
deferUntilInEventHandler: deferUntilInEventHandler,
7698
canvasResizedCallback: HEAP32[(((fullscreenStrategy)+(12))>>2)],
7699
canvasResizedCallbackUserData: HEAP32[(((fullscreenStrategy)+(16))>>2)]
7700
};
7701
__currentFullscreenStrategy = strategy;
7702
7703
return __emscripten_do_request_fullscreen(target, strategy);
7704
}
7705
7706
function _emscripten_request_pointerlock(target, deferUntilInEventHandler) {
7707
target = __findEventTarget(target);
7708
if (!target) return -4;
7709
if (!target.requestPointerLock
7710
&& !target.msRequestPointerLock
7711
) {
7712
return -1;
7713
}
7714
7715
var canPerformRequests = JSEvents.canPerformEventHandlerRequests();
7716
7717
// Queue this function call if we're not currently in an event handler and the user saw it appropriate to do so.
7718
if (!canPerformRequests) {
7719
if (deferUntilInEventHandler) {
7720
JSEvents.deferCall(__requestPointerLock, 2 /* priority below fullscreen */, [target]);
7721
return 1;
7722
} else {
7723
return -2;
7724
}
7725
}
7726
7727
return __requestPointerLock(target);
7728
}
7729
7730
7731
function _emscripten_get_heap_size() {
7732
return HEAPU8.length;
7733
}
7734
7735
function abortOnCannotGrowMemory(requestedSize) {
7736
abort('Cannot enlarge memory arrays to size ' + requestedSize + ' bytes (OOM). Either (1) compile with -s INITIAL_MEMORY=X with X higher than the current value ' + HEAP8.length + ', (2) compile with -s ALLOW_MEMORY_GROWTH=1 which allows increasing the size at runtime, or (3) if you want malloc to return NULL (0) instead of this abort, compile with -s ABORTING_MALLOC=0 ');
7737
}function _emscripten_resize_heap(requestedSize) {
7738
abortOnCannotGrowMemory(requestedSize);
7739
}
7740
7741
function _emscripten_sample_gamepad_data() {
7742
return (JSEvents.lastGamepadState = (navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : null)))
7743
? 0 : -1;
7744
}
7745
7746
7747
function __registerBeforeUnloadEventCallback(target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString) {
7748
var beforeUnloadEventHandlerFunc = function(ev) {
7749
var e = ev || event;
7750
7751
// Note: This is always called on the main browser thread, since it needs synchronously return a value!
7752
var confirmationMessage = dynCall_iiii(callbackfunc, eventTypeId, 0, userData);
7753
7754
if (confirmationMessage) {
7755
confirmationMessage = UTF8ToString(confirmationMessage);
7756
}
7757
if (confirmationMessage) {
7758
e.preventDefault();
7759
e.returnValue = confirmationMessage;
7760
return confirmationMessage;
7761
}
7762
};
7763
7764
var eventHandler = {
7765
target: __findEventTarget(target),
7766
eventTypeString: eventTypeString,
7767
callbackfunc: callbackfunc,
7768
handlerFunc: beforeUnloadEventHandlerFunc,
7769
useCapture: useCapture
7770
};
7771
JSEvents.registerOrRemoveHandler(eventHandler);
7772
}function _emscripten_set_beforeunload_callback_on_thread(userData, callbackfunc, targetThread) {
7773
if (typeof onbeforeunload === 'undefined') return -1;
7774
// beforeunload callback can only be registered on the main browser thread, because the page will go away immediately after returning from the handler,
7775
// and there is no time to start proxying it anywhere.
7776
if (targetThread !== 1) return -5;
7777
__registerBeforeUnloadEventCallback(2, userData, true, callbackfunc, 28, "beforeunload");
7778
return 0;
7779
}
7780
7781
7782
function __registerFocusEventCallback(target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) {
7783
if (!JSEvents.focusEvent) JSEvents.focusEvent = _malloc( 256 );
7784
7785
var focusEventHandlerFunc = function(ev) {
7786
var e = ev || event;
7787
7788
var nodeName = JSEvents.getNodeNameForTarget(e.target);
7789
var id = e.target.id ? e.target.id : '';
7790
7791
var focusEvent = JSEvents.focusEvent;
7792
stringToUTF8(nodeName, focusEvent + 0, 128);
7793
stringToUTF8(id, focusEvent + 128, 128);
7794
7795
if (dynCall_iiii(callbackfunc, eventTypeId, focusEvent, userData)) e.preventDefault();
7796
};
7797
7798
var eventHandler = {
7799
target: __findEventTarget(target),
7800
eventTypeString: eventTypeString,
7801
callbackfunc: callbackfunc,
7802
handlerFunc: focusEventHandlerFunc,
7803
useCapture: useCapture
7804
};
7805
JSEvents.registerOrRemoveHandler(eventHandler);
7806
}function _emscripten_set_blur_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) {
7807
__registerFocusEventCallback(target, userData, useCapture, callbackfunc, 12, "blur", targetThread);
7808
return 0;
7809
}
7810
7811
7812
function _emscripten_set_element_css_size(target, width, height) {
7813
target = __findEventTarget(target);
7814
if (!target) return -4;
7815
7816
target.style.width = width + "px";
7817
target.style.height = height + "px";
7818
7819
return 0;
7820
}
7821
7822
function _emscripten_set_focus_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) {
7823
__registerFocusEventCallback(target, userData, useCapture, callbackfunc, 13, "focus", targetThread);
7824
return 0;
7825
}
7826
7827
7828
7829
function __fillFullscreenChangeEventData(eventStruct) {
7830
var fullscreenElement = document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement || document.msFullscreenElement;
7831
var isFullscreen = !!fullscreenElement;
7832
/** @suppress{checkTypes} */
7833
HEAP32[((eventStruct)>>2)]=isFullscreen;
7834
HEAP32[(((eventStruct)+(4))>>2)]=JSEvents.fullscreenEnabled();
7835
// If transitioning to fullscreen, report info about the element that is now fullscreen.
7836
// If transitioning to windowed mode, report info about the element that just was fullscreen.
7837
var reportedElement = isFullscreen ? fullscreenElement : JSEvents.previousFullscreenElement;
7838
var nodeName = JSEvents.getNodeNameForTarget(reportedElement);
7839
var id = (reportedElement && reportedElement.id) ? reportedElement.id : '';
7840
stringToUTF8(nodeName, eventStruct + 8, 128);
7841
stringToUTF8(id, eventStruct + 136, 128);
7842
HEAP32[(((eventStruct)+(264))>>2)]=reportedElement ? reportedElement.clientWidth : 0;
7843
HEAP32[(((eventStruct)+(268))>>2)]=reportedElement ? reportedElement.clientHeight : 0;
7844
HEAP32[(((eventStruct)+(272))>>2)]=screen.width;
7845
HEAP32[(((eventStruct)+(276))>>2)]=screen.height;
7846
if (isFullscreen) {
7847
JSEvents.previousFullscreenElement = fullscreenElement;
7848
}
7849
}function __registerFullscreenChangeEventCallback(target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) {
7850
if (!JSEvents.fullscreenChangeEvent) JSEvents.fullscreenChangeEvent = _malloc( 280 );
7851
7852
var fullscreenChangeEventhandlerFunc = function(ev) {
7853
var e = ev || event;
7854
7855
var fullscreenChangeEvent = JSEvents.fullscreenChangeEvent;
7856
7857
__fillFullscreenChangeEventData(fullscreenChangeEvent);
7858
7859
if (dynCall_iiii(callbackfunc, eventTypeId, fullscreenChangeEvent, userData)) e.preventDefault();
7860
};
7861
7862
var eventHandler = {
7863
target: target,
7864
eventTypeString: eventTypeString,
7865
callbackfunc: callbackfunc,
7866
handlerFunc: fullscreenChangeEventhandlerFunc,
7867
useCapture: useCapture
7868
};
7869
JSEvents.registerOrRemoveHandler(eventHandler);
7870
}function _emscripten_set_fullscreenchange_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) {
7871
if (!JSEvents.fullscreenEnabled()) return -1;
7872
target = __findEventTarget(target);
7873
if (!target) return -4;
7874
__registerFullscreenChangeEventCallback(target, userData, useCapture, callbackfunc, 19, "fullscreenchange", targetThread);
7875
7876
7877
// Unprefixed Fullscreen API shipped in Chromium 71 (https://bugs.chromium.org/p/chromium/issues/detail?id=383813)
7878
// As of Safari 13.0.3 on macOS Catalina 10.15.1 still ships with prefixed webkitfullscreenchange. TODO: revisit this check once Safari ships unprefixed version.
7879
__registerFullscreenChangeEventCallback(target, userData, useCapture, callbackfunc, 19, "webkitfullscreenchange", targetThread);
7880
7881
return 0;
7882
}
7883
7884
7885
function __registerGamepadEventCallback(target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) {
7886
if (!JSEvents.gamepadEvent) JSEvents.gamepadEvent = _malloc( 1432 );
7887
7888
var gamepadEventHandlerFunc = function(ev) {
7889
var e = ev || event;
7890
7891
var gamepadEvent = JSEvents.gamepadEvent;
7892
__fillGamepadEventData(gamepadEvent, e["gamepad"]);
7893
7894
if (dynCall_iiii(callbackfunc, eventTypeId, gamepadEvent, userData)) e.preventDefault();
7895
};
7896
7897
var eventHandler = {
7898
target: __findEventTarget(target),
7899
allowsDeferredCalls: true,
7900
eventTypeString: eventTypeString,
7901
callbackfunc: callbackfunc,
7902
handlerFunc: gamepadEventHandlerFunc,
7903
useCapture: useCapture
7904
};
7905
JSEvents.registerOrRemoveHandler(eventHandler);
7906
}function _emscripten_set_gamepadconnected_callback_on_thread(userData, useCapture, callbackfunc, targetThread) {
7907
if (!navigator.getGamepads && !navigator.webkitGetGamepads) return -1;
7908
__registerGamepadEventCallback(2, userData, useCapture, callbackfunc, 26, "gamepadconnected", targetThread);
7909
return 0;
7910
}
7911
7912
function _emscripten_set_gamepaddisconnected_callback_on_thread(userData, useCapture, callbackfunc, targetThread) {
7913
if (!navigator.getGamepads && !navigator.webkitGetGamepads) return -1;
7914
__registerGamepadEventCallback(2, userData, useCapture, callbackfunc, 27, "gamepaddisconnected", targetThread);
7915
return 0;
7916
}
7917
7918
7919
function __registerKeyEventCallback(target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) {
7920
if (!JSEvents.keyEvent) JSEvents.keyEvent = _malloc( 164 );
7921
7922
var keyEventHandlerFunc = function(ev) {
7923
var e = ev || event;
7924
7925
var keyEventData = JSEvents.keyEvent;
7926
stringToUTF8(e.key ? e.key : "", keyEventData + 0, 32);
7927
stringToUTF8(e.code ? e.code : "", keyEventData + 32, 32);
7928
HEAP32[(((keyEventData)+(64))>>2)]=e.location;
7929
HEAP32[(((keyEventData)+(68))>>2)]=e.ctrlKey;
7930
HEAP32[(((keyEventData)+(72))>>2)]=e.shiftKey;
7931
HEAP32[(((keyEventData)+(76))>>2)]=e.altKey;
7932
HEAP32[(((keyEventData)+(80))>>2)]=e.metaKey;
7933
HEAP32[(((keyEventData)+(84))>>2)]=e.repeat;
7934
stringToUTF8(e.locale ? e.locale : "", keyEventData + 88, 32);
7935
stringToUTF8(e.char ? e.char : "", keyEventData + 120, 32);
7936
HEAP32[(((keyEventData)+(152))>>2)]=e.charCode;
7937
HEAP32[(((keyEventData)+(156))>>2)]=e.keyCode;
7938
HEAP32[(((keyEventData)+(160))>>2)]=e.which;
7939
7940
if (dynCall_iiii(callbackfunc, eventTypeId, keyEventData, userData)) e.preventDefault();
7941
};
7942
7943
var eventHandler = {
7944
target: __findEventTarget(target),
7945
allowsDeferredCalls: true,
7946
eventTypeString: eventTypeString,
7947
callbackfunc: callbackfunc,
7948
handlerFunc: keyEventHandlerFunc,
7949
useCapture: useCapture
7950
};
7951
JSEvents.registerOrRemoveHandler(eventHandler);
7952
}function _emscripten_set_keydown_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) {
7953
__registerKeyEventCallback(target, userData, useCapture, callbackfunc, 2, "keydown", targetThread);
7954
return 0;
7955
}
7956
7957
function _emscripten_set_keypress_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) {
7958
__registerKeyEventCallback(target, userData, useCapture, callbackfunc, 1, "keypress", targetThread);
7959
return 0;
7960
}
7961
7962
function _emscripten_set_keyup_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) {
7963
__registerKeyEventCallback(target, userData, useCapture, callbackfunc, 3, "keyup", targetThread);
7964
return 0;
7965
}
7966
7967
7968
7969
7970
function __fillMouseEventData(eventStruct, e, target) {
7971
HEAP32[((eventStruct)>>2)]=e.screenX;
7972
HEAP32[(((eventStruct)+(4))>>2)]=e.screenY;
7973
HEAP32[(((eventStruct)+(8))>>2)]=e.clientX;
7974
HEAP32[(((eventStruct)+(12))>>2)]=e.clientY;
7975
HEAP32[(((eventStruct)+(16))>>2)]=e.ctrlKey;
7976
HEAP32[(((eventStruct)+(20))>>2)]=e.shiftKey;
7977
HEAP32[(((eventStruct)+(24))>>2)]=e.altKey;
7978
HEAP32[(((eventStruct)+(28))>>2)]=e.metaKey;
7979
HEAP16[(((eventStruct)+(32))>>1)]=e.button;
7980
HEAP16[(((eventStruct)+(34))>>1)]=e.buttons;
7981
var movementX = e["movementX"]
7982
|| (e.screenX-JSEvents.previousScreenX)
7983
;
7984
var movementY = e["movementY"]
7985
|| (e.screenY-JSEvents.previousScreenY)
7986
;
7987
7988
HEAP32[(((eventStruct)+(36))>>2)]=movementX;
7989
HEAP32[(((eventStruct)+(40))>>2)]=movementY;
7990
7991
var rect = __getBoundingClientRect(target);
7992
HEAP32[(((eventStruct)+(44))>>2)]=e.clientX - rect.left;
7993
HEAP32[(((eventStruct)+(48))>>2)]=e.clientY - rect.top;
7994
7995
// wheel and mousewheel events contain wrong screenX/screenY on chrome/opera
7996
// https://github.com/emscripten-core/emscripten/pull/4997
7997
// https://bugs.chromium.org/p/chromium/issues/detail?id=699956
7998
if (e.type !== 'wheel' && e.type !== 'mousewheel') {
7999
JSEvents.previousScreenX = e.screenX;
8000
JSEvents.previousScreenY = e.screenY;
8001
}
8002
}function __registerMouseEventCallback(target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) {
8003
if (!JSEvents.mouseEvent) JSEvents.mouseEvent = _malloc( 64 );
8004
target = __findEventTarget(target);
8005
8006
var mouseEventHandlerFunc = function(ev) {
8007
var e = ev || event;
8008
8009
// TODO: Make this access thread safe, or this could update live while app is reading it.
8010
__fillMouseEventData(JSEvents.mouseEvent, e, target);
8011
8012
if (dynCall_iiii(callbackfunc, eventTypeId, JSEvents.mouseEvent, userData)) e.preventDefault();
8013
};
8014
8015
var eventHandler = {
8016
target: target,
8017
allowsDeferredCalls: eventTypeString != 'mousemove' && eventTypeString != 'mouseenter' && eventTypeString != 'mouseleave', // Mouse move events do not allow fullscreen/pointer lock requests to be handled in them!
8018
eventTypeString: eventTypeString,
8019
callbackfunc: callbackfunc,
8020
handlerFunc: mouseEventHandlerFunc,
8021
useCapture: useCapture
8022
};
8023
JSEvents.registerOrRemoveHandler(eventHandler);
8024
}function _emscripten_set_mousedown_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) {
8025
__registerMouseEventCallback(target, userData, useCapture, callbackfunc, 5, "mousedown", targetThread);
8026
return 0;
8027
}
8028
8029
function _emscripten_set_mouseenter_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) {
8030
__registerMouseEventCallback(target, userData, useCapture, callbackfunc, 33, "mouseenter", targetThread);
8031
return 0;
8032
}
8033
8034
function _emscripten_set_mouseleave_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) {
8035
__registerMouseEventCallback(target, userData, useCapture, callbackfunc, 34, "mouseleave", targetThread);
8036
return 0;
8037
}
8038
8039
function _emscripten_set_mousemove_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) {
8040
__registerMouseEventCallback(target, userData, useCapture, callbackfunc, 8, "mousemove", targetThread);
8041
return 0;
8042
}
8043
8044
function _emscripten_set_mouseup_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) {
8045
__registerMouseEventCallback(target, userData, useCapture, callbackfunc, 6, "mouseup", targetThread);
8046
return 0;
8047
}
8048
8049
8050
8051
function __fillPointerlockChangeEventData(eventStruct) {
8052
var pointerLockElement = document.pointerLockElement || document.mozPointerLockElement || document.webkitPointerLockElement || document.msPointerLockElement;
8053
var isPointerlocked = !!pointerLockElement;
8054
/** @suppress {checkTypes} */
8055
HEAP32[((eventStruct)>>2)]=isPointerlocked;
8056
var nodeName = JSEvents.getNodeNameForTarget(pointerLockElement);
8057
var id = (pointerLockElement && pointerLockElement.id) ? pointerLockElement.id : '';
8058
stringToUTF8(nodeName, eventStruct + 4, 128);
8059
stringToUTF8(id, eventStruct + 132, 128);
8060
}function __registerPointerlockChangeEventCallback(target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) {
8061
if (!JSEvents.pointerlockChangeEvent) JSEvents.pointerlockChangeEvent = _malloc( 260 );
8062
8063
var pointerlockChangeEventHandlerFunc = function(ev) {
8064
var e = ev || event;
8065
8066
var pointerlockChangeEvent = JSEvents.pointerlockChangeEvent;
8067
__fillPointerlockChangeEventData(pointerlockChangeEvent);
8068
8069
if (dynCall_iiii(callbackfunc, eventTypeId, pointerlockChangeEvent, userData)) e.preventDefault();
8070
};
8071
8072
var eventHandler = {
8073
target: target,
8074
eventTypeString: eventTypeString,
8075
callbackfunc: callbackfunc,
8076
handlerFunc: pointerlockChangeEventHandlerFunc,
8077
useCapture: useCapture
8078
};
8079
JSEvents.registerOrRemoveHandler(eventHandler);
8080
}/** @suppress {missingProperties} */
8081
function _emscripten_set_pointerlockchange_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) {
8082
// TODO: Currently not supported in pthreads or in --proxy-to-worker mode. (In pthreads mode, document object is not defined)
8083
if (!document || !document.body || (!document.body.requestPointerLock && !document.body.mozRequestPointerLock && !document.body.webkitRequestPointerLock && !document.body.msRequestPointerLock)) {
8084
return -1;
8085
}
8086
8087
target = __findEventTarget(target);
8088
if (!target) return -4;
8089
__registerPointerlockChangeEventCallback(target, userData, useCapture, callbackfunc, 20, "pointerlockchange", targetThread);
8090
__registerPointerlockChangeEventCallback(target, userData, useCapture, callbackfunc, 20, "mozpointerlockchange", targetThread);
8091
__registerPointerlockChangeEventCallback(target, userData, useCapture, callbackfunc, 20, "webkitpointerlockchange", targetThread);
8092
__registerPointerlockChangeEventCallback(target, userData, useCapture, callbackfunc, 20, "mspointerlockchange", targetThread);
8093
return 0;
8094
}
8095
8096
8097
function __registerUiEventCallback(target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) {
8098
if (!JSEvents.uiEvent) JSEvents.uiEvent = _malloc( 36 );
8099
8100
target = __findEventTarget(target);
8101
8102
var uiEventHandlerFunc = function(ev) {
8103
var e = ev || event;
8104
if (e.target != target) {
8105
// Never take ui events such as scroll via a 'bubbled' route, but always from the direct element that
8106
// was targeted. Otherwise e.g. if app logs a message in response to a page scroll, the Emscripten log
8107
// message box could cause to scroll, generating a new (bubbled) scroll message, causing a new log print,
8108
// causing a new scroll, etc..
8109
return;
8110
}
8111
var uiEvent = JSEvents.uiEvent;
8112
var b = document.body; // Take document.body to a variable, Closure compiler does not outline access to it on its own.
8113
HEAP32[((uiEvent)>>2)]=e.detail;
8114
HEAP32[(((uiEvent)+(4))>>2)]=b.clientWidth;
8115
HEAP32[(((uiEvent)+(8))>>2)]=b.clientHeight;
8116
HEAP32[(((uiEvent)+(12))>>2)]=innerWidth;
8117
HEAP32[(((uiEvent)+(16))>>2)]=innerHeight;
8118
HEAP32[(((uiEvent)+(20))>>2)]=outerWidth;
8119
HEAP32[(((uiEvent)+(24))>>2)]=outerHeight;
8120
HEAP32[(((uiEvent)+(28))>>2)]=pageXOffset;
8121
HEAP32[(((uiEvent)+(32))>>2)]=pageYOffset;
8122
if (dynCall_iiii(callbackfunc, eventTypeId, uiEvent, userData)) e.preventDefault();
8123
};
8124
8125
var eventHandler = {
8126
target: target,
8127
eventTypeString: eventTypeString,
8128
callbackfunc: callbackfunc,
8129
handlerFunc: uiEventHandlerFunc,
8130
useCapture: useCapture
8131
};
8132
JSEvents.registerOrRemoveHandler(eventHandler);
8133
}function _emscripten_set_resize_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) {
8134
__registerUiEventCallback(target, userData, useCapture, callbackfunc, 10, "resize", targetThread);
8135
return 0;
8136
}
8137
8138
8139
function __registerTouchEventCallback(target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) {
8140
if (!JSEvents.touchEvent) JSEvents.touchEvent = _malloc( 1684 );
8141
8142
target = __findEventTarget(target);
8143
8144
var touchEventHandlerFunc = function(ev) {
8145
var e = ev || event;
8146
8147
var touches = {};
8148
for(var i = 0; i < e.touches.length; ++i) {
8149
var touch = e.touches[i];
8150
touch.changed = false;
8151
touches[touch.identifier] = touch;
8152
}
8153
for(var i = 0; i < e.changedTouches.length; ++i) {
8154
var touch = e.changedTouches[i];
8155
touches[touch.identifier] = touch;
8156
touch.changed = true;
8157
}
8158
for(var i = 0; i < e.targetTouches.length; ++i) {
8159
var touch = e.targetTouches[i];
8160
touches[touch.identifier].onTarget = true;
8161
}
8162
8163
var touchEvent = JSEvents.touchEvent;
8164
var ptr = touchEvent;
8165
HEAP32[(((ptr)+(4))>>2)]=e.ctrlKey;
8166
HEAP32[(((ptr)+(8))>>2)]=e.shiftKey;
8167
HEAP32[(((ptr)+(12))>>2)]=e.altKey;
8168
HEAP32[(((ptr)+(16))>>2)]=e.metaKey;
8169
ptr += 20; // Advance to the start of the touch array.
8170
var targetRect = __getBoundingClientRect(target);
8171
var numTouches = 0;
8172
for(var i in touches) {
8173
var t = touches[i];
8174
HEAP32[((ptr)>>2)]=t.identifier;
8175
HEAP32[(((ptr)+(4))>>2)]=t.screenX;
8176
HEAP32[(((ptr)+(8))>>2)]=t.screenY;
8177
HEAP32[(((ptr)+(12))>>2)]=t.clientX;
8178
HEAP32[(((ptr)+(16))>>2)]=t.clientY;
8179
HEAP32[(((ptr)+(20))>>2)]=t.pageX;
8180
HEAP32[(((ptr)+(24))>>2)]=t.pageY;
8181
HEAP32[(((ptr)+(28))>>2)]=t.changed;
8182
HEAP32[(((ptr)+(32))>>2)]=t.onTarget;
8183
HEAP32[(((ptr)+(36))>>2)]=t.clientX - targetRect.left;
8184
HEAP32[(((ptr)+(40))>>2)]=t.clientY - targetRect.top;
8185
8186
ptr += 52;
8187
8188
if (++numTouches >= 32) {
8189
break;
8190
}
8191
}
8192
HEAP32[((touchEvent)>>2)]=numTouches;
8193
8194
if (dynCall_iiii(callbackfunc, eventTypeId, touchEvent, userData)) e.preventDefault();
8195
};
8196
8197
var eventHandler = {
8198
target: target,
8199
allowsDeferredCalls: eventTypeString == 'touchstart' || eventTypeString == 'touchend',
8200
eventTypeString: eventTypeString,
8201
callbackfunc: callbackfunc,
8202
handlerFunc: touchEventHandlerFunc,
8203
useCapture: useCapture
8204
};
8205
JSEvents.registerOrRemoveHandler(eventHandler);
8206
}function _emscripten_set_touchcancel_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) {
8207
__registerTouchEventCallback(target, userData, useCapture, callbackfunc, 25, "touchcancel", targetThread);
8208
return 0;
8209
}
8210
8211
function _emscripten_set_touchend_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) {
8212
__registerTouchEventCallback(target, userData, useCapture, callbackfunc, 23, "touchend", targetThread);
8213
return 0;
8214
}
8215
8216
function _emscripten_set_touchmove_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) {
8217
__registerTouchEventCallback(target, userData, useCapture, callbackfunc, 24, "touchmove", targetThread);
8218
return 0;
8219
}
8220
8221
function _emscripten_set_touchstart_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) {
8222
__registerTouchEventCallback(target, userData, useCapture, callbackfunc, 22, "touchstart", targetThread);
8223
return 0;
8224
}
8225
8226
8227
8228
function __fillVisibilityChangeEventData(eventStruct) {
8229
var visibilityStates = [ "hidden", "visible", "prerender", "unloaded" ];
8230
var visibilityState = visibilityStates.indexOf(document.visibilityState);
8231
8232
// Assigning a boolean to HEAP32 with expected type coercion.
8233
/** @suppress {checkTypes} */
8234
HEAP32[((eventStruct)>>2)]=document.hidden;
8235
HEAP32[(((eventStruct)+(4))>>2)]=visibilityState;
8236
}function __registerVisibilityChangeEventCallback(target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) {
8237
if (!JSEvents.visibilityChangeEvent) JSEvents.visibilityChangeEvent = _malloc( 8 );
8238
8239
var visibilityChangeEventHandlerFunc = function(ev) {
8240
var e = ev || event;
8241
8242
var visibilityChangeEvent = JSEvents.visibilityChangeEvent;
8243
8244
__fillVisibilityChangeEventData(visibilityChangeEvent);
8245
8246
if (dynCall_iiii(callbackfunc, eventTypeId, visibilityChangeEvent, userData)) e.preventDefault();
8247
};
8248
8249
var eventHandler = {
8250
target: target,
8251
eventTypeString: eventTypeString,
8252
callbackfunc: callbackfunc,
8253
handlerFunc: visibilityChangeEventHandlerFunc,
8254
useCapture: useCapture
8255
};
8256
JSEvents.registerOrRemoveHandler(eventHandler);
8257
}function _emscripten_set_visibilitychange_callback_on_thread(userData, useCapture, callbackfunc, targetThread) {
8258
if (!__specialEventTargets[1]) {
8259
return -4;
8260
}
8261
__registerVisibilityChangeEventCallback(__specialEventTargets[1], userData, useCapture, callbackfunc, 21, "visibilitychange", targetThread);
8262
return 0;
8263
}
8264
8265
8266
function __registerWheelEventCallback(target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) {
8267
if (!JSEvents.wheelEvent) JSEvents.wheelEvent = _malloc( 96 );
8268
8269
// The DOM Level 3 events spec event 'wheel'
8270
var wheelHandlerFunc = function(ev) {
8271
var e = ev || event;
8272
var wheelEvent = JSEvents.wheelEvent;
8273
__fillMouseEventData(wheelEvent, e, target);
8274
HEAPF64[(((wheelEvent)+(64))>>3)]=e["deltaX"];
8275
HEAPF64[(((wheelEvent)+(72))>>3)]=e["deltaY"];
8276
HEAPF64[(((wheelEvent)+(80))>>3)]=e["deltaZ"];
8277
HEAP32[(((wheelEvent)+(88))>>2)]=e["deltaMode"];
8278
if (dynCall_iiii(callbackfunc, eventTypeId, wheelEvent, userData)) e.preventDefault();
8279
};
8280
// The 'mousewheel' event as implemented in Safari 6.0.5
8281
var mouseWheelHandlerFunc = function(ev) {
8282
var e = ev || event;
8283
__fillMouseEventData(JSEvents.wheelEvent, e, target);
8284
HEAPF64[(((JSEvents.wheelEvent)+(64))>>3)]=e["wheelDeltaX"] || 0;
8285
/* 1. Invert to unify direction with the DOM Level 3 wheel event. 2. MSIE does not provide wheelDeltaY, so wheelDelta is used as a fallback. */
8286
var wheelDeltaY = -(e["wheelDeltaY"] || e["wheelDelta"])
8287
HEAPF64[(((JSEvents.wheelEvent)+(72))>>3)]=wheelDeltaY;
8288
HEAPF64[(((JSEvents.wheelEvent)+(80))>>3)]=0 /* Not available */;
8289
HEAP32[(((JSEvents.wheelEvent)+(88))>>2)]=0 /* DOM_DELTA_PIXEL */;
8290
var shouldCancel = dynCall_iiii(callbackfunc, eventTypeId, JSEvents.wheelEvent, userData);
8291
if (shouldCancel) {
8292
e.preventDefault();
8293
}
8294
};
8295
8296
var eventHandler = {
8297
target: target,
8298
allowsDeferredCalls: true,
8299
eventTypeString: eventTypeString,
8300
callbackfunc: callbackfunc,
8301
handlerFunc: (eventTypeString == 'wheel') ? wheelHandlerFunc : mouseWheelHandlerFunc,
8302
useCapture: useCapture
8303
};
8304
JSEvents.registerOrRemoveHandler(eventHandler);
8305
}function _emscripten_set_wheel_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) {
8306
target = __findEventTarget(target);
8307
if (typeof target.onwheel !== 'undefined') {
8308
__registerWheelEventCallback(target, userData, useCapture, callbackfunc, 9, "wheel", targetThread);
8309
return 0;
8310
} else if (typeof target.onmousewheel !== 'undefined') {
8311
__registerWheelEventCallback(target, userData, useCapture, callbackfunc, 9, "mousewheel", targetThread);
8312
return 0;
8313
} else {
8314
return -1;
8315
}
8316
}
8317
8318
function _emscripten_sleep() {
8319
throw 'Please compile your program with async support in order to use asynchronous operations like emscripten_sleep';
8320
}
8321
8322
8323
8324
var ENV={};
8325
8326
function __getExecutableName() {
8327
return thisProgram || './this.program';
8328
}function _emscripten_get_environ() {
8329
if (!_emscripten_get_environ.strings) {
8330
// Default values.
8331
var env = {
8332
'USER': 'web_user',
8333
'LOGNAME': 'web_user',
8334
'PATH': '/',
8335
'PWD': '/',
8336
'HOME': '/home/web_user',
8337
// Browser language detection #8751
8338
'LANG': ((typeof navigator === 'object' && navigator.languages && navigator.languages[0]) || 'C').replace('-', '_') + '.UTF-8',
8339
'_': __getExecutableName()
8340
};
8341
// Apply the user-provided values, if any.
8342
for (var x in ENV) {
8343
env[x] = ENV[x];
8344
}
8345
var strings = [];
8346
for (var x in env) {
8347
strings.push(x + '=' + env[x]);
8348
}
8349
_emscripten_get_environ.strings = strings;
8350
}
8351
return _emscripten_get_environ.strings;
8352
}function _environ_get(__environ, environ_buf) {
8353
var strings = _emscripten_get_environ();
8354
var bufSize = 0;
8355
strings.forEach(function(string, i) {
8356
var ptr = environ_buf + bufSize;
8357
HEAP32[(((__environ)+(i * 4))>>2)]=ptr;
8358
writeAsciiToMemory(string, ptr);
8359
bufSize += string.length + 1;
8360
});
8361
return 0;
8362
}
8363
8364
function _environ_sizes_get(penviron_count, penviron_buf_size) {
8365
var strings = _emscripten_get_environ();
8366
HEAP32[((penviron_count)>>2)]=strings.length;
8367
var bufSize = 0;
8368
strings.forEach(function(string) {
8369
bufSize += string.length + 1;
8370
});
8371
HEAP32[((penviron_buf_size)>>2)]=bufSize;
8372
return 0;
8373
}
8374
8375
function _exit(status) {
8376
// void _exit(int status);
8377
// http://pubs.opengroup.org/onlinepubs/000095399/functions/exit.html
8378
exit(status);
8379
}
8380
8381
function _fd_close(fd) {try {
8382
8383
var stream = SYSCALLS.getStreamFromFD(fd);
8384
FS.close(stream);
8385
return 0;
8386
} catch (e) {
8387
if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
8388
return e.errno;
8389
}
8390
}
8391
8392
function _fd_read(fd, iov, iovcnt, pnum) {try {
8393
8394
var stream = SYSCALLS.getStreamFromFD(fd);
8395
var num = SYSCALLS.doReadv(stream, iov, iovcnt);
8396
HEAP32[((pnum)>>2)]=num
8397
return 0;
8398
} catch (e) {
8399
if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
8400
return e.errno;
8401
}
8402
}
8403
8404
function _fd_seek(fd, offset_low, offset_high, whence, newOffset) {try {
8405
8406
var stream = SYSCALLS.getStreamFromFD(fd);
8407
var HIGH_OFFSET = 0x100000000; // 2^32
8408
// use an unsigned operator on low and shift high by 32-bits
8409
var offset = offset_high * HIGH_OFFSET + (offset_low >>> 0);
8410
8411
var DOUBLE_LIMIT = 0x20000000000000; // 2^53
8412
// we also check for equality since DOUBLE_LIMIT + 1 == DOUBLE_LIMIT
8413
if (offset <= -DOUBLE_LIMIT || offset >= DOUBLE_LIMIT) {
8414
return -61;
8415
}
8416
8417
FS.llseek(stream, offset, whence);
8418
(tempI64 = [stream.position>>>0,(tempDouble=stream.position,(+(Math_abs(tempDouble))) >= 1.0 ? (tempDouble > 0.0 ? ((Math_min((+(Math_floor((tempDouble)/4294967296.0))), 4294967295.0))|0)>>>0 : (~~((+(Math_ceil((tempDouble - +(((~~(tempDouble)))>>>0))/4294967296.0)))))>>>0) : 0)],HEAP32[((newOffset)>>2)]=tempI64[0],HEAP32[(((newOffset)+(4))>>2)]=tempI64[1]);
8419
if (stream.getdents && offset === 0 && whence === 0) stream.getdents = null; // reset readdir state
8420
return 0;
8421
} catch (e) {
8422
if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
8423
return e.errno;
8424
}
8425
}
8426
8427
function _fd_write(fd, iov, iovcnt, pnum) {try {
8428
8429
var stream = SYSCALLS.getStreamFromFD(fd);
8430
var num = SYSCALLS.doWritev(stream, iov, iovcnt);
8431
HEAP32[((pnum)>>2)]=num
8432
return 0;
8433
} catch (e) {
8434
if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
8435
return e.errno;
8436
}
8437
}
8438
8439
function _gettimeofday(ptr) {
8440
var now = Date.now();
8441
HEAP32[((ptr)>>2)]=(now/1000)|0; // seconds
8442
HEAP32[(((ptr)+(4))>>2)]=((now % 1000)*1000)|0; // microseconds
8443
return 0;
8444
}
8445
8446
function _glActiveTexture(x0) { GLctx['activeTexture'](x0) }
8447
8448
function _glAttachShader(program, shader) {
8449
GLctx.attachShader(GL.programs[program],
8450
GL.shaders[shader]);
8451
}
8452
8453
function _glBindBuffer(target, buffer) {
8454
8455
GLctx.bindBuffer(target, GL.buffers[buffer]);
8456
}
8457
8458
function _glBindTexture(target, texture) {
8459
GLctx.bindTexture(target, GL.textures[texture]);
8460
}
8461
8462
function _glBlendFunc(x0, x1) { GLctx['blendFunc'](x0, x1) }
8463
8464
function _glBufferData(target, size, data, usage) {
8465
// N.b. here first form specifies a heap subarray, second form an integer size, so the ?: code here is polymorphic. It is advised to avoid
8466
// randomly mixing both uses in calling code, to avoid any potential JS engine JIT issues.
8467
GLctx.bufferData(target, data ? HEAPU8.subarray(data, data+size) : size, usage);
8468
}
8469
8470
function _glClear(x0) { GLctx['clear'](x0) }
8471
8472
function _glClearColor(x0, x1, x2, x3) { GLctx['clearColor'](x0, x1, x2, x3) }
8473
8474
function _glCompileShader(shader) {
8475
GLctx.compileShader(GL.shaders[shader]);
8476
}
8477
8478
function _glCreateProgram() {
8479
var id = GL.getNewId(GL.programs);
8480
var program = GLctx.createProgram();
8481
program.name = id;
8482
GL.programs[id] = program;
8483
return id;
8484
}
8485
8486
function _glCreateShader(shaderType) {
8487
var id = GL.getNewId(GL.shaders);
8488
GL.shaders[id] = GLctx.createShader(shaderType);
8489
return id;
8490
}
8491
8492
function _glDepthFunc(x0) { GLctx['depthFunc'](x0) }
8493
8494
function _glDepthMask(flag) {
8495
GLctx.depthMask(!!flag);
8496
}
8497
8498
function _glDisable(x0) { GLctx['disable'](x0) }
8499
8500
function _glDisableVertexAttribArray(index) {
8501
GLctx.disableVertexAttribArray(index);
8502
}
8503
8504
function _glDrawArrays(mode, first, count) {
8505
8506
GLctx.drawArrays(mode, first, count);
8507
8508
}
8509
8510
function _glEnable(x0) { GLctx['enable'](x0) }
8511
8512
function _glEnableVertexAttribArray(index) {
8513
GLctx.enableVertexAttribArray(index);
8514
}
8515
8516
function _glGenBuffers(n, buffers) {
8517
__glGenObject(n, buffers, 'createBuffer', GL.buffers
8518
);
8519
}
8520
8521
function _glGenTextures(n, textures) {
8522
__glGenObject(n, textures, 'createTexture', GL.textures
8523
);
8524
}
8525
8526
function _glGetAttribLocation(program, name) {
8527
return GLctx.getAttribLocation(GL.programs[program], UTF8ToString(name));
8528
}
8529
8530
function _glGetShaderInfoLog(shader, maxLength, length, infoLog) {
8531
var log = GLctx.getShaderInfoLog(GL.shaders[shader]);
8532
if (log === null) log = '(unknown error)';
8533
var numBytesWrittenExclNull = (maxLength > 0 && infoLog) ? stringToUTF8(log, infoLog, maxLength) : 0;
8534
if (length) HEAP32[((length)>>2)]=numBytesWrittenExclNull;
8535
}
8536
8537
function _glGetShaderiv(shader, pname, p) {
8538
if (!p) {
8539
// GLES2 specification does not specify how to behave if p is a null pointer. Since calling this function does not make sense
8540
// if p == null, issue a GL error to notify user about it.
8541
GL.recordError(0x501 /* GL_INVALID_VALUE */);
8542
return;
8543
}
8544
if (pname == 0x8B84) { // GL_INFO_LOG_LENGTH
8545
var log = GLctx.getShaderInfoLog(GL.shaders[shader]);
8546
if (log === null) log = '(unknown error)';
8547
HEAP32[((p)>>2)]=log.length + 1;
8548
} else if (pname == 0x8B88) { // GL_SHADER_SOURCE_LENGTH
8549
var source = GLctx.getShaderSource(GL.shaders[shader]);
8550
var sourceLength = (source === null || source.length == 0) ? 0 : source.length + 1;
8551
HEAP32[((p)>>2)]=sourceLength;
8552
} else {
8553
HEAP32[((p)>>2)]=GLctx.getShaderParameter(GL.shaders[shader], pname);
8554
}
8555
}
8556
8557
function _glGetUniformLocation(program, name) {
8558
name = UTF8ToString(name);
8559
8560
var arrayIndex = 0;
8561
// If user passed an array accessor "[index]", parse the array index off the accessor.
8562
if (name[name.length - 1] == ']') {
8563
var leftBrace = name.lastIndexOf('[');
8564
arrayIndex = name[leftBrace+1] != ']' ? jstoi_q(name.slice(leftBrace + 1)) : 0; // "index]", parseInt will ignore the ']' at the end; but treat "foo[]" as "foo[0]"
8565
name = name.slice(0, leftBrace);
8566
}
8567
8568
var uniformInfo = GL.programInfos[program] && GL.programInfos[program].uniforms[name]; // returns pair [ dimension_of_uniform_array, uniform_location ]
8569
if (uniformInfo && arrayIndex >= 0 && arrayIndex < uniformInfo[0]) { // Check if user asked for an out-of-bounds element, i.e. for 'vec4 colors[3];' user could ask for 'colors[10]' which should return -1.
8570
return uniformInfo[1] + arrayIndex;
8571
} else {
8572
return -1;
8573
}
8574
}
8575
8576
function _glLinkProgram(program) {
8577
GLctx.linkProgram(GL.programs[program]);
8578
GL.populateUniformTable(program);
8579
}
8580
8581
function _glPolygonOffset(x0, x1) { GLctx['polygonOffset'](x0, x1) }
8582
8583
function _glScissor(x0, x1, x2, x3) { GLctx['scissor'](x0, x1, x2, x3) }
8584
8585
function _glShaderSource(shader, count, string, length) {
8586
var source = GL.getSource(shader, count, string, length);
8587
8588
8589
GLctx.shaderSource(GL.shaders[shader], source);
8590
}
8591
8592
function _glTexImage2D(target, level, internalFormat, width, height, border, format, type, pixels) {
8593
GLctx.texImage2D(target, level, internalFormat, width, height, border, format, type, pixels ? emscriptenWebGLGetTexPixelData(type, format, width, height, pixels, internalFormat) : null);
8594
}
8595
8596
function _glTexParameteri(x0, x1, x2) { GLctx['texParameteri'](x0, x1, x2) }
8597
8598
function _glUniform1i(location, v0) {
8599
GLctx.uniform1i(GL.uniforms[location], v0);
8600
}
8601
8602
function _glUseProgram(program) {
8603
GLctx.useProgram(GL.programs[program]);
8604
}
8605
8606
function _glVertexAttribPointer(index, size, type, normalized, stride, ptr) {
8607
GLctx.vertexAttribPointer(index, size, type, !!normalized, stride, ptr);
8608
}
8609
8610
function _glViewport(x0, x1, x2, x3) { GLctx['viewport'](x0, x1, x2, x3) }
8611
8612
8613
function _usleep(useconds) {
8614
// int usleep(useconds_t useconds);
8615
// http://pubs.opengroup.org/onlinepubs/000095399/functions/usleep.html
8616
// We're single-threaded, so use a busy loop. Super-ugly.
8617
var start = _emscripten_get_now();
8618
while (_emscripten_get_now() - start < useconds / 1000) {
8619
// Do nothing.
8620
}
8621
}function _nanosleep(rqtp, rmtp) {
8622
// int nanosleep(const struct timespec *rqtp, struct timespec *rmtp);
8623
if (rqtp === 0) {
8624
___setErrNo(28);
8625
return -1;
8626
}
8627
var seconds = HEAP32[((rqtp)>>2)];
8628
var nanoseconds = HEAP32[(((rqtp)+(4))>>2)];
8629
if (nanoseconds < 0 || nanoseconds > 999999999 || seconds < 0) {
8630
___setErrNo(28);
8631
return -1;
8632
}
8633
if (rmtp !== 0) {
8634
HEAP32[((rmtp)>>2)]=0;
8635
HEAP32[(((rmtp)+(4))>>2)]=0;
8636
}
8637
return _usleep((seconds * 1e6) + (nanoseconds / 1000));
8638
}
8639
8640
function _setTempRet0($i) {
8641
setTempRet0(($i) | 0);
8642
}
8643
8644
function _sigaction(signum, act, oldact) {
8645
//int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact);
8646
err('Calling stub instead of sigaction()');
8647
return 0;
8648
}
8649
8650
8651
var __sigalrm_handler=0;function _signal(sig, func) {
8652
if (sig == 14 /*SIGALRM*/) {
8653
__sigalrm_handler = func;
8654
} else {
8655
err('Calling stub instead of signal()');
8656
}
8657
return 0;
8658
}
8659
8660
function readAsmConstArgs(sigPtr, buf) {
8661
if (!readAsmConstArgs.array) {
8662
readAsmConstArgs.array = [];
8663
}
8664
var args = readAsmConstArgs.array;
8665
args.length = 0;
8666
var ch;
8667
while (ch = HEAPU8[sigPtr++]) {
8668
if (ch === 100/*'d'*/ || ch === 102/*'f'*/) {
8669
buf = (buf + 7) & ~7;
8670
args.push(HEAPF64[(buf >> 3)]);
8671
buf += 8;
8672
} else
8673
if (ch === 105 /*'i'*/)
8674
{
8675
buf = (buf + 3) & ~3;
8676
args.push(HEAP32[(buf >> 2)]);
8677
buf += 4;
8678
}
8679
else abort("unexpected char in asm const signature " + ch);
8680
}
8681
return args;
8682
}
8683
var FSNode = /** @constructor */ function(parent, name, mode, rdev) {
8684
if (!parent) {
8685
parent = this; // root node sets parent to itself
8686
}
8687
this.parent = parent;
8688
this.mount = parent.mount;
8689
this.mounted = null;
8690
this.id = FS.nextInode++;
8691
this.name = name;
8692
this.mode = mode;
8693
this.node_ops = {};
8694
this.stream_ops = {};
8695
this.rdev = rdev;
8696
};
8697
var readMode = 292/*292*/ | 73/*73*/;
8698
var writeMode = 146/*146*/;
8699
Object.defineProperties(FSNode.prototype, {
8700
read: {
8701
get: /** @this{FSNode} */function() {
8702
return (this.mode & readMode) === readMode;
8703
},
8704
set: /** @this{FSNode} */function(val) {
8705
val ? this.mode |= readMode : this.mode &= ~readMode;
8706
}
8707
},
8708
write: {
8709
get: /** @this{FSNode} */function() {
8710
return (this.mode & writeMode) === writeMode;
8711
},
8712
set: /** @this{FSNode} */function(val) {
8713
val ? this.mode |= writeMode : this.mode &= ~writeMode;
8714
}
8715
},
8716
isFolder: {
8717
get: /** @this{FSNode} */function() {
8718
return FS.isDir(this.mode);
8719
}
8720
},
8721
isDevice: {
8722
get: /** @this{FSNode} */function() {
8723
return FS.isChrdev(this.mode);
8724
}
8725
}
8726
});
8727
FS.FSNode = FSNode;
8728
FS.staticInit();;
8729
Module["requestFullscreen"] = function Module_requestFullscreen(lockPointer, resizeCanvas) { Browser.requestFullscreen(lockPointer, resizeCanvas) };
8730
Module["requestFullScreen"] = function Module_requestFullScreen() { Browser.requestFullScreen() };
8731
Module["requestAnimationFrame"] = function Module_requestAnimationFrame(func) { Browser.requestAnimationFrame(func) };
8732
Module["setCanvasSize"] = function Module_setCanvasSize(width, height, noUpdates) { Browser.setCanvasSize(width, height, noUpdates) };
8733
Module["pauseMainLoop"] = function Module_pauseMainLoop() { Browser.mainLoop.pause() };
8734
Module["resumeMainLoop"] = function Module_resumeMainLoop() { Browser.mainLoop.resume() };
8735
Module["getUserMedia"] = function Module_getUserMedia() { Browser.getUserMedia() }
8736
Module["createContext"] = function Module_createContext(canvas, useWebGL, setInModule, webGLContextAttributes) { return Browser.createContext(canvas, useWebGL, setInModule, webGLContextAttributes) };
8737
var GLctx; GL.init();
8738
for (var i = 0; i < 32; i++) __tempFixedLengthArray.push(new Array(i));;
8739
var ASSERTIONS = true;
8740
8741
// Copyright 2017 The Emscripten Authors. All rights reserved.
8742
// Emscripten is available under two separate licenses, the MIT license and the
8743
// University of Illinois/NCSA Open Source License. Both these licenses can be
8744
// found in the LICENSE file.
8745
8746
/** @type {function(string, boolean=, number=)} */
8747
function intArrayFromString(stringy, dontAddNull, length) {
8748
var len = length > 0 ? length : lengthBytesUTF8(stringy)+1;
8749
var u8array = new Array(len);
8750
var numBytesWritten = stringToUTF8Array(stringy, u8array, 0, u8array.length);
8751
if (dontAddNull) u8array.length = numBytesWritten;
8752
return u8array;
8753
}
8754
8755
function intArrayToString(array) {
8756
var ret = [];
8757
for (var i = 0; i < array.length; i++) {
8758
var chr = array[i];
8759
if (chr > 0xFF) {
8760
if (ASSERTIONS) {
8761
assert(false, 'Character code ' + chr + ' (' + String.fromCharCode(chr) + ') at offset ' + i + ' not in 0x00-0xFF.');
8762
}
8763
chr &= 0xFF;
8764
}
8765
ret.push(String.fromCharCode(chr));
8766
}
8767
return ret.join('');
8768
}
8769
8770
8771
var asmGlobalArg = {};
8772
var asmLibraryArg = { "__assert_fail": ___assert_fail, "__handle_stack_overflow": ___handle_stack_overflow, "__syscall221": ___syscall221, "__syscall5": ___syscall5, "__syscall54": ___syscall54, "abort": _abort, "atexit": _atexit, "clock_gettime": _clock_gettime, "dlclose": _dlclose, "dlerror": _dlerror, "dlsym": _dlsym, "eglBindAPI": _eglBindAPI, "eglChooseConfig": _eglChooseConfig, "eglCreateContext": _eglCreateContext, "eglCreateWindowSurface": _eglCreateWindowSurface, "eglDestroyContext": _eglDestroyContext, "eglDestroySurface": _eglDestroySurface, "eglGetConfigAttrib": _eglGetConfigAttrib, "eglGetDisplay": _eglGetDisplay, "eglGetError": _eglGetError, "eglGetProcAddress": _eglGetProcAddress, "eglInitialize": _eglInitialize, "eglMakeCurrent": _eglMakeCurrent, "eglQueryString": _eglQueryString, "eglSwapBuffers": _eglSwapBuffers, "eglSwapInterval": _eglSwapInterval, "eglTerminate": _eglTerminate, "eglWaitGL": _eglWaitGL, "eglWaitNative": _eglWaitNative, "emscripten_asm_const_iii": _emscripten_asm_const_iii, "emscripten_exit_fullscreen": _emscripten_exit_fullscreen, "emscripten_exit_pointerlock": _emscripten_exit_pointerlock, "emscripten_get_device_pixel_ratio": _emscripten_get_device_pixel_ratio, "emscripten_get_element_css_size": _emscripten_get_element_css_size, "emscripten_get_gamepad_status": _emscripten_get_gamepad_status, "emscripten_get_num_gamepads": _emscripten_get_num_gamepads, "emscripten_get_sbrk_ptr": _emscripten_get_sbrk_ptr, "emscripten_glActiveTexture": _emscripten_glActiveTexture, "emscripten_glAttachShader": _emscripten_glAttachShader, "emscripten_glBeginQueryEXT": _emscripten_glBeginQueryEXT, "emscripten_glBindAttribLocation": _emscripten_glBindAttribLocation, "emscripten_glBindBuffer": _emscripten_glBindBuffer, "emscripten_glBindFramebuffer": _emscripten_glBindFramebuffer, "emscripten_glBindRenderbuffer": _emscripten_glBindRenderbuffer, "emscripten_glBindTexture": _emscripten_glBindTexture, "emscripten_glBindVertexArrayOES": _emscripten_glBindVertexArrayOES, "emscripten_glBlendColor": _emscripten_glBlendColor, "emscripten_glBlendEquation": _emscripten_glBlendEquation, "emscripten_glBlendEquationSeparate": _emscripten_glBlendEquationSeparate, "emscripten_glBlendFunc": _emscripten_glBlendFunc, "emscripten_glBlendFuncSeparate": _emscripten_glBlendFuncSeparate, "emscripten_glBufferData": _emscripten_glBufferData, "emscripten_glBufferSubData": _emscripten_glBufferSubData, "emscripten_glCheckFramebufferStatus": _emscripten_glCheckFramebufferStatus, "emscripten_glClear": _emscripten_glClear, "emscripten_glClearColor": _emscripten_glClearColor, "emscripten_glClearDepthf": _emscripten_glClearDepthf, "emscripten_glClearStencil": _emscripten_glClearStencil, "emscripten_glColorMask": _emscripten_glColorMask, "emscripten_glCompileShader": _emscripten_glCompileShader, "emscripten_glCompressedTexImage2D": _emscripten_glCompressedTexImage2D, "emscripten_glCompressedTexSubImage2D": _emscripten_glCompressedTexSubImage2D, "emscripten_glCopyTexImage2D": _emscripten_glCopyTexImage2D, "emscripten_glCopyTexSubImage2D": _emscripten_glCopyTexSubImage2D, "emscripten_glCreateProgram": _emscripten_glCreateProgram, "emscripten_glCreateShader": _emscripten_glCreateShader, "emscripten_glCullFace": _emscripten_glCullFace, "emscripten_glDeleteBuffers": _emscripten_glDeleteBuffers, "emscripten_glDeleteFramebuffers": _emscripten_glDeleteFramebuffers, "emscripten_glDeleteProgram": _emscripten_glDeleteProgram, "emscripten_glDeleteQueriesEXT": _emscripten_glDeleteQueriesEXT, "emscripten_glDeleteRenderbuffers": _emscripten_glDeleteRenderbuffers, "emscripten_glDeleteShader": _emscripten_glDeleteShader, "emscripten_glDeleteTextures": _emscripten_glDeleteTextures, "emscripten_glDeleteVertexArraysOES": _emscripten_glDeleteVertexArraysOES, "emscripten_glDepthFunc": _emscripten_glDepthFunc, "emscripten_glDepthMask": _emscripten_glDepthMask, "emscripten_glDepthRangef": _emscripten_glDepthRangef, "emscripten_glDetachShader": _emscripten_glDetachShader, "emscripten_glDisable": _emscripten_glDisable, "emscripten_glDisableVertexAttribArray": _emscripten_glDisableVertexAttribArray, "emscripten_glDrawArrays": _emscripten_glDrawArrays, "emscripten_glDrawArraysInstancedANGLE": _emscripten_glDrawArraysInstancedANGLE, "emscripten_glDrawBuffersWEBGL": _emscripten_glDrawBuffersWEBGL, "emscripten_glDrawElements": _emscripten_glDrawElements, "emscripten_glDrawElementsInstancedANGLE": _emscripten_glDrawElementsInstancedANGLE, "emscripten_glEnable": _emscripten_glEnable, "emscripten_glEnableVertexAttribArray": _emscripten_glEnableVertexAttribArray, "emscripten_glEndQueryEXT": _emscripten_glEndQueryEXT, "emscripten_glFinish": _emscripten_glFinish, "emscripten_glFlush": _emscripten_glFlush, "emscripten_glFramebufferRenderbuffer": _emscripten_glFramebufferRenderbuffer, "emscripten_glFramebufferTexture2D": _emscripten_glFramebufferTexture2D, "emscripten_glFrontFace": _emscripten_glFrontFace, "emscripten_glGenBuffers": _emscripten_glGenBuffers, "emscripten_glGenFramebuffers": _emscripten_glGenFramebuffers, "emscripten_glGenQueriesEXT": _emscripten_glGenQueriesEXT, "emscripten_glGenRenderbuffers": _emscripten_glGenRenderbuffers, "emscripten_glGenTextures": _emscripten_glGenTextures, "emscripten_glGenVertexArraysOES": _emscripten_glGenVertexArraysOES, "emscripten_glGenerateMipmap": _emscripten_glGenerateMipmap, "emscripten_glGetActiveAttrib": _emscripten_glGetActiveAttrib, "emscripten_glGetActiveUniform": _emscripten_glGetActiveUniform, "emscripten_glGetAttachedShaders": _emscripten_glGetAttachedShaders, "emscripten_glGetAttribLocation": _emscripten_glGetAttribLocation, "emscripten_glGetBooleanv": _emscripten_glGetBooleanv, "emscripten_glGetBufferParameteriv": _emscripten_glGetBufferParameteriv, "emscripten_glGetError": _emscripten_glGetError, "emscripten_glGetFloatv": _emscripten_glGetFloatv, "emscripten_glGetFramebufferAttachmentParameteriv": _emscripten_glGetFramebufferAttachmentParameteriv, "emscripten_glGetIntegerv": _emscripten_glGetIntegerv, "emscripten_glGetProgramInfoLog": _emscripten_glGetProgramInfoLog, "emscripten_glGetProgramiv": _emscripten_glGetProgramiv, "emscripten_glGetQueryObjecti64vEXT": _emscripten_glGetQueryObjecti64vEXT, "emscripten_glGetQueryObjectivEXT": _emscripten_glGetQueryObjectivEXT, "emscripten_glGetQueryObjectui64vEXT": _emscripten_glGetQueryObjectui64vEXT, "emscripten_glGetQueryObjectuivEXT": _emscripten_glGetQueryObjectuivEXT, "emscripten_glGetQueryivEXT": _emscripten_glGetQueryivEXT, "emscripten_glGetRenderbufferParameteriv": _emscripten_glGetRenderbufferParameteriv, "emscripten_glGetShaderInfoLog": _emscripten_glGetShaderInfoLog, "emscripten_glGetShaderPrecisionFormat": _emscripten_glGetShaderPrecisionFormat, "emscripten_glGetShaderSource": _emscripten_glGetShaderSource, "emscripten_glGetShaderiv": _emscripten_glGetShaderiv, "emscripten_glGetString": _emscripten_glGetString, "emscripten_glGetTexParameterfv": _emscripten_glGetTexParameterfv, "emscripten_glGetTexParameteriv": _emscripten_glGetTexParameteriv, "emscripten_glGetUniformLocation": _emscripten_glGetUniformLocation, "emscripten_glGetUniformfv": _emscripten_glGetUniformfv, "emscripten_glGetUniformiv": _emscripten_glGetUniformiv, "emscripten_glGetVertexAttribPointerv": _emscripten_glGetVertexAttribPointerv, "emscripten_glGetVertexAttribfv": _emscripten_glGetVertexAttribfv, "emscripten_glGetVertexAttribiv": _emscripten_glGetVertexAttribiv, "emscripten_glHint": _emscripten_glHint, "emscripten_glIsBuffer": _emscripten_glIsBuffer, "emscripten_glIsEnabled": _emscripten_glIsEnabled, "emscripten_glIsFramebuffer": _emscripten_glIsFramebuffer, "emscripten_glIsProgram": _emscripten_glIsProgram, "emscripten_glIsQueryEXT": _emscripten_glIsQueryEXT, "emscripten_glIsRenderbuffer": _emscripten_glIsRenderbuffer, "emscripten_glIsShader": _emscripten_glIsShader, "emscripten_glIsTexture": _emscripten_glIsTexture, "emscripten_glIsVertexArrayOES": _emscripten_glIsVertexArrayOES, "emscripten_glLineWidth": _emscripten_glLineWidth, "emscripten_glLinkProgram": _emscripten_glLinkProgram, "emscripten_glPixelStorei": _emscripten_glPixelStorei, "emscripten_glPolygonOffset": _emscripten_glPolygonOffset, "emscripten_glQueryCounterEXT": _emscripten_glQueryCounterEXT, "emscripten_glReadPixels": _emscripten_glReadPixels, "emscripten_glReleaseShaderCompiler": _emscripten_glReleaseShaderCompiler, "emscripten_glRenderbufferStorage": _emscripten_glRenderbufferStorage, "emscripten_glSampleCoverage": _emscripten_glSampleCoverage, "emscripten_glScissor": _emscripten_glScissor, "emscripten_glShaderBinary": _emscripten_glShaderBinary, "emscripten_glShaderSource": _emscripten_glShaderSource, "emscripten_glStencilFunc": _emscripten_glStencilFunc, "emscripten_glStencilFuncSeparate": _emscripten_glStencilFuncSeparate, "emscripten_glStencilMask": _emscripten_glStencilMask, "emscripten_glStencilMaskSeparate": _emscripten_glStencilMaskSeparate, "emscripten_glStencilOp": _emscripten_glStencilOp, "emscripten_glStencilOpSeparate": _emscripten_glStencilOpSeparate, "emscripten_glTexImage2D": _emscripten_glTexImage2D, "emscripten_glTexParameterf": _emscripten_glTexParameterf, "emscripten_glTexParameterfv": _emscripten_glTexParameterfv, "emscripten_glTexParameteri": _emscripten_glTexParameteri, "emscripten_glTexParameteriv": _emscripten_glTexParameteriv, "emscripten_glTexSubImage2D": _emscripten_glTexSubImage2D, "emscripten_glUniform1f": _emscripten_glUniform1f, "emscripten_glUniform1fv": _emscripten_glUniform1fv, "emscripten_glUniform1i": _emscripten_glUniform1i, "emscripten_glUniform1iv": _emscripten_glUniform1iv, "emscripten_glUniform2f": _emscripten_glUniform2f, "emscripten_glUniform2fv": _emscripten_glUniform2fv, "emscripten_glUniform2i": _emscripten_glUniform2i, "emscripten_glUniform2iv": _emscripten_glUniform2iv, "emscripten_glUniform3f": _emscripten_glUniform3f, "emscripten_glUniform3fv": _emscripten_glUniform3fv, "emscripten_glUniform3i": _emscripten_glUniform3i, "emscripten_glUniform3iv": _emscripten_glUniform3iv, "emscripten_glUniform4f": _emscripten_glUniform4f, "emscripten_glUniform4fv": _emscripten_glUniform4fv, "emscripten_glUniform4i": _emscripten_glUniform4i, "emscripten_glUniform4iv": _emscripten_glUniform4iv, "emscripten_glUniformMatrix2fv": _emscripten_glUniformMatrix2fv, "emscripten_glUniformMatrix3fv": _emscripten_glUniformMatrix3fv, "emscripten_glUniformMatrix4fv": _emscripten_glUniformMatrix4fv, "emscripten_glUseProgram": _emscripten_glUseProgram, "emscripten_glValidateProgram": _emscripten_glValidateProgram, "emscripten_glVertexAttrib1f": _emscripten_glVertexAttrib1f, "emscripten_glVertexAttrib1fv": _emscripten_glVertexAttrib1fv, "emscripten_glVertexAttrib2f": _emscripten_glVertexAttrib2f, "emscripten_glVertexAttrib2fv": _emscripten_glVertexAttrib2fv, "emscripten_glVertexAttrib3f": _emscripten_glVertexAttrib3f, "emscripten_glVertexAttrib3fv": _emscripten_glVertexAttrib3fv, "emscripten_glVertexAttrib4f": _emscripten_glVertexAttrib4f, "emscripten_glVertexAttrib4fv": _emscripten_glVertexAttrib4fv, "emscripten_glVertexAttribDivisorANGLE": _emscripten_glVertexAttribDivisorANGLE, "emscripten_glVertexAttribPointer": _emscripten_glVertexAttribPointer, "emscripten_glViewport": _emscripten_glViewport, "emscripten_has_asyncify": _emscripten_has_asyncify, "emscripten_memcpy_big": _emscripten_memcpy_big, "emscripten_request_fullscreen_strategy": _emscripten_request_fullscreen_strategy, "emscripten_request_pointerlock": _emscripten_request_pointerlock, "emscripten_resize_heap": _emscripten_resize_heap, "emscripten_sample_gamepad_data": _emscripten_sample_gamepad_data, "emscripten_set_beforeunload_callback_on_thread": _emscripten_set_beforeunload_callback_on_thread, "emscripten_set_blur_callback_on_thread": _emscripten_set_blur_callback_on_thread, "emscripten_set_canvas_element_size": _emscripten_set_canvas_element_size, "emscripten_set_element_css_size": _emscripten_set_element_css_size, "emscripten_set_focus_callback_on_thread": _emscripten_set_focus_callback_on_thread, "emscripten_set_fullscreenchange_callback_on_thread": _emscripten_set_fullscreenchange_callback_on_thread, "emscripten_set_gamepadconnected_callback_on_thread": _emscripten_set_gamepadconnected_callback_on_thread, "emscripten_set_gamepaddisconnected_callback_on_thread": _emscripten_set_gamepaddisconnected_callback_on_thread, "emscripten_set_keydown_callback_on_thread": _emscripten_set_keydown_callback_on_thread, "emscripten_set_keypress_callback_on_thread": _emscripten_set_keypress_callback_on_thread, "emscripten_set_keyup_callback_on_thread": _emscripten_set_keyup_callback_on_thread, "emscripten_set_main_loop": _emscripten_set_main_loop, "emscripten_set_mousedown_callback_on_thread": _emscripten_set_mousedown_callback_on_thread, "emscripten_set_mouseenter_callback_on_thread": _emscripten_set_mouseenter_callback_on_thread, "emscripten_set_mouseleave_callback_on_thread": _emscripten_set_mouseleave_callback_on_thread, "emscripten_set_mousemove_callback_on_thread": _emscripten_set_mousemove_callback_on_thread, "emscripten_set_mouseup_callback_on_thread": _emscripten_set_mouseup_callback_on_thread, "emscripten_set_pointerlockchange_callback_on_thread": _emscripten_set_pointerlockchange_callback_on_thread, "emscripten_set_resize_callback_on_thread": _emscripten_set_resize_callback_on_thread, "emscripten_set_touchcancel_callback_on_thread": _emscripten_set_touchcancel_callback_on_thread, "emscripten_set_touchend_callback_on_thread": _emscripten_set_touchend_callback_on_thread, "emscripten_set_touchmove_callback_on_thread": _emscripten_set_touchmove_callback_on_thread, "emscripten_set_touchstart_callback_on_thread": _emscripten_set_touchstart_callback_on_thread, "emscripten_set_visibilitychange_callback_on_thread": _emscripten_set_visibilitychange_callback_on_thread, "emscripten_set_wheel_callback_on_thread": _emscripten_set_wheel_callback_on_thread, "emscripten_sleep": _emscripten_sleep, "environ_get": _environ_get, "environ_sizes_get": _environ_sizes_get, "exit": _exit, "fd_close": _fd_close, "fd_read": _fd_read, "fd_seek": _fd_seek, "fd_write": _fd_write, "gettimeofday": _gettimeofday, "glActiveTexture": _glActiveTexture, "glAttachShader": _glAttachShader, "glBindBuffer": _glBindBuffer, "glBindTexture": _glBindTexture, "glBlendFunc": _glBlendFunc, "glBufferData": _glBufferData, "glClear": _glClear, "glClearColor": _glClearColor, "glCompileShader": _glCompileShader, "glCreateProgram": _glCreateProgram, "glCreateShader": _glCreateShader, "glDepthFunc": _glDepthFunc, "glDepthMask": _glDepthMask, "glDisable": _glDisable, "glDisableVertexAttribArray": _glDisableVertexAttribArray, "glDrawArrays": _glDrawArrays, "glEnable": _glEnable, "glEnableVertexAttribArray": _glEnableVertexAttribArray, "glGenBuffers": _glGenBuffers, "glGenTextures": _glGenTextures, "glGetAttribLocation": _glGetAttribLocation, "glGetShaderInfoLog": _glGetShaderInfoLog, "glGetShaderiv": _glGetShaderiv, "glGetUniformLocation": _glGetUniformLocation, "glLinkProgram": _glLinkProgram, "glPolygonOffset": _glPolygonOffset, "glScissor": _glScissor, "glShaderSource": _glShaderSource, "glTexImage2D": _glTexImage2D, "glTexParameteri": _glTexParameteri, "glUniform1i": _glUniform1i, "glUseProgram": _glUseProgram, "glVertexAttribPointer": _glVertexAttribPointer, "glViewport": _glViewport, "memory": wasmMemory, "nanosleep": _nanosleep, "setTempRet0": _setTempRet0, "sigaction": _sigaction, "signal": _signal, "table": wasmTable };
8773
var asm = createWasm();
8774
Module["asm"] = asm;
8775
/** @type {function(...*):?} */
8776
var ___wasm_call_ctors = Module["___wasm_call_ctors"] = function() {
8777
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8778
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8779
return Module["asm"]["__wasm_call_ctors"].apply(null, arguments)
8780
};
8781
8782
/** @type {function(...*):?} */
8783
var _memcpy = Module["_memcpy"] = function() {
8784
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8785
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8786
return Module["asm"]["memcpy"].apply(null, arguments)
8787
};
8788
8789
/** @type {function(...*):?} */
8790
var _memset = Module["_memset"] = function() {
8791
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8792
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8793
return Module["asm"]["memset"].apply(null, arguments)
8794
};
8795
8796
/** @type {function(...*):?} */
8797
var _malloc = Module["_malloc"] = function() {
8798
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8799
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8800
return Module["asm"]["malloc"].apply(null, arguments)
8801
};
8802
8803
/** @type {function(...*):?} */
8804
var _free = Module["_free"] = function() {
8805
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8806
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8807
return Module["asm"]["free"].apply(null, arguments)
8808
};
8809
8810
/** @type {function(...*):?} */
8811
var _main = Module["_main"] = function() {
8812
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8813
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8814
return Module["asm"]["main"].apply(null, arguments)
8815
};
8816
8817
/** @type {function(...*):?} */
8818
var _strstr = Module["_strstr"] = function() {
8819
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8820
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8821
return Module["asm"]["strstr"].apply(null, arguments)
8822
};
8823
8824
/** @type {function(...*):?} */
8825
var ___errno_location = Module["___errno_location"] = function() {
8826
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8827
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8828
return Module["asm"]["__errno_location"].apply(null, arguments)
8829
};
8830
8831
/** @type {function(...*):?} */
8832
var _fflush = Module["_fflush"] = function() {
8833
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8834
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8835
return Module["asm"]["fflush"].apply(null, arguments)
8836
};
8837
8838
/** @type {function(...*):?} */
8839
var _emscripten_GetProcAddress = Module["_emscripten_GetProcAddress"] = function() {
8840
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8841
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8842
return Module["asm"]["emscripten_GetProcAddress"].apply(null, arguments)
8843
};
8844
8845
/** @type {function(...*):?} */
8846
var ___set_stack_limit = Module["___set_stack_limit"] = function() {
8847
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8848
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8849
return Module["asm"]["__set_stack_limit"].apply(null, arguments)
8850
};
8851
8852
/** @type {function(...*):?} */
8853
var stackSave = Module["stackSave"] = function() {
8854
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8855
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8856
return Module["asm"]["stackSave"].apply(null, arguments)
8857
};
8858
8859
/** @type {function(...*):?} */
8860
var stackAlloc = Module["stackAlloc"] = function() {
8861
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8862
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8863
return Module["asm"]["stackAlloc"].apply(null, arguments)
8864
};
8865
8866
/** @type {function(...*):?} */
8867
var stackRestore = Module["stackRestore"] = function() {
8868
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8869
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8870
return Module["asm"]["stackRestore"].apply(null, arguments)
8871
};
8872
8873
/** @type {function(...*):?} */
8874
var __growWasmMemory = Module["__growWasmMemory"] = function() {
8875
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8876
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8877
return Module["asm"]["__growWasmMemory"].apply(null, arguments)
8878
};
8879
8880
/** @type {function(...*):?} */
8881
var dynCall_i = Module["dynCall_i"] = function() {
8882
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8883
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8884
return Module["asm"]["dynCall_i"].apply(null, arguments)
8885
};
8886
8887
/** @type {function(...*):?} */
8888
var dynCall_v = Module["dynCall_v"] = function() {
8889
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8890
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8891
return Module["asm"]["dynCall_v"].apply(null, arguments)
8892
};
8893
8894
/** @type {function(...*):?} */
8895
var dynCall_iiii = Module["dynCall_iiii"] = function() {
8896
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8897
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8898
return Module["asm"]["dynCall_iiii"].apply(null, arguments)
8899
};
8900
8901
/** @type {function(...*):?} */
8902
var dynCall_vi = Module["dynCall_vi"] = function() {
8903
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8904
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8905
return Module["asm"]["dynCall_vi"].apply(null, arguments)
8906
};
8907
8908
/** @type {function(...*):?} */
8909
var dynCall_iii = Module["dynCall_iii"] = function() {
8910
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8911
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8912
return Module["asm"]["dynCall_iii"].apply(null, arguments)
8913
};
8914
8915
/** @type {function(...*):?} */
8916
var dynCall_vd = Module["dynCall_vd"] = function() {
8917
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8918
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8919
return Module["asm"]["dynCall_vd"].apply(null, arguments)
8920
};
8921
8922
/** @type {function(...*):?} */
8923
var dynCall_ii = Module["dynCall_ii"] = function() {
8924
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8925
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8926
return Module["asm"]["dynCall_ii"].apply(null, arguments)
8927
};
8928
8929
/** @type {function(...*):?} */
8930
var dynCall_viii = Module["dynCall_viii"] = function() {
8931
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8932
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8933
return Module["asm"]["dynCall_viii"].apply(null, arguments)
8934
};
8935
8936
/** @type {function(...*):?} */
8937
var dynCall_vii = Module["dynCall_vii"] = function() {
8938
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8939
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8940
return Module["asm"]["dynCall_vii"].apply(null, arguments)
8941
};
8942
8943
/** @type {function(...*):?} */
8944
var dynCall_viiii = Module["dynCall_viiii"] = function() {
8945
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8946
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8947
return Module["asm"]["dynCall_viiii"].apply(null, arguments)
8948
};
8949
8950
/** @type {function(...*):?} */
8951
var dynCall_d = Module["dynCall_d"] = function() {
8952
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8953
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8954
return Module["asm"]["dynCall_d"].apply(null, arguments)
8955
};
8956
8957
/** @type {function(...*):?} */
8958
var dynCall_iiiii = Module["dynCall_iiiii"] = function() {
8959
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8960
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8961
return Module["asm"]["dynCall_iiiii"].apply(null, arguments)
8962
};
8963
8964
/** @type {function(...*):?} */
8965
var dynCall_iiiiii = Module["dynCall_iiiiii"] = function() {
8966
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8967
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8968
return Module["asm"]["dynCall_iiiiii"].apply(null, arguments)
8969
};
8970
8971
/** @type {function(...*):?} */
8972
var dynCall_jiji = Module["dynCall_jiji"] = function() {
8973
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8974
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8975
return Module["asm"]["dynCall_jiji"].apply(null, arguments)
8976
};
8977
8978
/** @type {function(...*):?} */
8979
var dynCall_ji = Module["dynCall_ji"] = function() {
8980
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8981
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8982
return Module["asm"]["dynCall_ji"].apply(null, arguments)
8983
};
8984
8985
/** @type {function(...*):?} */
8986
var dynCall_iiiiidii = Module["dynCall_iiiiidii"] = function() {
8987
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8988
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8989
return Module["asm"]["dynCall_iiiiidii"].apply(null, arguments)
8990
};
8991
8992
/** @type {function(...*):?} */
8993
var dynCall_iiiiiiiiii = Module["dynCall_iiiiiiiiii"] = function() {
8994
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8995
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8996
return Module["asm"]["dynCall_iiiiiiiiii"].apply(null, arguments)
8997
};
8998
8999
/** @type {function(...*):?} */
9000
var dynCall_iiiiiiiii = Module["dynCall_iiiiiiiii"] = function() {
9001
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
9002
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
9003
return Module["asm"]["dynCall_iiiiiiiii"].apply(null, arguments)
9004
};
9005
9006
/** @type {function(...*):?} */
9007
var dynCall_viiiiiii = Module["dynCall_viiiiiii"] = function() {
9008
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
9009
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
9010
return Module["asm"]["dynCall_viiiiiii"].apply(null, arguments)
9011
};
9012
9013
/** @type {function(...*):?} */
9014
var dynCall_viiiiiiiiiii = Module["dynCall_viiiiiiiiiii"] = function() {
9015
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
9016
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
9017
return Module["asm"]["dynCall_viiiiiiiiiii"].apply(null, arguments)
9018
};
9019
9020
/** @type {function(...*):?} */
9021
var dynCall_iiiiiiii = Module["dynCall_iiiiiiii"] = function() {
9022
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
9023
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
9024
return Module["asm"]["dynCall_iiiiiiii"].apply(null, arguments)
9025
};
9026
9027
/** @type {function(...*):?} */
9028
var dynCall_iidiiii = Module["dynCall_iidiiii"] = function() {
9029
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
9030
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
9031
return Module["asm"]["dynCall_iidiiii"].apply(null, arguments)
9032
};
9033
9034
/** @type {function(...*):?} */
9035
var dynCall_viiiii = Module["dynCall_viiiii"] = function() {
9036
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
9037
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
9038
return Module["asm"]["dynCall_viiiii"].apply(null, arguments)
9039
};
9040
9041
/** @type {function(...*):?} */
9042
var dynCall_vffff = Module["dynCall_vffff"] = function() {
9043
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
9044
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
9045
return Module["asm"]["dynCall_vffff"].apply(null, arguments)
9046
};
9047
9048
/** @type {function(...*):?} */
9049
var dynCall_vf = Module["dynCall_vf"] = function() {
9050
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
9051
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
9052
return Module["asm"]["dynCall_vf"].apply(null, arguments)
9053
};
9054
9055
/** @type {function(...*):?} */
9056
var dynCall_viiiiiiii = Module["dynCall_viiiiiiii"] = function() {
9057
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
9058
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
9059
return Module["asm"]["dynCall_viiiiiiii"].apply(null, arguments)
9060
};
9061
9062
/** @type {function(...*):?} */
9063
var dynCall_viiiiiiiii = Module["dynCall_viiiiiiiii"] = function() {
9064
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
9065
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
9066
return Module["asm"]["dynCall_viiiiiiiii"].apply(null, arguments)
9067
};
9068
9069
/** @type {function(...*):?} */
9070
var dynCall_vff = Module["dynCall_vff"] = function() {
9071
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
9072
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
9073
return Module["asm"]["dynCall_vff"].apply(null, arguments)
9074
};
9075
9076
/** @type {function(...*):?} */
9077
var dynCall_vfi = Module["dynCall_vfi"] = function() {
9078
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
9079
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
9080
return Module["asm"]["dynCall_vfi"].apply(null, arguments)
9081
};
9082
9083
/** @type {function(...*):?} */
9084
var dynCall_viif = Module["dynCall_viif"] = function() {
9085
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
9086
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
9087
return Module["asm"]["dynCall_viif"].apply(null, arguments)
9088
};
9089
9090
/** @type {function(...*):?} */
9091
var dynCall_vif = Module["dynCall_vif"] = function() {
9092
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
9093
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
9094
return Module["asm"]["dynCall_vif"].apply(null, arguments)
9095
};
9096
9097
/** @type {function(...*):?} */
9098
var dynCall_viff = Module["dynCall_viff"] = function() {
9099
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
9100
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
9101
return Module["asm"]["dynCall_viff"].apply(null, arguments)
9102
};
9103
9104
/** @type {function(...*):?} */
9105
var dynCall_vifff = Module["dynCall_vifff"] = function() {
9106
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
9107
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
9108
return Module["asm"]["dynCall_vifff"].apply(null, arguments)
9109
};
9110
9111
/** @type {function(...*):?} */
9112
var dynCall_viffff = Module["dynCall_viffff"] = function() {
9113
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
9114
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
9115
return Module["asm"]["dynCall_viffff"].apply(null, arguments)
9116
};
9117
9118
/** @type {function(...*):?} */
9119
var dynCall_viiiiii = Module["dynCall_viiiiii"] = function() {
9120
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
9121
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
9122
return Module["asm"]["dynCall_viiiiii"].apply(null, arguments)
9123
};
9124
9125
9126
9127
9128
// === Auto-generated postamble setup entry stuff ===
9129
9130
Module['asm'] = asm;
9131
9132
if (!Object.getOwnPropertyDescriptor(Module, "intArrayFromString")) Module["intArrayFromString"] = function() { abort("'intArrayFromString' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9133
if (!Object.getOwnPropertyDescriptor(Module, "intArrayToString")) Module["intArrayToString"] = function() { abort("'intArrayToString' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9134
if (!Object.getOwnPropertyDescriptor(Module, "ccall")) Module["ccall"] = function() { abort("'ccall' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9135
if (!Object.getOwnPropertyDescriptor(Module, "cwrap")) Module["cwrap"] = function() { abort("'cwrap' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9136
if (!Object.getOwnPropertyDescriptor(Module, "setValue")) Module["setValue"] = function() { abort("'setValue' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9137
if (!Object.getOwnPropertyDescriptor(Module, "getValue")) Module["getValue"] = function() { abort("'getValue' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9138
if (!Object.getOwnPropertyDescriptor(Module, "allocate")) Module["allocate"] = function() { abort("'allocate' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9139
if (!Object.getOwnPropertyDescriptor(Module, "getMemory")) Module["getMemory"] = function() { abort("'getMemory' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you") };
9140
if (!Object.getOwnPropertyDescriptor(Module, "UTF8ArrayToString")) Module["UTF8ArrayToString"] = function() { abort("'UTF8ArrayToString' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9141
if (!Object.getOwnPropertyDescriptor(Module, "UTF8ToString")) Module["UTF8ToString"] = function() { abort("'UTF8ToString' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9142
if (!Object.getOwnPropertyDescriptor(Module, "stringToUTF8Array")) Module["stringToUTF8Array"] = function() { abort("'stringToUTF8Array' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9143
if (!Object.getOwnPropertyDescriptor(Module, "stringToUTF8")) Module["stringToUTF8"] = function() { abort("'stringToUTF8' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9144
if (!Object.getOwnPropertyDescriptor(Module, "lengthBytesUTF8")) Module["lengthBytesUTF8"] = function() { abort("'lengthBytesUTF8' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9145
if (!Object.getOwnPropertyDescriptor(Module, "stackTrace")) Module["stackTrace"] = function() { abort("'stackTrace' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9146
if (!Object.getOwnPropertyDescriptor(Module, "addOnPreRun")) Module["addOnPreRun"] = function() { abort("'addOnPreRun' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9147
if (!Object.getOwnPropertyDescriptor(Module, "addOnInit")) Module["addOnInit"] = function() { abort("'addOnInit' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9148
if (!Object.getOwnPropertyDescriptor(Module, "addOnPreMain")) Module["addOnPreMain"] = function() { abort("'addOnPreMain' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9149
if (!Object.getOwnPropertyDescriptor(Module, "addOnExit")) Module["addOnExit"] = function() { abort("'addOnExit' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9150
if (!Object.getOwnPropertyDescriptor(Module, "addOnPostRun")) Module["addOnPostRun"] = function() { abort("'addOnPostRun' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9151
if (!Object.getOwnPropertyDescriptor(Module, "writeStringToMemory")) Module["writeStringToMemory"] = function() { abort("'writeStringToMemory' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9152
if (!Object.getOwnPropertyDescriptor(Module, "writeArrayToMemory")) Module["writeArrayToMemory"] = function() { abort("'writeArrayToMemory' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9153
if (!Object.getOwnPropertyDescriptor(Module, "writeAsciiToMemory")) Module["writeAsciiToMemory"] = function() { abort("'writeAsciiToMemory' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9154
if (!Object.getOwnPropertyDescriptor(Module, "addRunDependency")) Module["addRunDependency"] = function() { abort("'addRunDependency' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you") };
9155
if (!Object.getOwnPropertyDescriptor(Module, "removeRunDependency")) Module["removeRunDependency"] = function() { abort("'removeRunDependency' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you") };
9156
if (!Object.getOwnPropertyDescriptor(Module, "FS_createFolder")) Module["FS_createFolder"] = function() { abort("'FS_createFolder' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you") };
9157
if (!Object.getOwnPropertyDescriptor(Module, "FS_createPath")) Module["FS_createPath"] = function() { abort("'FS_createPath' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you") };
9158
if (!Object.getOwnPropertyDescriptor(Module, "FS_createDataFile")) Module["FS_createDataFile"] = function() { abort("'FS_createDataFile' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you") };
9159
if (!Object.getOwnPropertyDescriptor(Module, "FS_createPreloadedFile")) Module["FS_createPreloadedFile"] = function() { abort("'FS_createPreloadedFile' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you") };
9160
if (!Object.getOwnPropertyDescriptor(Module, "FS_createLazyFile")) Module["FS_createLazyFile"] = function() { abort("'FS_createLazyFile' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you") };
9161
if (!Object.getOwnPropertyDescriptor(Module, "FS_createLink")) Module["FS_createLink"] = function() { abort("'FS_createLink' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you") };
9162
if (!Object.getOwnPropertyDescriptor(Module, "FS_createDevice")) Module["FS_createDevice"] = function() { abort("'FS_createDevice' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you") };
9163
if (!Object.getOwnPropertyDescriptor(Module, "FS_unlink")) Module["FS_unlink"] = function() { abort("'FS_unlink' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you") };
9164
if (!Object.getOwnPropertyDescriptor(Module, "dynamicAlloc")) Module["dynamicAlloc"] = function() { abort("'dynamicAlloc' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9165
if (!Object.getOwnPropertyDescriptor(Module, "loadDynamicLibrary")) Module["loadDynamicLibrary"] = function() { abort("'loadDynamicLibrary' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9166
if (!Object.getOwnPropertyDescriptor(Module, "loadWebAssemblyModule")) Module["loadWebAssemblyModule"] = function() { abort("'loadWebAssemblyModule' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9167
if (!Object.getOwnPropertyDescriptor(Module, "getLEB")) Module["getLEB"] = function() { abort("'getLEB' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9168
if (!Object.getOwnPropertyDescriptor(Module, "getFunctionTables")) Module["getFunctionTables"] = function() { abort("'getFunctionTables' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9169
if (!Object.getOwnPropertyDescriptor(Module, "alignFunctionTables")) Module["alignFunctionTables"] = function() { abort("'alignFunctionTables' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9170
if (!Object.getOwnPropertyDescriptor(Module, "registerFunctions")) Module["registerFunctions"] = function() { abort("'registerFunctions' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9171
if (!Object.getOwnPropertyDescriptor(Module, "addFunction")) Module["addFunction"] = function() { abort("'addFunction' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9172
if (!Object.getOwnPropertyDescriptor(Module, "removeFunction")) Module["removeFunction"] = function() { abort("'removeFunction' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9173
if (!Object.getOwnPropertyDescriptor(Module, "getFuncWrapper")) Module["getFuncWrapper"] = function() { abort("'getFuncWrapper' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9174
if (!Object.getOwnPropertyDescriptor(Module, "prettyPrint")) Module["prettyPrint"] = function() { abort("'prettyPrint' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9175
if (!Object.getOwnPropertyDescriptor(Module, "makeBigInt")) Module["makeBigInt"] = function() { abort("'makeBigInt' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9176
if (!Object.getOwnPropertyDescriptor(Module, "dynCall")) Module["dynCall"] = function() { abort("'dynCall' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9177
if (!Object.getOwnPropertyDescriptor(Module, "getCompilerSetting")) Module["getCompilerSetting"] = function() { abort("'getCompilerSetting' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9178
if (!Object.getOwnPropertyDescriptor(Module, "print")) Module["print"] = function() { abort("'print' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9179
if (!Object.getOwnPropertyDescriptor(Module, "printErr")) Module["printErr"] = function() { abort("'printErr' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9180
if (!Object.getOwnPropertyDescriptor(Module, "getTempRet0")) Module["getTempRet0"] = function() { abort("'getTempRet0' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9181
if (!Object.getOwnPropertyDescriptor(Module, "setTempRet0")) Module["setTempRet0"] = function() { abort("'setTempRet0' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9182
Module["callMain"] = callMain;
9183
if (!Object.getOwnPropertyDescriptor(Module, "abort")) Module["abort"] = function() { abort("'abort' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9184
if (!Object.getOwnPropertyDescriptor(Module, "stringToNewUTF8")) Module["stringToNewUTF8"] = function() { abort("'stringToNewUTF8' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9185
if (!Object.getOwnPropertyDescriptor(Module, "abortOnCannotGrowMemory")) Module["abortOnCannotGrowMemory"] = function() { abort("'abortOnCannotGrowMemory' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9186
if (!Object.getOwnPropertyDescriptor(Module, "emscripten_realloc_buffer")) Module["emscripten_realloc_buffer"] = function() { abort("'emscripten_realloc_buffer' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9187
if (!Object.getOwnPropertyDescriptor(Module, "ENV")) Module["ENV"] = function() { abort("'ENV' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9188
if (!Object.getOwnPropertyDescriptor(Module, "setjmpId")) Module["setjmpId"] = function() { abort("'setjmpId' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9189
if (!Object.getOwnPropertyDescriptor(Module, "ERRNO_CODES")) Module["ERRNO_CODES"] = function() { abort("'ERRNO_CODES' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9190
if (!Object.getOwnPropertyDescriptor(Module, "ERRNO_MESSAGES")) Module["ERRNO_MESSAGES"] = function() { abort("'ERRNO_MESSAGES' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9191
if (!Object.getOwnPropertyDescriptor(Module, "DNS")) Module["DNS"] = function() { abort("'DNS' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9192
if (!Object.getOwnPropertyDescriptor(Module, "GAI_ERRNO_MESSAGES")) Module["GAI_ERRNO_MESSAGES"] = function() { abort("'GAI_ERRNO_MESSAGES' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9193
if (!Object.getOwnPropertyDescriptor(Module, "Protocols")) Module["Protocols"] = function() { abort("'Protocols' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9194
if (!Object.getOwnPropertyDescriptor(Module, "Sockets")) Module["Sockets"] = function() { abort("'Sockets' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9195
if (!Object.getOwnPropertyDescriptor(Module, "UNWIND_CACHE")) Module["UNWIND_CACHE"] = function() { abort("'UNWIND_CACHE' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9196
if (!Object.getOwnPropertyDescriptor(Module, "readAsmConstArgs")) Module["readAsmConstArgs"] = function() { abort("'readAsmConstArgs' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9197
if (!Object.getOwnPropertyDescriptor(Module, "jstoi_q")) Module["jstoi_q"] = function() { abort("'jstoi_q' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9198
if (!Object.getOwnPropertyDescriptor(Module, "jstoi_s")) Module["jstoi_s"] = function() { abort("'jstoi_s' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9199
if (!Object.getOwnPropertyDescriptor(Module, "PATH")) Module["PATH"] = function() { abort("'PATH' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9200
if (!Object.getOwnPropertyDescriptor(Module, "PATH_FS")) Module["PATH_FS"] = function() { abort("'PATH_FS' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9201
if (!Object.getOwnPropertyDescriptor(Module, "SYSCALLS")) Module["SYSCALLS"] = function() { abort("'SYSCALLS' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9202
if (!Object.getOwnPropertyDescriptor(Module, "syscallMmap2")) Module["syscallMmap2"] = function() { abort("'syscallMmap2' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9203
if (!Object.getOwnPropertyDescriptor(Module, "syscallMunmap")) Module["syscallMunmap"] = function() { abort("'syscallMunmap' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9204
if (!Object.getOwnPropertyDescriptor(Module, "JSEvents")) Module["JSEvents"] = function() { abort("'JSEvents' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9205
if (!Object.getOwnPropertyDescriptor(Module, "demangle")) Module["demangle"] = function() { abort("'demangle' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9206
if (!Object.getOwnPropertyDescriptor(Module, "demangleAll")) Module["demangleAll"] = function() { abort("'demangleAll' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9207
if (!Object.getOwnPropertyDescriptor(Module, "jsStackTrace")) Module["jsStackTrace"] = function() { abort("'jsStackTrace' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9208
if (!Object.getOwnPropertyDescriptor(Module, "stackTrace")) Module["stackTrace"] = function() { abort("'stackTrace' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9209
if (!Object.getOwnPropertyDescriptor(Module, "writeI53ToI64")) Module["writeI53ToI64"] = function() { abort("'writeI53ToI64' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9210
if (!Object.getOwnPropertyDescriptor(Module, "writeI53ToI64Clamped")) Module["writeI53ToI64Clamped"] = function() { abort("'writeI53ToI64Clamped' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9211
if (!Object.getOwnPropertyDescriptor(Module, "writeI53ToI64Signaling")) Module["writeI53ToI64Signaling"] = function() { abort("'writeI53ToI64Signaling' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9212
if (!Object.getOwnPropertyDescriptor(Module, "writeI53ToU64Clamped")) Module["writeI53ToU64Clamped"] = function() { abort("'writeI53ToU64Clamped' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9213
if (!Object.getOwnPropertyDescriptor(Module, "writeI53ToU64Signaling")) Module["writeI53ToU64Signaling"] = function() { abort("'writeI53ToU64Signaling' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9214
if (!Object.getOwnPropertyDescriptor(Module, "readI53FromI64")) Module["readI53FromI64"] = function() { abort("'readI53FromI64' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9215
if (!Object.getOwnPropertyDescriptor(Module, "readI53FromU64")) Module["readI53FromU64"] = function() { abort("'readI53FromU64' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9216
if (!Object.getOwnPropertyDescriptor(Module, "convertI32PairToI53")) Module["convertI32PairToI53"] = function() { abort("'convertI32PairToI53' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9217
if (!Object.getOwnPropertyDescriptor(Module, "convertU32PairToI53")) Module["convertU32PairToI53"] = function() { abort("'convertU32PairToI53' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9218
if (!Object.getOwnPropertyDescriptor(Module, "Browser")) Module["Browser"] = function() { abort("'Browser' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9219
if (!Object.getOwnPropertyDescriptor(Module, "FS")) Module["FS"] = function() { abort("'FS' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9220
if (!Object.getOwnPropertyDescriptor(Module, "MEMFS")) Module["MEMFS"] = function() { abort("'MEMFS' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9221
if (!Object.getOwnPropertyDescriptor(Module, "TTY")) Module["TTY"] = function() { abort("'TTY' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9222
if (!Object.getOwnPropertyDescriptor(Module, "PIPEFS")) Module["PIPEFS"] = function() { abort("'PIPEFS' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9223
if (!Object.getOwnPropertyDescriptor(Module, "SOCKFS")) Module["SOCKFS"] = function() { abort("'SOCKFS' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9224
if (!Object.getOwnPropertyDescriptor(Module, "GL")) Module["GL"] = function() { abort("'GL' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9225
if (!Object.getOwnPropertyDescriptor(Module, "emscriptenWebGLGet")) Module["emscriptenWebGLGet"] = function() { abort("'emscriptenWebGLGet' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9226
if (!Object.getOwnPropertyDescriptor(Module, "emscriptenWebGLGetTexPixelData")) Module["emscriptenWebGLGetTexPixelData"] = function() { abort("'emscriptenWebGLGetTexPixelData' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9227
if (!Object.getOwnPropertyDescriptor(Module, "emscriptenWebGLGetUniform")) Module["emscriptenWebGLGetUniform"] = function() { abort("'emscriptenWebGLGetUniform' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9228
if (!Object.getOwnPropertyDescriptor(Module, "emscriptenWebGLGetVertexAttrib")) Module["emscriptenWebGLGetVertexAttrib"] = function() { abort("'emscriptenWebGLGetVertexAttrib' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9229
if (!Object.getOwnPropertyDescriptor(Module, "AL")) Module["AL"] = function() { abort("'AL' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9230
if (!Object.getOwnPropertyDescriptor(Module, "SDL")) Module["SDL"] = function() { abort("'SDL' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9231
if (!Object.getOwnPropertyDescriptor(Module, "SDL_gfx")) Module["SDL_gfx"] = function() { abort("'SDL_gfx' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9232
if (!Object.getOwnPropertyDescriptor(Module, "GLUT")) Module["GLUT"] = function() { abort("'GLUT' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9233
if (!Object.getOwnPropertyDescriptor(Module, "EGL")) Module["EGL"] = function() { abort("'EGL' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9234
if (!Object.getOwnPropertyDescriptor(Module, "GLFW_Window")) Module["GLFW_Window"] = function() { abort("'GLFW_Window' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9235
if (!Object.getOwnPropertyDescriptor(Module, "GLFW")) Module["GLFW"] = function() { abort("'GLFW' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9236
if (!Object.getOwnPropertyDescriptor(Module, "GLEW")) Module["GLEW"] = function() { abort("'GLEW' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9237
if (!Object.getOwnPropertyDescriptor(Module, "IDBStore")) Module["IDBStore"] = function() { abort("'IDBStore' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9238
if (!Object.getOwnPropertyDescriptor(Module, "runAndAbortIfError")) Module["runAndAbortIfError"] = function() { abort("'runAndAbortIfError' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9239
if (!Object.getOwnPropertyDescriptor(Module, "warnOnce")) Module["warnOnce"] = function() { abort("'warnOnce' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9240
if (!Object.getOwnPropertyDescriptor(Module, "stackSave")) Module["stackSave"] = function() { abort("'stackSave' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9241
if (!Object.getOwnPropertyDescriptor(Module, "stackRestore")) Module["stackRestore"] = function() { abort("'stackRestore' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9242
if (!Object.getOwnPropertyDescriptor(Module, "stackAlloc")) Module["stackAlloc"] = function() { abort("'stackAlloc' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9243
if (!Object.getOwnPropertyDescriptor(Module, "AsciiToString")) Module["AsciiToString"] = function() { abort("'AsciiToString' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9244
if (!Object.getOwnPropertyDescriptor(Module, "stringToAscii")) Module["stringToAscii"] = function() { abort("'stringToAscii' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9245
if (!Object.getOwnPropertyDescriptor(Module, "UTF16ToString")) Module["UTF16ToString"] = function() { abort("'UTF16ToString' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9246
if (!Object.getOwnPropertyDescriptor(Module, "stringToUTF16")) Module["stringToUTF16"] = function() { abort("'stringToUTF16' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9247
if (!Object.getOwnPropertyDescriptor(Module, "lengthBytesUTF16")) Module["lengthBytesUTF16"] = function() { abort("'lengthBytesUTF16' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9248
if (!Object.getOwnPropertyDescriptor(Module, "UTF32ToString")) Module["UTF32ToString"] = function() { abort("'UTF32ToString' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9249
if (!Object.getOwnPropertyDescriptor(Module, "stringToUTF32")) Module["stringToUTF32"] = function() { abort("'stringToUTF32' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9250
if (!Object.getOwnPropertyDescriptor(Module, "lengthBytesUTF32")) Module["lengthBytesUTF32"] = function() { abort("'lengthBytesUTF32' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9251
if (!Object.getOwnPropertyDescriptor(Module, "allocateUTF8")) Module["allocateUTF8"] = function() { abort("'allocateUTF8' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9252
if (!Object.getOwnPropertyDescriptor(Module, "allocateUTF8OnStack")) Module["allocateUTF8OnStack"] = function() { abort("'allocateUTF8OnStack' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9253
Module["writeStackCookie"] = writeStackCookie;
9254
Module["checkStackCookie"] = checkStackCookie;
9255
Module["abortStackOverflow"] = abortStackOverflow;if (!Object.getOwnPropertyDescriptor(Module, "ALLOC_NORMAL")) Object.defineProperty(Module, "ALLOC_NORMAL", { configurable: true, get: function() { abort("'ALLOC_NORMAL' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") } });
9256
if (!Object.getOwnPropertyDescriptor(Module, "ALLOC_STACK")) Object.defineProperty(Module, "ALLOC_STACK", { configurable: true, get: function() { abort("'ALLOC_STACK' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") } });
9257
if (!Object.getOwnPropertyDescriptor(Module, "ALLOC_DYNAMIC")) Object.defineProperty(Module, "ALLOC_DYNAMIC", { configurable: true, get: function() { abort("'ALLOC_DYNAMIC' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") } });
9258
if (!Object.getOwnPropertyDescriptor(Module, "ALLOC_NONE")) Object.defineProperty(Module, "ALLOC_NONE", { configurable: true, get: function() { abort("'ALLOC_NONE' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") } });
9259
9260
9261
9262
var calledRun;
9263
9264
9265
/**
9266
* @constructor
9267
* @this {ExitStatus}
9268
*/
9269
function ExitStatus(status) {
9270
this.name = "ExitStatus";
9271
this.message = "Program terminated with exit(" + status + ")";
9272
this.status = status;
9273
}
9274
9275
var calledMain = false;
9276
9277
9278
dependenciesFulfilled = function runCaller() {
9279
// If run has never been called, and we should call run (INVOKE_RUN is true, and Module.noInitialRun is not false)
9280
if (!calledRun) run();
9281
if (!calledRun) dependenciesFulfilled = runCaller; // try this again later, after new deps are fulfilled
9282
};
9283
9284
function callMain(args) {
9285
assert(runDependencies == 0, 'cannot call main when async dependencies remain! (listen on Module["onRuntimeInitialized"])');
9286
assert(__ATPRERUN__.length == 0, 'cannot call main when preRun functions remain to be called');
9287
9288
var entryFunction = Module['_main'];
9289
9290
9291
args = args || [];
9292
9293
var argc = args.length+1;
9294
var argv = stackAlloc((argc + 1) * 4);
9295
HEAP32[argv >> 2] = allocateUTF8OnStack(thisProgram);
9296
for (var i = 1; i < argc; i++) {
9297
HEAP32[(argv >> 2) + i] = allocateUTF8OnStack(args[i - 1]);
9298
}
9299
HEAP32[(argv >> 2) + argc] = 0;
9300
9301
9302
try {
9303
9304
Module['___set_stack_limit'](STACK_MAX);
9305
9306
var ret = entryFunction(argc, argv);
9307
9308
9309
// In PROXY_TO_PTHREAD builds, we should never exit the runtime below, as execution is asynchronously handed
9310
// off to a pthread.
9311
// if we're not running an evented main loop, it's time to exit
9312
exit(ret, /* implicit = */ true);
9313
}
9314
catch(e) {
9315
if (e instanceof ExitStatus) {
9316
// exit() throws this once it's done to make sure execution
9317
// has been stopped completely
9318
return;
9319
} else if (e == 'unwind') {
9320
// running an evented main loop, don't immediately exit
9321
noExitRuntime = true;
9322
return;
9323
} else {
9324
var toLog = e;
9325
if (e && typeof e === 'object' && e.stack) {
9326
toLog = [e, e.stack];
9327
}
9328
err('exception thrown: ' + toLog);
9329
quit_(1, e);
9330
}
9331
} finally {
9332
calledMain = true;
9333
}
9334
}
9335
9336
9337
9338
9339
/** @type {function(Array=)} */
9340
function run(args) {
9341
args = args || arguments_;
9342
9343
if (runDependencies > 0) {
9344
return;
9345
}
9346
9347
writeStackCookie();
9348
9349
preRun();
9350
9351
if (runDependencies > 0) return; // a preRun added a dependency, run will be called later
9352
9353
function doRun() {
9354
// run may have just been called through dependencies being fulfilled just in this very frame,
9355
// or while the async setStatus time below was happening
9356
if (calledRun) return;
9357
calledRun = true;
9358
Module['calledRun'] = true;
9359
9360
if (ABORT) return;
9361
9362
initRuntime();
9363
9364
preMain();
9365
9366
if (Module['onRuntimeInitialized']) Module['onRuntimeInitialized']();
9367
9368
if (shouldRunNow) callMain(args);
9369
9370
postRun();
9371
}
9372
9373
if (Module['setStatus']) {
9374
Module['setStatus']('Running...');
9375
setTimeout(function() {
9376
setTimeout(function() {
9377
Module['setStatus']('');
9378
}, 1);
9379
doRun();
9380
}, 1);
9381
} else
9382
{
9383
doRun();
9384
}
9385
checkStackCookie();
9386
}
9387
Module['run'] = run;
9388
9389
function checkUnflushedContent() {
9390
// Compiler settings do not allow exiting the runtime, so flushing
9391
// the streams is not possible. but in ASSERTIONS mode we check
9392
// if there was something to flush, and if so tell the user they
9393
// should request that the runtime be exitable.
9394
// Normally we would not even include flush() at all, but in ASSERTIONS
9395
// builds we do so just for this check, and here we see if there is any
9396
// content to flush, that is, we check if there would have been
9397
// something a non-ASSERTIONS build would have not seen.
9398
// How we flush the streams depends on whether we are in SYSCALLS_REQUIRE_FILESYSTEM=0
9399
// mode (which has its own special function for this; otherwise, all
9400
// the code is inside libc)
9401
var print = out;
9402
var printErr = err;
9403
var has = false;
9404
out = err = function(x) {
9405
has = true;
9406
}
9407
try { // it doesn't matter if it fails
9408
var flush = Module['_fflush'];
9409
if (flush) flush(0);
9410
// also flush in the JS FS layer
9411
['stdout', 'stderr'].forEach(function(name) {
9412
var info = FS.analyzePath('/dev/' + name);
9413
if (!info) return;
9414
var stream = info.object;
9415
var rdev = stream.rdev;
9416
var tty = TTY.ttys[rdev];
9417
if (tty && tty.output && tty.output.length) {
9418
has = true;
9419
}
9420
});
9421
} catch(e) {}
9422
out = print;
9423
err = printErr;
9424
if (has) {
9425
warnOnce('stdio streams had content in them that was not flushed. you should set EXIT_RUNTIME to 1 (see the FAQ), or make sure to emit a newline when you printf etc.');
9426
}
9427
}
9428
9429
/** @param {boolean|number=} implicit */
9430
function exit(status, implicit) {
9431
checkUnflushedContent();
9432
9433
// if this is just main exit-ing implicitly, and the status is 0, then we
9434
// don't need to do anything here and can just leave. if the status is
9435
// non-zero, though, then we need to report it.
9436
// (we may have warned about this earlier, if a situation justifies doing so)
9437
if (implicit && noExitRuntime && status === 0) {
9438
return;
9439
}
9440
9441
if (noExitRuntime) {
9442
// if exit() was called, we may warn the user if the runtime isn't actually being shut down
9443
if (!implicit) {
9444
err('program exited (with status: ' + status + '), but EXIT_RUNTIME is not set, so halting execution but not exiting the runtime or preventing further async execution (build with EXIT_RUNTIME=1, if you want a true shutdown)');
9445
}
9446
} else {
9447
9448
ABORT = true;
9449
EXITSTATUS = status;
9450
9451
exitRuntime();
9452
9453
if (Module['onExit']) Module['onExit'](status);
9454
}
9455
9456
quit_(status, new ExitStatus(status));
9457
}
9458
9459
if (Module['preInit']) {
9460
if (typeof Module['preInit'] == 'function') Module['preInit'] = [Module['preInit']];
9461
while (Module['preInit'].length > 0) {
9462
Module['preInit'].pop()();
9463
}
9464
}
9465
9466
// shouldRunNow refers to calling main(), not run().
9467
var shouldRunNow = true;
9468
9469
if (Module['noInitialRun']) shouldRunNow = false;
9470
9471
9472
noExitRuntime = true;
9473
9474
run();
9475
9476
9477
9478
9479
9480
// {{MODULE_ADDITIONS}}
9481
9482
9483
9484
9485