Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
titaniumnetwork-dev
GitHub Repository: titaniumnetwork-dev/Incognito-old
Path: blob/main/static/src/gs/public/sm64/sm64.us.f3dex2e.js
1344 views
1
// Copyright 2010 The Emscripten Authors. All rights reserved.
2
// Emscripten is available under two separate licenses, the MIT license and the
3
// University of Illinois/NCSA Open Source License. Both these licenses can be
4
// found in the LICENSE file.
5
6
// The Module object: Our interface to the outside world. We import
7
// and export values on it. There are various ways Module can be used:
8
// 1. Not defined. We create it here
9
// 2. A function parameter, function(Module) { ..generated code.. }
10
// 3. pre-run appended it, var Module = {}; ..generated code..
11
// 4. External script tag defines var Module.
12
// We need to check if Module already exists (e.g. case 3 above).
13
// Substitution will be replaced with actual code on later stage of the build,
14
// this way Closure Compiler will not mangle it (e.g. case 4. above).
15
// Note that if you want to run closure, and also to use Module
16
// after the generated code, you will need to define var Module = {};
17
// before the code. Then that object will be used in the code, and you
18
// can continue to use Module afterwards as well.
19
var Module = typeof Module !== 'undefined' ? Module : {};
20
21
// --pre-jses are emitted after the Module integration code, so that they can
22
// refer to Module (if they choose; they can also define Module)
23
// {{PRE_JSES}}
24
25
// Sometimes an existing Module object exists with properties
26
// meant to overwrite the default module functionality. Here
27
// we collect those properties and reapply _after_ we configure
28
// the current environment's defaults to avoid having to be so
29
// defensive during initialization.
30
var moduleOverrides = {};
31
var key;
32
for (key in Module) {
33
if (Module.hasOwnProperty(key)) {
34
moduleOverrides[key] = Module[key];
35
}
36
}
37
38
var arguments_ = [];
39
var thisProgram = './this.program';
40
var quit_ = function(status, toThrow) {
41
throw toThrow;
42
};
43
44
// Determine the runtime environment we are in. You can customize this by
45
// setting the ENVIRONMENT setting at compile time (see settings.js).
46
47
var ENVIRONMENT_IS_WEB = false;
48
var ENVIRONMENT_IS_WORKER = false;
49
var ENVIRONMENT_IS_NODE = false;
50
var ENVIRONMENT_IS_SHELL = false;
51
ENVIRONMENT_IS_WEB = typeof window === 'object';
52
ENVIRONMENT_IS_WORKER = typeof importScripts === 'function';
53
// N.b. Electron.js environment is simultaneously a NODE-environment, but
54
// also a web environment.
55
ENVIRONMENT_IS_NODE = typeof process === 'object' && typeof process.versions === 'object' && typeof process.versions.node === 'string';
56
ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER;
57
58
if (Module['ENVIRONMENT']) {
59
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)');
60
}
61
62
63
64
// `/` should be present at the end if `scriptDirectory` is not empty
65
var scriptDirectory = '';
66
function locateFile(path) {
67
if (Module['locateFile']) {
68
return Module['locateFile'](path, scriptDirectory);
69
}
70
return scriptDirectory + path;
71
}
72
73
// Hooks that are implemented differently in different runtime environments.
74
var read_,
75
readAsync,
76
readBinary,
77
setWindowTitle;
78
79
var nodeFS;
80
var nodePath;
81
82
if (ENVIRONMENT_IS_NODE) {
83
if (ENVIRONMENT_IS_WORKER) {
84
scriptDirectory = require('path').dirname(scriptDirectory) + '/';
85
} else {
86
scriptDirectory = __dirname + '/';
87
}
88
89
90
read_ = function shell_read(filename, binary) {
91
if (!nodeFS) nodeFS = require('fs');
92
if (!nodePath) nodePath = require('path');
93
filename = nodePath['normalize'](filename);
94
return nodeFS['readFileSync'](filename, binary ? null : 'utf8');
95
};
96
97
readBinary = function readBinary(filename) {
98
var ret = read_(filename, true);
99
if (!ret.buffer) {
100
ret = new Uint8Array(ret);
101
}
102
assert(ret.buffer);
103
return ret;
104
};
105
106
107
108
109
if (process['argv'].length > 1) {
110
thisProgram = process['argv'][1].replace(/\\/g, '/');
111
}
112
113
arguments_ = process['argv'].slice(2);
114
115
if (typeof module !== 'undefined') {
116
module['exports'] = Module;
117
}
118
119
process['on']('uncaughtException', function(ex) {
120
// suppress ExitStatus exceptions from showing an error
121
if (!(ex instanceof ExitStatus)) {
122
throw ex;
123
}
124
});
125
126
process['on']('unhandledRejection', abort);
127
128
quit_ = function(status) {
129
process['exit'](status);
130
};
131
132
Module['inspect'] = function () { return '[Emscripten Module object]'; };
133
134
135
136
} else
137
if (ENVIRONMENT_IS_SHELL) {
138
139
140
if (typeof read != 'undefined') {
141
read_ = function shell_read(f) {
142
return read(f);
143
};
144
}
145
146
readBinary = function readBinary(f) {
147
var data;
148
if (typeof readbuffer === 'function') {
149
return new Uint8Array(readbuffer(f));
150
}
151
data = read(f, 'binary');
152
assert(typeof data === 'object');
153
return data;
154
};
155
156
if (typeof scriptArgs != 'undefined') {
157
arguments_ = scriptArgs;
158
} else if (typeof arguments != 'undefined') {
159
arguments_ = arguments;
160
}
161
162
if (typeof quit === 'function') {
163
quit_ = function(status) {
164
quit(status);
165
};
166
}
167
168
if (typeof print !== 'undefined') {
169
// Prefer to use print/printErr where they exist, as they usually work better.
170
if (typeof console === 'undefined') console = /** @type{!Console} */({});
171
console.log = /** @type{!function(this:Console, ...*): undefined} */ (print);
172
console.warn = console.error = /** @type{!function(this:Console, ...*): undefined} */ (typeof printErr !== 'undefined' ? printErr : print);
173
}
174
175
176
} else
177
178
// Note that this includes Node.js workers when relevant (pthreads is enabled).
179
// Node.js workers are detected as a combination of ENVIRONMENT_IS_WORKER and
180
// ENVIRONMENT_IS_NODE.
181
if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) {
182
if (ENVIRONMENT_IS_WORKER) { // Check worker, not web, since window could be polyfilled
183
scriptDirectory = self.location.href;
184
} else if (document.currentScript) { // web
185
scriptDirectory = document.currentScript.src;
186
}
187
// blob urls look like blob:http://site.com/etc/etc and we cannot infer anything from them.
188
// otherwise, slice off the final part of the url to find the script directory.
189
// if scriptDirectory does not contain a slash, lastIndexOf will return -1,
190
// and scriptDirectory will correctly be replaced with an empty string.
191
if (scriptDirectory.indexOf('blob:') !== 0) {
192
scriptDirectory = scriptDirectory.substr(0, scriptDirectory.lastIndexOf('/')+1);
193
} else {
194
scriptDirectory = '';
195
}
196
197
198
// Differentiate the Web Worker from the Node Worker case, as reading must
199
// be done differently.
200
{
201
202
203
read_ = function shell_read(url) {
204
var xhr = new XMLHttpRequest();
205
xhr.open('GET', url, false);
206
xhr.send(null);
207
return xhr.responseText;
208
};
209
210
if (ENVIRONMENT_IS_WORKER) {
211
readBinary = function readBinary(url) {
212
var xhr = new XMLHttpRequest();
213
xhr.open('GET', url, false);
214
xhr.responseType = 'arraybuffer';
215
xhr.send(null);
216
return new Uint8Array(/** @type{!ArrayBuffer} */(xhr.response));
217
};
218
}
219
220
readAsync = function readAsync(url, onload, onerror) {
221
var xhr = new XMLHttpRequest();
222
xhr.open('GET', url, true);
223
xhr.responseType = 'arraybuffer';
224
xhr.onload = function xhr_onload() {
225
if (xhr.status == 200 || (xhr.status == 0 && xhr.response)) { // file URLs can return 0
226
onload(xhr.response);
227
return;
228
}
229
onerror();
230
};
231
xhr.onerror = onerror;
232
xhr.send(null);
233
};
234
235
236
237
238
}
239
240
setWindowTitle = function(title) { document.title = title };
241
} else
242
{
243
throw new Error('environment detection error');
244
}
245
246
247
// Set up the out() and err() hooks, which are how we can print to stdout or
248
// stderr, respectively.
249
var out = Module['print'] || console.log.bind(console);
250
var err = Module['printErr'] || console.warn.bind(console);
251
252
// Merge back in the overrides
253
for (key in moduleOverrides) {
254
if (moduleOverrides.hasOwnProperty(key)) {
255
Module[key] = moduleOverrides[key];
256
}
257
}
258
// Free the object hierarchy contained in the overrides, this lets the GC
259
// reclaim data used e.g. in memoryInitializerRequest, which is a large typed array.
260
moduleOverrides = null;
261
262
// Emit code to handle expected values on the Module object. This applies Module.x
263
// to the proper local x. This has two benefits: first, we only emit it if it is
264
// expected to arrive, and second, by using a local everywhere else that can be
265
// minified.
266
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_') } });
267
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') } });
268
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_') } });
269
270
// perform assertions in shell.js after we set up out() and err(), as otherwise if an assertion fails it cannot print the message
271
// Assertions on removed incoming Module JS APIs.
272
assert(typeof Module['memoryInitializerPrefixURL'] === 'undefined', 'Module.memoryInitializerPrefixURL option was removed, use Module.locateFile instead');
273
assert(typeof Module['pthreadMainPrefixURL'] === 'undefined', 'Module.pthreadMainPrefixURL option was removed, use Module.locateFile instead');
274
assert(typeof Module['cdInitializerPrefixURL'] === 'undefined', 'Module.cdInitializerPrefixURL option was removed, use Module.locateFile instead');
275
assert(typeof Module['filePackagePrefixURL'] === 'undefined', 'Module.filePackagePrefixURL option was removed, use Module.locateFile instead');
276
assert(typeof Module['read'] === 'undefined', 'Module.read option was removed (modify read_ in JS)');
277
assert(typeof Module['readAsync'] === 'undefined', 'Module.readAsync option was removed (modify readAsync in JS)');
278
assert(typeof Module['readBinary'] === 'undefined', 'Module.readBinary option was removed (modify readBinary in JS)');
279
assert(typeof Module['setWindowTitle'] === 'undefined', 'Module.setWindowTitle option was removed (modify setWindowTitle in JS)');
280
assert(typeof Module['TOTAL_MEMORY'] === 'undefined', 'Module.TOTAL_MEMORY has been renamed Module.INITIAL_MEMORY');
281
if (!Object.getOwnPropertyDescriptor(Module, 'read')) Object.defineProperty(Module, 'read', { configurable: true, get: function() { abort('Module.read has been replaced with plain read_') } });
282
if (!Object.getOwnPropertyDescriptor(Module, 'readAsync')) Object.defineProperty(Module, 'readAsync', { configurable: true, get: function() { abort('Module.readAsync has been replaced with plain readAsync') } });
283
if (!Object.getOwnPropertyDescriptor(Module, 'readBinary')) Object.defineProperty(Module, 'readBinary', { configurable: true, get: function() { abort('Module.readBinary has been replaced with plain readBinary') } });
284
// 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') } });
285
var IDBFS = 'IDBFS is no longer included by default; build with -lidbfs.js';
286
var PROXYFS = 'PROXYFS is no longer included by default; build with -lproxyfs.js';
287
var WORKERFS = 'WORKERFS is no longer included by default; build with -lworkerfs.js';
288
var NODEFS = 'NODEFS is no longer included by default; build with -lnodefs.js';
289
290
291
// TODO remove when SDL2 is fixed (also see above)
292
293
294
295
// Copyright 2017 The Emscripten Authors. All rights reserved.
296
// Emscripten is available under two separate licenses, the MIT license and the
297
// University of Illinois/NCSA Open Source License. Both these licenses can be
298
// found in the LICENSE file.
299
300
// {{PREAMBLE_ADDITIONS}}
301
302
var STACK_ALIGN = 16;
303
304
// stack management, and other functionality that is provided by the compiled code,
305
// should not be used before it is ready
306
307
/** @suppress{duplicate} */
308
var stackSave;
309
/** @suppress{duplicate} */
310
var stackRestore;
311
/** @suppress{duplicate} */
312
var stackAlloc;
313
314
stackSave = stackRestore = stackAlloc = function() {
315
abort('cannot use the stack before compiled code is ready to run, and has provided stack access');
316
};
317
318
function staticAlloc(size) {
319
abort('staticAlloc is no longer available at runtime; instead, perform static allocations at compile time (using makeStaticAlloc)');
320
}
321
322
function dynamicAlloc(size) {
323
assert(DYNAMICTOP_PTR);
324
var ret = HEAP32[DYNAMICTOP_PTR>>2];
325
var end = (ret + size + 15) & -16;
326
assert(end <= HEAP8.length, 'failure to dynamicAlloc - memory growth etc. is not supported there, call malloc/sbrk directly');
327
HEAP32[DYNAMICTOP_PTR>>2] = end;
328
return ret;
329
}
330
331
function alignMemory(size, factor) {
332
if (!factor) factor = STACK_ALIGN; // stack alignment (16-byte) by default
333
return Math.ceil(size / factor) * factor;
334
}
335
336
function getNativeTypeSize(type) {
337
switch (type) {
338
case 'i1': case 'i8': return 1;
339
case 'i16': return 2;
340
case 'i32': return 4;
341
case 'i64': return 8;
342
case 'float': return 4;
343
case 'double': return 8;
344
default: {
345
if (type[type.length-1] === '*') {
346
return 4; // A pointer
347
} else if (type[0] === 'i') {
348
var bits = Number(type.substr(1));
349
assert(bits % 8 === 0, 'getNativeTypeSize invalid bits ' + bits + ', type ' + type);
350
return bits / 8;
351
} else {
352
return 0;
353
}
354
}
355
}
356
}
357
358
function warnOnce(text) {
359
if (!warnOnce.shown) warnOnce.shown = {};
360
if (!warnOnce.shown[text]) {
361
warnOnce.shown[text] = 1;
362
err(text);
363
}
364
}
365
366
367
368
369
370
371
// Wraps a JS function as a wasm function with a given signature.
372
function convertJsFunctionToWasm(func, sig) {
373
374
// If the type reflection proposal is available, use the new
375
// "WebAssembly.Function" constructor.
376
// Otherwise, construct a minimal wasm module importing the JS function and
377
// re-exporting it.
378
if (typeof WebAssembly.Function === "function") {
379
var typeNames = {
380
'i': 'i32',
381
'j': 'i64',
382
'f': 'f32',
383
'd': 'f64'
384
};
385
var type = {
386
parameters: [],
387
results: sig[0] == 'v' ? [] : [typeNames[sig[0]]]
388
};
389
for (var i = 1; i < sig.length; ++i) {
390
type.parameters.push(typeNames[sig[i]]);
391
}
392
return new WebAssembly.Function(type, func);
393
}
394
395
// The module is static, with the exception of the type section, which is
396
// generated based on the signature passed in.
397
var typeSection = [
398
0x01, // id: section,
399
0x00, // length: 0 (placeholder)
400
0x01, // count: 1
401
0x60, // form: func
402
];
403
var sigRet = sig.slice(0, 1);
404
var sigParam = sig.slice(1);
405
var typeCodes = {
406
'i': 0x7f, // i32
407
'j': 0x7e, // i64
408
'f': 0x7d, // f32
409
'd': 0x7c, // f64
410
};
411
412
// Parameters, length + signatures
413
typeSection.push(sigParam.length);
414
for (var i = 0; i < sigParam.length; ++i) {
415
typeSection.push(typeCodes[sigParam[i]]);
416
}
417
418
// Return values, length + signatures
419
// With no multi-return in MVP, either 0 (void) or 1 (anything else)
420
if (sigRet == 'v') {
421
typeSection.push(0x00);
422
} else {
423
typeSection = typeSection.concat([0x01, typeCodes[sigRet]]);
424
}
425
426
// Write the overall length of the type section back into the section header
427
// (excepting the 2 bytes for the section id and length)
428
typeSection[1] = typeSection.length - 2;
429
430
// Rest of the module is static
431
var bytes = new Uint8Array([
432
0x00, 0x61, 0x73, 0x6d, // magic ("\0asm")
433
0x01, 0x00, 0x00, 0x00, // version: 1
434
].concat(typeSection, [
435
0x02, 0x07, // import section
436
// (import "e" "f" (func 0 (type 0)))
437
0x01, 0x01, 0x65, 0x01, 0x66, 0x00, 0x00,
438
0x07, 0x05, // export section
439
// (export "f" (func 0 (type 0)))
440
0x01, 0x01, 0x66, 0x00, 0x00,
441
]));
442
443
// We can compile this wasm module synchronously because it is very small.
444
// This accepts an import (at "e.f"), that it reroutes to an export (at "f")
445
var module = new WebAssembly.Module(bytes);
446
var instance = new WebAssembly.Instance(module, {
447
'e': {
448
'f': func
449
}
450
});
451
var wrappedFunc = instance.exports['f'];
452
return wrappedFunc;
453
}
454
455
var freeTableIndexes = [];
456
457
// Add a wasm function to the table.
458
function addFunctionWasm(func, sig) {
459
var table = wasmTable;
460
var ret;
461
// Reuse a free index if there is one, otherwise grow.
462
if (freeTableIndexes.length) {
463
ret = freeTableIndexes.pop();
464
} else {
465
ret = table.length;
466
// Grow the table
467
try {
468
table.grow(1);
469
} catch (err) {
470
if (!(err instanceof RangeError)) {
471
throw err;
472
}
473
throw 'Unable to grow wasm table. Set ALLOW_TABLE_GROWTH.';
474
}
475
}
476
477
// Set the new value.
478
try {
479
// Attempting to call this with JS function will cause of table.set() to fail
480
table.set(ret, func);
481
} catch (err) {
482
if (!(err instanceof TypeError)) {
483
throw err;
484
}
485
assert(typeof sig !== 'undefined', 'Missing signature argument to addFunction');
486
var wrapped = convertJsFunctionToWasm(func, sig);
487
table.set(ret, wrapped);
488
}
489
490
return ret;
491
}
492
493
function removeFunctionWasm(index) {
494
freeTableIndexes.push(index);
495
}
496
497
// 'sig' parameter is required for the llvm backend but only when func is not
498
// already a WebAssembly function.
499
function addFunction(func, sig) {
500
assert(typeof func !== 'undefined');
501
502
return addFunctionWasm(func, sig);
503
}
504
505
function removeFunction(index) {
506
removeFunctionWasm(index);
507
}
508
509
510
511
var funcWrappers = {};
512
513
function getFuncWrapper(func, sig) {
514
if (!func) return; // on null pointer, return undefined
515
assert(sig);
516
if (!funcWrappers[sig]) {
517
funcWrappers[sig] = {};
518
}
519
var sigCache = funcWrappers[sig];
520
if (!sigCache[func]) {
521
// optimize away arguments usage in common cases
522
if (sig.length === 1) {
523
sigCache[func] = function dynCall_wrapper() {
524
return dynCall(sig, func);
525
};
526
} else if (sig.length === 2) {
527
sigCache[func] = function dynCall_wrapper(arg) {
528
return dynCall(sig, func, [arg]);
529
};
530
} else {
531
// general case
532
sigCache[func] = function dynCall_wrapper() {
533
return dynCall(sig, func, Array.prototype.slice.call(arguments));
534
};
535
}
536
}
537
return sigCache[func];
538
}
539
540
541
542
543
544
function makeBigInt(low, high, unsigned) {
545
return unsigned ? ((+((low>>>0)))+((+((high>>>0)))*4294967296.0)) : ((+((low>>>0)))+((+((high|0)))*4294967296.0));
546
}
547
548
/** @param {Array=} args */
549
function dynCall(sig, ptr, args) {
550
if (args && args.length) {
551
// j (64-bit integer) must be passed in as two numbers [low 32, high 32].
552
assert(args.length === sig.substring(1).replace(/j/g, '--').length);
553
assert(('dynCall_' + sig) in Module, 'bad function pointer type - no table for sig \'' + sig + '\'');
554
return Module['dynCall_' + sig].apply(null, [ptr].concat(args));
555
} else {
556
assert(sig.length == 1);
557
assert(('dynCall_' + sig) in Module, 'bad function pointer type - no table for sig \'' + sig + '\'');
558
return Module['dynCall_' + sig].call(null, ptr);
559
}
560
}
561
562
var tempRet0 = 0;
563
564
var setTempRet0 = function(value) {
565
tempRet0 = value;
566
};
567
568
var getTempRet0 = function() {
569
return tempRet0;
570
};
571
572
function getCompilerSetting(name) {
573
throw 'You must build with -s RETAIN_COMPILER_SETTINGS=1 for getCompilerSetting or emscripten_get_compiler_setting to work';
574
}
575
576
var Runtime = {
577
// helpful errors
578
getTempRet0: function() { abort('getTempRet0() is now a top-level function, after removing the Runtime object. Remove "Runtime."') },
579
staticAlloc: function() { abort('staticAlloc() is now a top-level function, after removing the Runtime object. Remove "Runtime."') },
580
stackAlloc: function() { abort('stackAlloc() is now a top-level function, after removing the Runtime object. Remove "Runtime."') },
581
};
582
583
// The address globals begin at. Very low in memory, for code size and optimization opportunities.
584
// Above 0 is static memory, starting with globals.
585
// Then the stack.
586
// Then 'dynamic' memory for sbrk.
587
var GLOBAL_BASE = 1024;
588
589
590
591
592
// === Preamble library stuff ===
593
594
// Documentation for the public APIs defined in this file must be updated in:
595
// site/source/docs/api_reference/preamble.js.rst
596
// A prebuilt local version of the documentation is available at:
597
// site/build/text/docs/api_reference/preamble.js.txt
598
// You can also build docs locally as HTML or other formats in site/
599
// An online HTML version (which may be of a different version of Emscripten)
600
// is up at http://kripken.github.io/emscripten-site/docs/api_reference/preamble.js.html
601
602
603
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') } });
604
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') } });
605
606
607
if (typeof WebAssembly !== 'object') {
608
abort('No WebAssembly support found. Build with -s WASM=0 to target JavaScript instead.');
609
}
610
611
612
// In MINIMAL_RUNTIME, setValue() and getValue() are only available when building with safe heap enabled, for heap safety checking.
613
// In traditional runtime, setValue() and getValue() are always available (although their use is highly discouraged due to perf penalties)
614
615
/** @param {number} ptr
616
@param {number} value
617
@param {string} type
618
@param {number|boolean=} noSafe */
619
function setValue(ptr, value, type, noSafe) {
620
type = type || 'i8';
621
if (type.charAt(type.length-1) === '*') type = 'i32'; // pointers are 32-bit
622
switch(type) {
623
case 'i1': HEAP8[((ptr)>>0)]=value; break;
624
case 'i8': HEAP8[((ptr)>>0)]=value; break;
625
case 'i16': HEAP16[((ptr)>>1)]=value; break;
626
case 'i32': HEAP32[((ptr)>>2)]=value; break;
627
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;
628
case 'float': HEAPF32[((ptr)>>2)]=value; break;
629
case 'double': HEAPF64[((ptr)>>3)]=value; break;
630
default: abort('invalid type for setValue: ' + type);
631
}
632
}
633
634
/** @param {number} ptr
635
@param {string} type
636
@param {number|boolean=} noSafe */
637
function getValue(ptr, type, noSafe) {
638
type = type || 'i8';
639
if (type.charAt(type.length-1) === '*') type = 'i32'; // pointers are 32-bit
640
switch(type) {
641
case 'i1': return HEAP8[((ptr)>>0)];
642
case 'i8': return HEAP8[((ptr)>>0)];
643
case 'i16': return HEAP16[((ptr)>>1)];
644
case 'i32': return HEAP32[((ptr)>>2)];
645
case 'i64': return HEAP32[((ptr)>>2)];
646
case 'float': return HEAPF32[((ptr)>>2)];
647
case 'double': return HEAPF64[((ptr)>>3)];
648
default: abort('invalid type for getValue: ' + type);
649
}
650
return null;
651
}
652
653
654
655
656
657
// Wasm globals
658
659
var wasmMemory;
660
661
// In fastcomp asm.js, we don't need a wasm Table at all.
662
// In the wasm backend, we polyfill the WebAssembly object,
663
// so this creates a (non-native-wasm) table for us.
664
var wasmTable = new WebAssembly.Table({
665
'initial': 1821,
666
'maximum': 1821 + 0,
667
'element': 'anyfunc'
668
});
669
670
671
//========================================
672
// Runtime essentials
673
//========================================
674
675
// whether we are quitting the application. no code should run after this.
676
// set in exit() and abort()
677
var ABORT = false;
678
679
// set by exit() and abort(). Passed to 'onExit' handler.
680
// NOTE: This is also used as the process return code code in shell environments
681
// but only when noExitRuntime is false.
682
var EXITSTATUS = 0;
683
684
/** @type {function(*, string=)} */
685
function assert(condition, text) {
686
if (!condition) {
687
abort('Assertion failed: ' + text);
688
}
689
}
690
691
// Returns the C function with a specified identifier (for C++, you need to do manual name mangling)
692
function getCFunc(ident) {
693
var func = Module['_' + ident]; // closure exported function
694
assert(func, 'Cannot call unknown function ' + ident + ', make sure it is exported');
695
return func;
696
}
697
698
// C calling interface.
699
/** @param {Array=} argTypes
700
@param {Arguments|Array=} args
701
@param {Object=} opts */
702
function ccall(ident, returnType, argTypes, args, opts) {
703
// For fast lookup of conversion functions
704
var toC = {
705
'string': function(str) {
706
var ret = 0;
707
if (str !== null && str !== undefined && str !== 0) { // null string
708
// at most 4 bytes per UTF-8 code point, +1 for the trailing '\0'
709
var len = (str.length << 2) + 1;
710
ret = stackAlloc(len);
711
stringToUTF8(str, ret, len);
712
}
713
return ret;
714
},
715
'array': function(arr) {
716
var ret = stackAlloc(arr.length);
717
writeArrayToMemory(arr, ret);
718
return ret;
719
}
720
};
721
722
function convertReturnValue(ret) {
723
if (returnType === 'string') return UTF8ToString(ret);
724
if (returnType === 'boolean') return Boolean(ret);
725
return ret;
726
}
727
728
var func = getCFunc(ident);
729
var cArgs = [];
730
var stack = 0;
731
assert(returnType !== 'array', 'Return type should not be "array".');
732
if (args) {
733
for (var i = 0; i < args.length; i++) {
734
var converter = toC[argTypes[i]];
735
if (converter) {
736
if (stack === 0) stack = stackSave();
737
cArgs[i] = converter(args[i]);
738
} else {
739
cArgs[i] = args[i];
740
}
741
}
742
}
743
var ret = func.apply(null, cArgs);
744
745
ret = convertReturnValue(ret);
746
if (stack !== 0) stackRestore(stack);
747
return ret;
748
}
749
750
/** @param {Array=} argTypes
751
@param {Object=} opts */
752
function cwrap(ident, returnType, argTypes, opts) {
753
return function() {
754
return ccall(ident, returnType, argTypes, arguments, opts);
755
}
756
}
757
758
var ALLOC_NORMAL = 0; // Tries to use _malloc()
759
var ALLOC_STACK = 1; // Lives for the duration of the current function call
760
var ALLOC_DYNAMIC = 2; // Cannot be freed except through sbrk
761
var ALLOC_NONE = 3; // Do not allocate
762
763
// allocate(): This is for internal use. You can use it yourself as well, but the interface
764
// is a little tricky (see docs right below). The reason is that it is optimized
765
// for multiple syntaxes to save space in generated code. So you should
766
// normally not use allocate(), and instead allocate memory using _malloc(),
767
// initialize it with setValue(), and so forth.
768
// @slab: An array of data, or a number. If a number, then the size of the block to allocate,
769
// in *bytes* (note that this is sometimes confusing: the next parameter does not
770
// affect this!)
771
// @types: Either an array of types, one for each byte (or 0 if no type at that position),
772
// or a single type which is used for the entire block. This only matters if there
773
// is initial data - if @slab is a number, then this does not matter at all and is
774
// ignored.
775
// @allocator: How to allocate memory, see ALLOC_*
776
/** @type {function((TypedArray|Array<number>|number), string, number, number=)} */
777
function allocate(slab, types, allocator, ptr) {
778
var zeroinit, size;
779
if (typeof slab === 'number') {
780
zeroinit = true;
781
size = slab;
782
} else {
783
zeroinit = false;
784
size = slab.length;
785
}
786
787
var singleType = typeof types === 'string' ? types : null;
788
789
var ret;
790
if (allocator == ALLOC_NONE) {
791
ret = ptr;
792
} else {
793
ret = [_malloc,
794
stackAlloc,
795
dynamicAlloc][allocator](Math.max(size, singleType ? 1 : types.length));
796
}
797
798
if (zeroinit) {
799
var stop;
800
ptr = ret;
801
assert((ret & 3) == 0);
802
stop = ret + (size & ~3);
803
for (; ptr < stop; ptr += 4) {
804
HEAP32[((ptr)>>2)]=0;
805
}
806
stop = ret + size;
807
while (ptr < stop) {
808
HEAP8[((ptr++)>>0)]=0;
809
}
810
return ret;
811
}
812
813
if (singleType === 'i8') {
814
if (slab.subarray || slab.slice) {
815
HEAPU8.set(/** @type {!Uint8Array} */ (slab), ret);
816
} else {
817
HEAPU8.set(new Uint8Array(slab), ret);
818
}
819
return ret;
820
}
821
822
var i = 0, type, typeSize, previousType;
823
while (i < size) {
824
var curr = slab[i];
825
826
type = singleType || types[i];
827
if (type === 0) {
828
i++;
829
continue;
830
}
831
assert(type, 'Must know what type to store in allocate!');
832
833
if (type == 'i64') type = 'i32'; // special case: we have one i32 here, and one i32 later
834
835
setValue(ret+i, curr, type);
836
837
// no need to look up size unless type changes, so cache it
838
if (previousType !== type) {
839
typeSize = getNativeTypeSize(type);
840
previousType = type;
841
}
842
i += typeSize;
843
}
844
845
return ret;
846
}
847
848
// Allocate memory during any stage of startup - static memory early on, dynamic memory later, malloc when ready
849
function getMemory(size) {
850
if (!runtimeInitialized) return dynamicAlloc(size);
851
return _malloc(size);
852
}
853
854
855
// runtime_strings.js: Strings related runtime functions that are part of both MINIMAL_RUNTIME and regular runtime.
856
857
// Given a pointer 'ptr' to a null-terminated UTF8-encoded string in the given array that contains uint8 values, returns
858
// a copy of that string as a Javascript String object.
859
860
var UTF8Decoder = typeof TextDecoder !== 'undefined' ? new TextDecoder('utf8') : undefined;
861
862
/**
863
* @param {number} idx
864
* @param {number=} maxBytesToRead
865
* @return {string}
866
*/
867
function UTF8ArrayToString(u8Array, idx, maxBytesToRead) {
868
var endIdx = idx + maxBytesToRead;
869
var endPtr = idx;
870
// TextDecoder needs to know the byte length in advance, it doesn't stop on null terminator by itself.
871
// Also, use the length info to avoid running tiny strings through TextDecoder, since .subarray() allocates garbage.
872
// (As a tiny code save trick, compare endPtr against endIdx using a negation, so that undefined means Infinity)
873
while (u8Array[endPtr] && !(endPtr >= endIdx)) ++endPtr;
874
875
if (endPtr - idx > 16 && u8Array.subarray && UTF8Decoder) {
876
return UTF8Decoder.decode(u8Array.subarray(idx, endPtr));
877
} else {
878
var str = '';
879
// If building with TextDecoder, we have already computed the string length above, so test loop end condition against that
880
while (idx < endPtr) {
881
// For UTF8 byte structure, see:
882
// http://en.wikipedia.org/wiki/UTF-8#Description
883
// https://www.ietf.org/rfc/rfc2279.txt
884
// https://tools.ietf.org/html/rfc3629
885
var u0 = u8Array[idx++];
886
if (!(u0 & 0x80)) { str += String.fromCharCode(u0); continue; }
887
var u1 = u8Array[idx++] & 63;
888
if ((u0 & 0xE0) == 0xC0) { str += String.fromCharCode(((u0 & 31) << 6) | u1); continue; }
889
var u2 = u8Array[idx++] & 63;
890
if ((u0 & 0xF0) == 0xE0) {
891
u0 = ((u0 & 15) << 12) | (u1 << 6) | u2;
892
} else {
893
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!');
894
u0 = ((u0 & 7) << 18) | (u1 << 12) | (u2 << 6) | (u8Array[idx++] & 63);
895
}
896
897
if (u0 < 0x10000) {
898
str += String.fromCharCode(u0);
899
} else {
900
var ch = u0 - 0x10000;
901
str += String.fromCharCode(0xD800 | (ch >> 10), 0xDC00 | (ch & 0x3FF));
902
}
903
}
904
}
905
return str;
906
}
907
908
// Given a pointer 'ptr' to a null-terminated UTF8-encoded string in the emscripten HEAP, returns a
909
// copy of that string as a Javascript String object.
910
// maxBytesToRead: an optional length that specifies the maximum number of bytes to read. You can omit
911
// this parameter to scan the string until the first \0 byte. If maxBytesToRead is
912
// passed, and the string at [ptr, ptr+maxBytesToReadr[ contains a null byte in the
913
// middle, then the string will cut short at that byte index (i.e. maxBytesToRead will
914
// not produce a string of exact length [ptr, ptr+maxBytesToRead[)
915
// N.B. mixing frequent uses of UTF8ToString() with and without maxBytesToRead may
916
// throw JS JIT optimizations off, so it is worth to consider consistently using one
917
// style or the other.
918
/**
919
* @param {number} ptr
920
* @param {number=} maxBytesToRead
921
* @return {string}
922
*/
923
function UTF8ToString(ptr, maxBytesToRead) {
924
return ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead) : '';
925
}
926
927
// Copies the given Javascript String object 'str' to the given byte array at address 'outIdx',
928
// encoded in UTF8 form and null-terminated. The copy will require at most str.length*4+1 bytes of space in the HEAP.
929
// Use the function lengthBytesUTF8 to compute the exact number of bytes (excluding null terminator) that this function will write.
930
// Parameters:
931
// str: the Javascript string to copy.
932
// outU8Array: the array to copy to. Each index in this array is assumed to be one 8-byte element.
933
// outIdx: The starting offset in the array to begin the copying.
934
// maxBytesToWrite: The maximum number of bytes this function can write to the array.
935
// This count should include the null terminator,
936
// i.e. if maxBytesToWrite=1, only the null terminator will be written and nothing else.
937
// maxBytesToWrite=0 does not write any bytes to the output, not even the null terminator.
938
// Returns the number of bytes written, EXCLUDING the null terminator.
939
940
function stringToUTF8Array(str, outU8Array, outIdx, maxBytesToWrite) {
941
if (!(maxBytesToWrite > 0)) // Parameter maxBytesToWrite is not optional. Negative values, 0, null, undefined and false each don't write out any bytes.
942
return 0;
943
944
var startIdx = outIdx;
945
var endIdx = outIdx + maxBytesToWrite - 1; // -1 for string null terminator.
946
for (var i = 0; i < str.length; ++i) {
947
// 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.
948
// See http://unicode.org/faq/utf_bom.html#utf16-3
949
// 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
950
var u = str.charCodeAt(i); // possibly a lead surrogate
951
if (u >= 0xD800 && u <= 0xDFFF) {
952
var u1 = str.charCodeAt(++i);
953
u = 0x10000 + ((u & 0x3FF) << 10) | (u1 & 0x3FF);
954
}
955
if (u <= 0x7F) {
956
if (outIdx >= endIdx) break;
957
outU8Array[outIdx++] = u;
958
} else if (u <= 0x7FF) {
959
if (outIdx + 1 >= endIdx) break;
960
outU8Array[outIdx++] = 0xC0 | (u >> 6);
961
outU8Array[outIdx++] = 0x80 | (u & 63);
962
} else if (u <= 0xFFFF) {
963
if (outIdx + 2 >= endIdx) break;
964
outU8Array[outIdx++] = 0xE0 | (u >> 12);
965
outU8Array[outIdx++] = 0x80 | ((u >> 6) & 63);
966
outU8Array[outIdx++] = 0x80 | (u & 63);
967
} else {
968
if (outIdx + 3 >= endIdx) break;
969
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).');
970
outU8Array[outIdx++] = 0xF0 | (u >> 18);
971
outU8Array[outIdx++] = 0x80 | ((u >> 12) & 63);
972
outU8Array[outIdx++] = 0x80 | ((u >> 6) & 63);
973
outU8Array[outIdx++] = 0x80 | (u & 63);
974
}
975
}
976
// Null-terminate the pointer to the buffer.
977
outU8Array[outIdx] = 0;
978
return outIdx - startIdx;
979
}
980
981
// Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr',
982
// null-terminated and encoded in UTF8 form. The copy will require at most str.length*4+1 bytes of space in the HEAP.
983
// Use the function lengthBytesUTF8 to compute the exact number of bytes (excluding null terminator) that this function will write.
984
// Returns the number of bytes written, EXCLUDING the null terminator.
985
986
function stringToUTF8(str, outPtr, maxBytesToWrite) {
987
assert(typeof maxBytesToWrite == 'number', 'stringToUTF8(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!');
988
return stringToUTF8Array(str, HEAPU8,outPtr, maxBytesToWrite);
989
}
990
991
// Returns the number of bytes the given Javascript string takes if encoded as a UTF8 byte array, EXCLUDING the null terminator byte.
992
function lengthBytesUTF8(str) {
993
var len = 0;
994
for (var i = 0; i < str.length; ++i) {
995
// 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.
996
// See http://unicode.org/faq/utf_bom.html#utf16-3
997
var u = str.charCodeAt(i); // possibly a lead surrogate
998
if (u >= 0xD800 && u <= 0xDFFF) u = 0x10000 + ((u & 0x3FF) << 10) | (str.charCodeAt(++i) & 0x3FF);
999
if (u <= 0x7F) ++len;
1000
else if (u <= 0x7FF) len += 2;
1001
else if (u <= 0xFFFF) len += 3;
1002
else len += 4;
1003
}
1004
return len;
1005
}
1006
1007
1008
1009
// runtime_strings_extra.js: Strings related runtime functions that are available only in regular runtime.
1010
1011
// Given a pointer 'ptr' to a null-terminated ASCII-encoded string in the emscripten HEAP, returns
1012
// a copy of that string as a Javascript String object.
1013
1014
function AsciiToString(ptr) {
1015
var str = '';
1016
while (1) {
1017
var ch = HEAPU8[((ptr++)>>0)];
1018
if (!ch) return str;
1019
str += String.fromCharCode(ch);
1020
}
1021
}
1022
1023
// Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr',
1024
// null-terminated and encoded in ASCII form. The copy will require at most str.length+1 bytes of space in the HEAP.
1025
1026
function stringToAscii(str, outPtr) {
1027
return writeAsciiToMemory(str, outPtr, false);
1028
}
1029
1030
// Given a pointer 'ptr' to a null-terminated UTF16LE-encoded string in the emscripten HEAP, returns
1031
// a copy of that string as a Javascript String object.
1032
1033
var UTF16Decoder = typeof TextDecoder !== 'undefined' ? new TextDecoder('utf-16le') : undefined;
1034
1035
function UTF16ToString(ptr) {
1036
assert(ptr % 2 == 0, 'Pointer passed to UTF16ToString must be aligned to two bytes!');
1037
var endPtr = ptr;
1038
// TextDecoder needs to know the byte length in advance, it doesn't stop on null terminator by itself.
1039
// Also, use the length info to avoid running tiny strings through TextDecoder, since .subarray() allocates garbage.
1040
var idx = endPtr >> 1;
1041
while (HEAP16[idx]) ++idx;
1042
endPtr = idx << 1;
1043
1044
if (endPtr - ptr > 32 && UTF16Decoder) {
1045
return UTF16Decoder.decode(HEAPU8.subarray(ptr, endPtr));
1046
} else {
1047
var i = 0;
1048
1049
var str = '';
1050
while (1) {
1051
var codeUnit = HEAP16[(((ptr)+(i*2))>>1)];
1052
if (codeUnit == 0) return str;
1053
++i;
1054
// fromCharCode constructs a character from a UTF-16 code unit, so we can pass the UTF16 string right through.
1055
str += String.fromCharCode(codeUnit);
1056
}
1057
}
1058
}
1059
1060
// Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr',
1061
// null-terminated and encoded in UTF16 form. The copy will require at most str.length*4+2 bytes of space in the HEAP.
1062
// Use the function lengthBytesUTF16() to compute the exact number of bytes (excluding null terminator) that this function will write.
1063
// Parameters:
1064
// str: the Javascript string to copy.
1065
// outPtr: Byte address in Emscripten HEAP where to write the string to.
1066
// maxBytesToWrite: The maximum number of bytes this function can write to the array. This count should include the null
1067
// terminator, i.e. if maxBytesToWrite=2, only the null terminator will be written and nothing else.
1068
// maxBytesToWrite<2 does not write any bytes to the output, not even the null terminator.
1069
// Returns the number of bytes written, EXCLUDING the null terminator.
1070
1071
function stringToUTF16(str, outPtr, maxBytesToWrite) {
1072
assert(outPtr % 2 == 0, 'Pointer passed to stringToUTF16 must be aligned to two bytes!');
1073
assert(typeof maxBytesToWrite == 'number', 'stringToUTF16(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!');
1074
// Backwards compatibility: if max bytes is not specified, assume unsafe unbounded write is allowed.
1075
if (maxBytesToWrite === undefined) {
1076
maxBytesToWrite = 0x7FFFFFFF;
1077
}
1078
if (maxBytesToWrite < 2) return 0;
1079
maxBytesToWrite -= 2; // Null terminator.
1080
var startPtr = outPtr;
1081
var numCharsToWrite = (maxBytesToWrite < str.length*2) ? (maxBytesToWrite / 2) : str.length;
1082
for (var i = 0; i < numCharsToWrite; ++i) {
1083
// charCodeAt returns a UTF-16 encoded code unit, so it can be directly written to the HEAP.
1084
var codeUnit = str.charCodeAt(i); // possibly a lead surrogate
1085
HEAP16[((outPtr)>>1)]=codeUnit;
1086
outPtr += 2;
1087
}
1088
// Null-terminate the pointer to the HEAP.
1089
HEAP16[((outPtr)>>1)]=0;
1090
return outPtr - startPtr;
1091
}
1092
1093
// Returns the number of bytes the given Javascript string takes if encoded as a UTF16 byte array, EXCLUDING the null terminator byte.
1094
1095
function lengthBytesUTF16(str) {
1096
return str.length*2;
1097
}
1098
1099
function UTF32ToString(ptr) {
1100
assert(ptr % 4 == 0, 'Pointer passed to UTF32ToString must be aligned to four bytes!');
1101
var i = 0;
1102
1103
var str = '';
1104
while (1) {
1105
var utf32 = HEAP32[(((ptr)+(i*4))>>2)];
1106
if (utf32 == 0)
1107
return str;
1108
++i;
1109
// 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.
1110
// See http://unicode.org/faq/utf_bom.html#utf16-3
1111
if (utf32 >= 0x10000) {
1112
var ch = utf32 - 0x10000;
1113
str += String.fromCharCode(0xD800 | (ch >> 10), 0xDC00 | (ch & 0x3FF));
1114
} else {
1115
str += String.fromCharCode(utf32);
1116
}
1117
}
1118
}
1119
1120
// Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr',
1121
// null-terminated and encoded in UTF32 form. The copy will require at most str.length*4+4 bytes of space in the HEAP.
1122
// Use the function lengthBytesUTF32() to compute the exact number of bytes (excluding null terminator) that this function will write.
1123
// Parameters:
1124
// str: the Javascript string to copy.
1125
// outPtr: Byte address in Emscripten HEAP where to write the string to.
1126
// maxBytesToWrite: The maximum number of bytes this function can write to the array. This count should include the null
1127
// terminator, i.e. if maxBytesToWrite=4, only the null terminator will be written and nothing else.
1128
// maxBytesToWrite<4 does not write any bytes to the output, not even the null terminator.
1129
// Returns the number of bytes written, EXCLUDING the null terminator.
1130
1131
function stringToUTF32(str, outPtr, maxBytesToWrite) {
1132
assert(outPtr % 4 == 0, 'Pointer passed to stringToUTF32 must be aligned to four bytes!');
1133
assert(typeof maxBytesToWrite == 'number', 'stringToUTF32(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!');
1134
// Backwards compatibility: if max bytes is not specified, assume unsafe unbounded write is allowed.
1135
if (maxBytesToWrite === undefined) {
1136
maxBytesToWrite = 0x7FFFFFFF;
1137
}
1138
if (maxBytesToWrite < 4) return 0;
1139
var startPtr = outPtr;
1140
var endPtr = startPtr + maxBytesToWrite - 4;
1141
for (var i = 0; i < str.length; ++i) {
1142
// 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.
1143
// See http://unicode.org/faq/utf_bom.html#utf16-3
1144
var codeUnit = str.charCodeAt(i); // possibly a lead surrogate
1145
if (codeUnit >= 0xD800 && codeUnit <= 0xDFFF) {
1146
var trailSurrogate = str.charCodeAt(++i);
1147
codeUnit = 0x10000 + ((codeUnit & 0x3FF) << 10) | (trailSurrogate & 0x3FF);
1148
}
1149
HEAP32[((outPtr)>>2)]=codeUnit;
1150
outPtr += 4;
1151
if (outPtr + 4 > endPtr) break;
1152
}
1153
// Null-terminate the pointer to the HEAP.
1154
HEAP32[((outPtr)>>2)]=0;
1155
return outPtr - startPtr;
1156
}
1157
1158
// Returns the number of bytes the given Javascript string takes if encoded as a UTF16 byte array, EXCLUDING the null terminator byte.
1159
1160
function lengthBytesUTF32(str) {
1161
var len = 0;
1162
for (var i = 0; i < str.length; ++i) {
1163
// 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.
1164
// See http://unicode.org/faq/utf_bom.html#utf16-3
1165
var codeUnit = str.charCodeAt(i);
1166
if (codeUnit >= 0xD800 && codeUnit <= 0xDFFF) ++i; // possibly a lead surrogate, so skip over the tail surrogate.
1167
len += 4;
1168
}
1169
1170
return len;
1171
}
1172
1173
// Allocate heap space for a JS string, and write it there.
1174
// It is the responsibility of the caller to free() that memory.
1175
function allocateUTF8(str) {
1176
var size = lengthBytesUTF8(str) + 1;
1177
var ret = _malloc(size);
1178
if (ret) stringToUTF8Array(str, HEAP8, ret, size);
1179
return ret;
1180
}
1181
1182
// Allocate stack space for a JS string, and write it there.
1183
function allocateUTF8OnStack(str) {
1184
var size = lengthBytesUTF8(str) + 1;
1185
var ret = stackAlloc(size);
1186
stringToUTF8Array(str, HEAP8, ret, size);
1187
return ret;
1188
}
1189
1190
// Deprecated: This function should not be called because it is unsafe and does not provide
1191
// a maximum length limit of how many bytes it is allowed to write. Prefer calling the
1192
// function stringToUTF8Array() instead, which takes in a maximum length that can be used
1193
// to be secure from out of bounds writes.
1194
/** @deprecated
1195
@param {boolean=} dontAddNull */
1196
function writeStringToMemory(string, buffer, dontAddNull) {
1197
warnOnce('writeStringToMemory is deprecated and should not be called! Use stringToUTF8() instead!');
1198
1199
var /** @type {number} */ lastChar, /** @type {number} */ end;
1200
if (dontAddNull) {
1201
// stringToUTF8Array always appends null. If we don't want to do that, remember the
1202
// character that existed at the location where the null will be placed, and restore
1203
// that after the write (below).
1204
end = buffer + lengthBytesUTF8(string);
1205
lastChar = HEAP8[end];
1206
}
1207
stringToUTF8(string, buffer, Infinity);
1208
if (dontAddNull) HEAP8[end] = lastChar; // Restore the value under the null character.
1209
}
1210
1211
function writeArrayToMemory(array, buffer) {
1212
assert(array.length >= 0, 'writeArrayToMemory array must have a length (should be an array or typed array)')
1213
HEAP8.set(array, buffer);
1214
}
1215
1216
/** @param {boolean=} dontAddNull */
1217
function writeAsciiToMemory(str, buffer, dontAddNull) {
1218
for (var i = 0; i < str.length; ++i) {
1219
assert(str.charCodeAt(i) === str.charCodeAt(i)&0xff);
1220
HEAP8[((buffer++)>>0)]=str.charCodeAt(i);
1221
}
1222
// Null-terminate the pointer to the HEAP.
1223
if (!dontAddNull) HEAP8[((buffer)>>0)]=0;
1224
}
1225
1226
1227
1228
// Memory management
1229
1230
var PAGE_SIZE = 16384;
1231
var WASM_PAGE_SIZE = 65536;
1232
var ASMJS_PAGE_SIZE = 16777216;
1233
1234
function alignUp(x, multiple) {
1235
if (x % multiple > 0) {
1236
x += multiple - (x % multiple);
1237
}
1238
return x;
1239
}
1240
1241
var HEAP,
1242
/** @type {ArrayBuffer} */
1243
buffer,
1244
/** @type {Int8Array} */
1245
HEAP8,
1246
/** @type {Uint8Array} */
1247
HEAPU8,
1248
/** @type {Int16Array} */
1249
HEAP16,
1250
/** @type {Uint16Array} */
1251
HEAPU16,
1252
/** @type {Int32Array} */
1253
HEAP32,
1254
/** @type {Uint32Array} */
1255
HEAPU32,
1256
/** @type {Float32Array} */
1257
HEAPF32,
1258
/** @type {Float64Array} */
1259
HEAPF64;
1260
1261
function updateGlobalBufferAndViews(buf) {
1262
buffer = buf;
1263
Module['HEAP8'] = HEAP8 = new Int8Array(buf);
1264
Module['HEAP16'] = HEAP16 = new Int16Array(buf);
1265
Module['HEAP32'] = HEAP32 = new Int32Array(buf);
1266
Module['HEAPU8'] = HEAPU8 = new Uint8Array(buf);
1267
Module['HEAPU16'] = HEAPU16 = new Uint16Array(buf);
1268
Module['HEAPU32'] = HEAPU32 = new Uint32Array(buf);
1269
Module['HEAPF32'] = HEAPF32 = new Float32Array(buf);
1270
Module['HEAPF64'] = HEAPF64 = new Float64Array(buf);
1271
}
1272
1273
var STATIC_BASE = 1024,
1274
STACK_BASE = 19593120,
1275
STACKTOP = STACK_BASE,
1276
STACK_MAX = 14350240,
1277
DYNAMIC_BASE = 19593120,
1278
DYNAMICTOP_PTR = 14350080;
1279
1280
assert(STACK_BASE % 16 === 0, 'stack must start aligned');
1281
assert(DYNAMIC_BASE % 16 === 0, 'heap must start aligned');
1282
1283
1284
1285
var TOTAL_STACK = 5242880;
1286
if (Module['TOTAL_STACK']) assert(TOTAL_STACK === Module['TOTAL_STACK'], 'the stack size can no longer be determined at runtime')
1287
1288
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') } });
1289
1290
assert(INITIAL_INITIAL_MEMORY >= TOTAL_STACK, 'INITIAL_MEMORY should be larger than TOTAL_STACK, was ' + INITIAL_INITIAL_MEMORY + '! (TOTAL_STACK=' + TOTAL_STACK + ')');
1291
1292
// check for full engine support (use string 'subarray' to avoid closure compiler confusion)
1293
assert(typeof Int32Array !== 'undefined' && typeof Float64Array !== 'undefined' && Int32Array.prototype.subarray !== undefined && Int32Array.prototype.set !== undefined,
1294
'JS engine does not provide full typed array support');
1295
1296
1297
1298
1299
1300
1301
// In standalone mode, the wasm creates the memory, and the user can't provide it.
1302
// In non-standalone/normal mode, we create the memory here.
1303
1304
// Create the main memory. (Note: this isn't used in STANDALONE_WASM mode since the wasm
1305
// memory is created in the wasm, not in JS.)
1306
1307
if (Module['wasmMemory']) {
1308
wasmMemory = Module['wasmMemory'];
1309
} else
1310
{
1311
wasmMemory = new WebAssembly.Memory({
1312
'initial': INITIAL_INITIAL_MEMORY / WASM_PAGE_SIZE
1313
,
1314
'maximum': INITIAL_INITIAL_MEMORY / WASM_PAGE_SIZE
1315
});
1316
}
1317
1318
1319
if (wasmMemory) {
1320
buffer = wasmMemory.buffer;
1321
}
1322
1323
// If the user provides an incorrect length, just use that length instead rather than providing the user to
1324
// specifically provide the memory length with Module['INITIAL_MEMORY'].
1325
INITIAL_INITIAL_MEMORY = buffer.byteLength;
1326
assert(INITIAL_INITIAL_MEMORY % WASM_PAGE_SIZE === 0);
1327
updateGlobalBufferAndViews(buffer);
1328
1329
HEAP32[DYNAMICTOP_PTR>>2] = DYNAMIC_BASE;
1330
1331
1332
1333
1334
// Initializes the stack cookie. Called at the startup of main and at the startup of each thread in pthreads mode.
1335
function writeStackCookie() {
1336
assert((STACK_MAX & 3) == 0);
1337
// The stack grows downwards
1338
HEAPU32[(STACK_MAX >> 2)+1] = 0x2135467;
1339
HEAPU32[(STACK_MAX >> 2)+2] = 0x89BACDFE;
1340
// Also test the global address 0 for integrity.
1341
// We don't do this with ASan because ASan does its own checks for this.
1342
HEAP32[0] = 0x63736d65; /* 'emsc' */
1343
}
1344
1345
function checkStackCookie() {
1346
var cookie1 = HEAPU32[(STACK_MAX >> 2)+1];
1347
var cookie2 = HEAPU32[(STACK_MAX >> 2)+2];
1348
if (cookie1 != 0x2135467 || cookie2 != 0x89BACDFE) {
1349
abort('Stack overflow! Stack cookie has been overwritten, expected hex dwords 0x89BACDFE and 0x2135467, but received 0x' + cookie2.toString(16) + ' ' + cookie1.toString(16));
1350
}
1351
// Also test the global address 0 for integrity.
1352
// We don't do this with ASan because ASan does its own checks for this.
1353
if (HEAP32[0] !== 0x63736d65 /* 'emsc' */) abort('Runtime error: The application has corrupted its heap memory area (address zero)!');
1354
}
1355
1356
function abortStackOverflow(allocSize) {
1357
abort('Stack overflow! Attempted to allocate ' + allocSize + ' bytes on the stack, but stack has only ' + (STACK_MAX - stackSave() + allocSize) + ' bytes available!');
1358
}
1359
1360
1361
1362
1363
// Endianness check (note: assumes compiler arch was little-endian)
1364
(function() {
1365
var h16 = new Int16Array(1);
1366
var h8 = new Int8Array(h16.buffer);
1367
h16[0] = 0x6373;
1368
if (h8[0] !== 0x73 || h8[1] !== 0x63) throw 'Runtime error: expected the system to be little-endian!';
1369
})();
1370
1371
function abortFnPtrError(ptr, sig) {
1372
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.");
1373
}
1374
1375
1376
1377
function callRuntimeCallbacks(callbacks) {
1378
while(callbacks.length > 0) {
1379
var callback = callbacks.shift();
1380
if (typeof callback == 'function') {
1381
callback();
1382
continue;
1383
}
1384
var func = callback.func;
1385
if (typeof func === 'number') {
1386
if (callback.arg === undefined) {
1387
Module['dynCall_v'](func);
1388
} else {
1389
Module['dynCall_vi'](func, callback.arg);
1390
}
1391
} else {
1392
func(callback.arg === undefined ? null : callback.arg);
1393
}
1394
}
1395
}
1396
1397
var __ATPRERUN__ = []; // functions called before the runtime is initialized
1398
var __ATINIT__ = []; // functions called during startup
1399
var __ATMAIN__ = []; // functions called when main() is to be run
1400
var __ATEXIT__ = []; // functions called during shutdown
1401
var __ATPOSTRUN__ = []; // functions called after the main() is called
1402
1403
var runtimeInitialized = false;
1404
var runtimeExited = false;
1405
1406
1407
function preRun() {
1408
1409
if (Module['preRun']) {
1410
if (typeof Module['preRun'] == 'function') Module['preRun'] = [Module['preRun']];
1411
while (Module['preRun'].length) {
1412
addOnPreRun(Module['preRun'].shift());
1413
}
1414
}
1415
1416
callRuntimeCallbacks(__ATPRERUN__);
1417
}
1418
1419
function initRuntime() {
1420
checkStackCookie();
1421
assert(!runtimeInitialized);
1422
runtimeInitialized = true;
1423
if (!Module["noFSInit"] && !FS.init.initialized) FS.init();
1424
TTY.init();
1425
callRuntimeCallbacks(__ATINIT__);
1426
}
1427
1428
function preMain() {
1429
checkStackCookie();
1430
FS.ignorePermissions = false;
1431
callRuntimeCallbacks(__ATMAIN__);
1432
}
1433
1434
function exitRuntime() {
1435
checkStackCookie();
1436
runtimeExited = true;
1437
}
1438
1439
function postRun() {
1440
checkStackCookie();
1441
1442
if (Module['postRun']) {
1443
if (typeof Module['postRun'] == 'function') Module['postRun'] = [Module['postRun']];
1444
while (Module['postRun'].length) {
1445
addOnPostRun(Module['postRun'].shift());
1446
}
1447
}
1448
1449
callRuntimeCallbacks(__ATPOSTRUN__);
1450
}
1451
1452
function addOnPreRun(cb) {
1453
__ATPRERUN__.unshift(cb);
1454
}
1455
1456
function addOnInit(cb) {
1457
__ATINIT__.unshift(cb);
1458
}
1459
1460
function addOnPreMain(cb) {
1461
__ATMAIN__.unshift(cb);
1462
}
1463
1464
function addOnExit(cb) {
1465
}
1466
1467
function addOnPostRun(cb) {
1468
__ATPOSTRUN__.unshift(cb);
1469
}
1470
1471
/** @param {number|boolean=} ignore */
1472
function unSign(value, bits, ignore) {
1473
if (value >= 0) {
1474
return value;
1475
}
1476
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
1477
: Math.pow(2, bits) + value;
1478
}
1479
/** @param {number|boolean=} ignore */
1480
function reSign(value, bits, ignore) {
1481
if (value <= 0) {
1482
return value;
1483
}
1484
var half = bits <= 32 ? Math.abs(1 << (bits-1)) // abs is needed if bits == 32
1485
: Math.pow(2, bits-1);
1486
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
1487
// but, in general there is no perfect solution here. With 64-bit ints, we get rounding and errors
1488
// TODO: In i64 mode 1, resign the two parts separately and safely
1489
value = -2*half + value; // Cannot bitshift half, as it may be at the limit of the bits JS uses in bitshifts
1490
}
1491
return value;
1492
}
1493
1494
1495
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/imul
1496
1497
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/fround
1498
1499
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32
1500
1501
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc
1502
1503
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');
1504
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');
1505
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');
1506
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');
1507
1508
var Math_abs = Math.abs;
1509
var Math_cos = Math.cos;
1510
var Math_sin = Math.sin;
1511
var Math_tan = Math.tan;
1512
var Math_acos = Math.acos;
1513
var Math_asin = Math.asin;
1514
var Math_atan = Math.atan;
1515
var Math_atan2 = Math.atan2;
1516
var Math_exp = Math.exp;
1517
var Math_log = Math.log;
1518
var Math_sqrt = Math.sqrt;
1519
var Math_ceil = Math.ceil;
1520
var Math_floor = Math.floor;
1521
var Math_pow = Math.pow;
1522
var Math_imul = Math.imul;
1523
var Math_fround = Math.fround;
1524
var Math_round = Math.round;
1525
var Math_min = Math.min;
1526
var Math_max = Math.max;
1527
var Math_clz32 = Math.clz32;
1528
var Math_trunc = Math.trunc;
1529
1530
1531
1532
// A counter of dependencies for calling run(). If we need to
1533
// do asynchronous work before running, increment this and
1534
// decrement it. Incrementing must happen in a place like
1535
// Module.preRun (used by emcc to add file preloading).
1536
// Note that you can add dependencies in preRun, even though
1537
// it happens right before run - run will be postponed until
1538
// the dependencies are met.
1539
var runDependencies = 0;
1540
var runDependencyWatcher = null;
1541
var dependenciesFulfilled = null; // overridden to take different actions when all run dependencies are fulfilled
1542
var runDependencyTracking = {};
1543
1544
function getUniqueRunDependency(id) {
1545
var orig = id;
1546
while (1) {
1547
if (!runDependencyTracking[id]) return id;
1548
id = orig + Math.random();
1549
}
1550
}
1551
1552
function addRunDependency(id) {
1553
runDependencies++;
1554
1555
if (Module['monitorRunDependencies']) {
1556
Module['monitorRunDependencies'](runDependencies);
1557
}
1558
1559
if (id) {
1560
assert(!runDependencyTracking[id]);
1561
runDependencyTracking[id] = 1;
1562
if (runDependencyWatcher === null && typeof setInterval !== 'undefined') {
1563
// Check for missing dependencies every few seconds
1564
runDependencyWatcher = setInterval(function() {
1565
if (ABORT) {
1566
clearInterval(runDependencyWatcher);
1567
runDependencyWatcher = null;
1568
return;
1569
}
1570
var shown = false;
1571
for (var dep in runDependencyTracking) {
1572
if (!shown) {
1573
shown = true;
1574
err('still waiting on run dependencies:');
1575
}
1576
err('dependency: ' + dep);
1577
}
1578
if (shown) {
1579
err('(end of list)');
1580
}
1581
}, 10000);
1582
}
1583
} else {
1584
err('warning: run dependency added without ID');
1585
}
1586
}
1587
1588
function removeRunDependency(id) {
1589
runDependencies--;
1590
1591
if (Module['monitorRunDependencies']) {
1592
Module['monitorRunDependencies'](runDependencies);
1593
}
1594
1595
if (id) {
1596
assert(runDependencyTracking[id]);
1597
delete runDependencyTracking[id];
1598
} else {
1599
err('warning: run dependency removed without ID');
1600
}
1601
if (runDependencies == 0) {
1602
if (runDependencyWatcher !== null) {
1603
clearInterval(runDependencyWatcher);
1604
runDependencyWatcher = null;
1605
}
1606
if (dependenciesFulfilled) {
1607
var callback = dependenciesFulfilled;
1608
dependenciesFulfilled = null;
1609
callback(); // can add another dependenciesFulfilled
1610
}
1611
}
1612
}
1613
1614
Module["preloadedImages"] = {}; // maps url to image data
1615
Module["preloadedAudios"] = {}; // maps url to audio data
1616
1617
1618
/** @param {string|number=} what */
1619
function abort(what) {
1620
if (Module['onAbort']) {
1621
Module['onAbort'](what);
1622
}
1623
1624
what += '';
1625
out(what);
1626
err(what);
1627
1628
ABORT = true;
1629
EXITSTATUS = 1;
1630
1631
var output = 'abort(' + what + ') at ' + stackTrace();
1632
what = output;
1633
1634
// Throw a wasm runtime error, because a JS error might be seen as a foreign
1635
// exception, which means we'd run destructors on it. We need the error to
1636
// simply make the program stop.
1637
throw new WebAssembly.RuntimeError(what);
1638
}
1639
1640
1641
var memoryInitializer = null;
1642
1643
1644
1645
1646
1647
1648
1649
1650
// Copyright 2017 The Emscripten Authors. All rights reserved.
1651
// Emscripten is available under two separate licenses, the MIT license and the
1652
// University of Illinois/NCSA Open Source License. Both these licenses can be
1653
// found in the LICENSE file.
1654
1655
// Prefix of data URIs emitted by SINGLE_FILE and related options.
1656
var dataURIPrefix = 'data:application/octet-stream;base64,';
1657
1658
// Indicates whether filename is a base64 data URI.
1659
function isDataURI(filename) {
1660
return String.prototype.startsWith ?
1661
filename.startsWith(dataURIPrefix) :
1662
filename.indexOf(dataURIPrefix) === 0;
1663
}
1664
1665
1666
1667
1668
var wasmBinaryFile = 'sm64.us.f3dex2e.wasm';
1669
if (!isDataURI(wasmBinaryFile)) {
1670
wasmBinaryFile = locateFile(wasmBinaryFile);
1671
}
1672
1673
function getBinary() {
1674
try {
1675
if (wasmBinary) {
1676
return new Uint8Array(wasmBinary);
1677
}
1678
1679
if (readBinary) {
1680
return readBinary(wasmBinaryFile);
1681
} else {
1682
throw "both async and sync fetching of the wasm failed";
1683
}
1684
}
1685
catch (err) {
1686
abort(err);
1687
}
1688
}
1689
1690
function getBinaryPromise() {
1691
// if we don't have the binary yet, and have the Fetch api, use that
1692
// 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
1693
if (!wasmBinary && (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) && typeof fetch === 'function') {
1694
return fetch(wasmBinaryFile, { credentials: 'same-origin' }).then(function(response) {
1695
if (!response['ok']) {
1696
throw "failed to load wasm binary file at '" + wasmBinaryFile + "'";
1697
}
1698
return response['arrayBuffer']();
1699
}).catch(function () {
1700
return getBinary();
1701
});
1702
}
1703
// Otherwise, getBinary should be able to get it synchronously
1704
return new Promise(function(resolve, reject) {
1705
resolve(getBinary());
1706
});
1707
}
1708
1709
1710
1711
// Create the wasm instance.
1712
// Receives the wasm imports, returns the exports.
1713
function createWasm() {
1714
// prepare imports
1715
var info = {
1716
'env': asmLibraryArg,
1717
'wasi_snapshot_preview1': asmLibraryArg
1718
};
1719
// Load the wasm module and create an instance of using native support in the JS engine.
1720
// handle a generated wasm instance, receiving its exports and
1721
// performing other necessary setup
1722
/** @param {WebAssembly.Module=} module*/
1723
function receiveInstance(instance, module) {
1724
var exports = instance.exports;
1725
Module['asm'] = exports;
1726
removeRunDependency('wasm-instantiate');
1727
}
1728
// we can't run yet (except in a pthread, where we have a custom sync instantiator)
1729
addRunDependency('wasm-instantiate');
1730
1731
1732
// Async compilation can be confusing when an error on the page overwrites Module
1733
// (for example, if the order of elements is wrong, and the one defining Module is
1734
// later), so we save Module and check it later.
1735
var trueModule = Module;
1736
function receiveInstantiatedSource(output) {
1737
// 'output' is a WebAssemblyInstantiatedSource object which has both the module and instance.
1738
// receiveInstance() will swap in the exports (to Module.asm) so they can be called
1739
assert(Module === trueModule, 'the Module object should not be replaced during async compilation - perhaps the order of HTML elements is wrong?');
1740
trueModule = null;
1741
// 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.
1742
// When the regression is fixed, can restore the above USE_PTHREADS-enabled path.
1743
receiveInstance(output['instance']);
1744
}
1745
1746
1747
function instantiateArrayBuffer(receiver) {
1748
return getBinaryPromise().then(function(binary) {
1749
return WebAssembly.instantiate(binary, info);
1750
}).then(receiver, function(reason) {
1751
err('failed to asynchronously prepare wasm: ' + reason);
1752
abort(reason);
1753
});
1754
}
1755
1756
// Prefer streaming instantiation if available.
1757
function instantiateAsync() {
1758
if (!wasmBinary &&
1759
typeof WebAssembly.instantiateStreaming === 'function' &&
1760
!isDataURI(wasmBinaryFile) &&
1761
typeof fetch === 'function') {
1762
fetch(wasmBinaryFile, { credentials: 'same-origin' }).then(function (response) {
1763
var result = WebAssembly.instantiateStreaming(response, info);
1764
return result.then(receiveInstantiatedSource, function(reason) {
1765
// We expect the most common failure cause to be a bad MIME type for the binary,
1766
// in which case falling back to ArrayBuffer instantiation should work.
1767
err('wasm streaming compile failed: ' + reason);
1768
err('falling back to ArrayBuffer instantiation');
1769
instantiateArrayBuffer(receiveInstantiatedSource);
1770
});
1771
});
1772
} else {
1773
return instantiateArrayBuffer(receiveInstantiatedSource);
1774
}
1775
}
1776
// User shell pages can write their own Module.instantiateWasm = function(imports, successCallback) callback
1777
// to manually instantiate the Wasm module themselves. This allows pages to run the instantiation parallel
1778
// to any other async startup actions they are performing.
1779
if (Module['instantiateWasm']) {
1780
try {
1781
var exports = Module['instantiateWasm'](info, receiveInstance);
1782
return exports;
1783
} catch(e) {
1784
err('Module.instantiateWasm callback failed with error: ' + e);
1785
return false;
1786
}
1787
}
1788
1789
instantiateAsync();
1790
return {}; // no exports yet; we'll fill them in later
1791
}
1792
1793
1794
// Globals used by JS i64 conversions
1795
var tempDouble;
1796
var tempI64;
1797
1798
// === Body ===
1799
1800
var ASM_CONSTS = {
1801
3069901: function($0) {requestAnimationFrame(function(time) { dynCall("vd", $0, [time]); })},
1802
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;},
1803
3070210: function($0) {var str = ""; for (var i = 0; i < 512; i++) { str += String.fromCharCode(HEAPU8[$0 + i]); } localStorage.sm64_save_file = btoa(str);},
1804
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;},
1805
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;},
1806
8777696: function($0) {if (Module['canvas']) { Module['canvas'].style['cursor'] = UTF8ToString($0); } return 0;},
1807
8777789: function() {if (Module['canvas']) { Module['canvas'].style['cursor'] = 'none'; }},
1808
8779014: function() {return screen.width;},
1809
8779041: function() {return screen.height;},
1810
8779069: function() {return window.innerWidth;},
1811
8779101: function() {return window.innerHeight;},
1812
8779179: function($0) {if (typeof Module['setWindowTitle'] !== 'undefined') { Module['setWindowTitle'](UTF8ToString($0)); } return 0;},
1813
8779333: function() {if (typeof(AudioContext) !== 'undefined') { return 1; } else if (typeof(webkitAudioContext) !== 'undefined') { return 1; } return 0;},
1814
8779499: function() {if ((typeof(navigator.mediaDevices) !== 'undefined') && (typeof(navigator.mediaDevices.getUserMedia) !== 'undefined')) { return 1; } else if (typeof(navigator.webkitGetUserMedia) !== 'undefined') { return 1; } return 0;},
1815
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;},
1816
8780208: function() {var SDL2 = Module['SDL2']; return SDL2.audioContext.sampleRate;},
1817
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); }},
1818
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']);},
1819
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'); } } }},
1820
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]; } }},
1821
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; }}
1822
};
1823
1824
function _emscripten_asm_const_iii(code, sigPtr, argbuf) {
1825
var args = readAsmConstArgs(sigPtr, argbuf);
1826
return ASM_CONSTS[code].apply(null, args);
1827
}
1828
1829
1830
1831
// STATICTOP = STATIC_BASE + 14349216;
1832
/* global initializers */ __ATINIT__.push({ func: function() { ___wasm_call_ctors() } });
1833
1834
1835
1836
1837
/* no memory initializer */
1838
// {{PRE_LIBRARY}}
1839
1840
1841
function demangle(func) {
1842
warnOnce('warning: build with -s DEMANGLE_SUPPORT=1 to link in libcxxabi demangling');
1843
return func;
1844
}
1845
1846
function demangleAll(text) {
1847
var regex =
1848
/\b_Z[\w\d_]+/g;
1849
return text.replace(regex,
1850
function(x) {
1851
var y = demangle(x);
1852
return x === y ? x : (y + ' [' + x + ']');
1853
});
1854
}
1855
1856
function jsStackTrace() {
1857
var err = new Error();
1858
if (!err.stack) {
1859
// IE10+ special cases: It does have callstack info, but it is only populated if an Error object is thrown,
1860
// so try that as a special-case.
1861
try {
1862
throw new Error();
1863
} catch(e) {
1864
err = e;
1865
}
1866
if (!err.stack) {
1867
return '(no stack trace available)';
1868
}
1869
}
1870
return err.stack.toString();
1871
}
1872
1873
function stackTrace() {
1874
var js = jsStackTrace();
1875
if (Module['extraStackTrace']) js += '\n' + Module['extraStackTrace']();
1876
return demangleAll(js);
1877
}
1878
1879
function ___assert_fail(condition, filename, line, func) {
1880
abort('Assertion failed: ' + UTF8ToString(condition) + ', at: ' + [filename ? UTF8ToString(filename) : 'unknown filename', line, func ? UTF8ToString(func) : 'unknown function']);
1881
}
1882
1883
function ___handle_stack_overflow() {
1884
abort('stack overflow')
1885
}
1886
1887
1888
function ___setErrNo(value) {
1889
if (Module['___errno_location']) HEAP32[((Module['___errno_location']())>>2)]=value;
1890
else err('failed to set errno from JS');
1891
return value;
1892
}
1893
1894
1895
var PATH={splitPath:function(filename) {
1896
var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
1897
return splitPathRe.exec(filename).slice(1);
1898
},normalizeArray:function(parts, allowAboveRoot) {
1899
// if the path tries to go above the root, `up` ends up > 0
1900
var up = 0;
1901
for (var i = parts.length - 1; i >= 0; i--) {
1902
var last = parts[i];
1903
if (last === '.') {
1904
parts.splice(i, 1);
1905
} else if (last === '..') {
1906
parts.splice(i, 1);
1907
up++;
1908
} else if (up) {
1909
parts.splice(i, 1);
1910
up--;
1911
}
1912
}
1913
// if the path is allowed to go above the root, restore leading ..s
1914
if (allowAboveRoot) {
1915
for (; up; up--) {
1916
parts.unshift('..');
1917
}
1918
}
1919
return parts;
1920
},normalize:function(path) {
1921
var isAbsolute = path.charAt(0) === '/',
1922
trailingSlash = path.substr(-1) === '/';
1923
// Normalize the path
1924
path = PATH.normalizeArray(path.split('/').filter(function(p) {
1925
return !!p;
1926
}), !isAbsolute).join('/');
1927
if (!path && !isAbsolute) {
1928
path = '.';
1929
}
1930
if (path && trailingSlash) {
1931
path += '/';
1932
}
1933
return (isAbsolute ? '/' : '') + path;
1934
},dirname:function(path) {
1935
var result = PATH.splitPath(path),
1936
root = result[0],
1937
dir = result[1];
1938
if (!root && !dir) {
1939
// No dirname whatsoever
1940
return '.';
1941
}
1942
if (dir) {
1943
// It has a dirname, strip trailing slash
1944
dir = dir.substr(0, dir.length - 1);
1945
}
1946
return root + dir;
1947
},basename:function(path) {
1948
// EMSCRIPTEN return '/'' for '/', not an empty string
1949
if (path === '/') return '/';
1950
var lastSlash = path.lastIndexOf('/');
1951
if (lastSlash === -1) return path;
1952
return path.substr(lastSlash+1);
1953
},extname:function(path) {
1954
return PATH.splitPath(path)[3];
1955
},join:function() {
1956
var paths = Array.prototype.slice.call(arguments, 0);
1957
return PATH.normalize(paths.join('/'));
1958
},join2:function(l, r) {
1959
return PATH.normalize(l + '/' + r);
1960
}};
1961
1962
1963
var PATH_FS={resolve:function() {
1964
var resolvedPath = '',
1965
resolvedAbsolute = false;
1966
for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
1967
var path = (i >= 0) ? arguments[i] : FS.cwd();
1968
// Skip empty and invalid entries
1969
if (typeof path !== 'string') {
1970
throw new TypeError('Arguments to path.resolve must be strings');
1971
} else if (!path) {
1972
return ''; // an invalid portion invalidates the whole thing
1973
}
1974
resolvedPath = path + '/' + resolvedPath;
1975
resolvedAbsolute = path.charAt(0) === '/';
1976
}
1977
// At this point the path should be resolved to a full absolute path, but
1978
// handle relative paths to be safe (might happen when process.cwd() fails)
1979
resolvedPath = PATH.normalizeArray(resolvedPath.split('/').filter(function(p) {
1980
return !!p;
1981
}), !resolvedAbsolute).join('/');
1982
return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
1983
},relative:function(from, to) {
1984
from = PATH_FS.resolve(from).substr(1);
1985
to = PATH_FS.resolve(to).substr(1);
1986
function trim(arr) {
1987
var start = 0;
1988
for (; start < arr.length; start++) {
1989
if (arr[start] !== '') break;
1990
}
1991
var end = arr.length - 1;
1992
for (; end >= 0; end--) {
1993
if (arr[end] !== '') break;
1994
}
1995
if (start > end) return [];
1996
return arr.slice(start, end - start + 1);
1997
}
1998
var fromParts = trim(from.split('/'));
1999
var toParts = trim(to.split('/'));
2000
var length = Math.min(fromParts.length, toParts.length);
2001
var samePartsLength = length;
2002
for (var i = 0; i < length; i++) {
2003
if (fromParts[i] !== toParts[i]) {
2004
samePartsLength = i;
2005
break;
2006
}
2007
}
2008
var outputParts = [];
2009
for (var i = samePartsLength; i < fromParts.length; i++) {
2010
outputParts.push('..');
2011
}
2012
outputParts = outputParts.concat(toParts.slice(samePartsLength));
2013
return outputParts.join('/');
2014
}};
2015
2016
var TTY={ttys:[],init:function () {
2017
// https://github.com/emscripten-core/emscripten/pull/1555
2018
// if (ENVIRONMENT_IS_NODE) {
2019
// // currently, FS.init does not distinguish if process.stdin is a file or TTY
2020
// // device, it always assumes it's a TTY device. because of this, we're forcing
2021
// // process.stdin to UTF8 encoding to at least make stdin reading compatible
2022
// // with text files until FS.init can be refactored.
2023
// process['stdin']['setEncoding']('utf8');
2024
// }
2025
},shutdown:function() {
2026
// https://github.com/emscripten-core/emscripten/pull/1555
2027
// if (ENVIRONMENT_IS_NODE) {
2028
// // inolen: any idea as to why node -e 'process.stdin.read()' wouldn't exit immediately (with process.stdin being a tty)?
2029
// // 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
2030
// // inolen: I thought read() in that case was a synchronous operation that just grabbed some amount of buffered data if it exists?
2031
// // isaacs: it is. but it also triggers a _read() call, which calls readStart() on the handle
2032
// // isaacs: do process.stdin.pause() and i'd think it'd probably close the pending call
2033
// process['stdin']['pause']();
2034
// }
2035
},register:function(dev, ops) {
2036
TTY.ttys[dev] = { input: [], output: [], ops: ops };
2037
FS.registerDevice(dev, TTY.stream_ops);
2038
},stream_ops:{open:function(stream) {
2039
var tty = TTY.ttys[stream.node.rdev];
2040
if (!tty) {
2041
throw new FS.ErrnoError(43);
2042
}
2043
stream.tty = tty;
2044
stream.seekable = false;
2045
},close:function(stream) {
2046
// flush any pending line data
2047
stream.tty.ops.flush(stream.tty);
2048
},flush:function(stream) {
2049
stream.tty.ops.flush(stream.tty);
2050
},read:function(stream, buffer, offset, length, pos /* ignored */) {
2051
if (!stream.tty || !stream.tty.ops.get_char) {
2052
throw new FS.ErrnoError(60);
2053
}
2054
var bytesRead = 0;
2055
for (var i = 0; i < length; i++) {
2056
var result;
2057
try {
2058
result = stream.tty.ops.get_char(stream.tty);
2059
} catch (e) {
2060
throw new FS.ErrnoError(29);
2061
}
2062
if (result === undefined && bytesRead === 0) {
2063
throw new FS.ErrnoError(6);
2064
}
2065
if (result === null || result === undefined) break;
2066
bytesRead++;
2067
buffer[offset+i] = result;
2068
}
2069
if (bytesRead) {
2070
stream.node.timestamp = Date.now();
2071
}
2072
return bytesRead;
2073
},write:function(stream, buffer, offset, length, pos) {
2074
if (!stream.tty || !stream.tty.ops.put_char) {
2075
throw new FS.ErrnoError(60);
2076
}
2077
try {
2078
for (var i = 0; i < length; i++) {
2079
stream.tty.ops.put_char(stream.tty, buffer[offset+i]);
2080
}
2081
} catch (e) {
2082
throw new FS.ErrnoError(29);
2083
}
2084
if (length) {
2085
stream.node.timestamp = Date.now();
2086
}
2087
return i;
2088
}},default_tty_ops:{get_char:function(tty) {
2089
if (!tty.input.length) {
2090
var result = null;
2091
if (ENVIRONMENT_IS_NODE) {
2092
// we will read data by chunks of BUFSIZE
2093
var BUFSIZE = 256;
2094
var buf = Buffer.alloc ? Buffer.alloc(BUFSIZE) : new Buffer(BUFSIZE);
2095
var bytesRead = 0;
2096
2097
try {
2098
bytesRead = nodeFS.readSync(process.stdin.fd, buf, 0, BUFSIZE, null);
2099
} catch(e) {
2100
// Cross-platform differences: on Windows, reading EOF throws an exception, but on other OSes,
2101
// reading EOF returns 0. Uniformize behavior by treating the EOF exception to return 0.
2102
if (e.toString().indexOf('EOF') != -1) bytesRead = 0;
2103
else throw e;
2104
}
2105
2106
if (bytesRead > 0) {
2107
result = buf.slice(0, bytesRead).toString('utf-8');
2108
} else {
2109
result = null;
2110
}
2111
} else
2112
if (typeof window != 'undefined' &&
2113
typeof window.prompt == 'function') {
2114
// Browser.
2115
result = window.prompt('Input: '); // returns null on cancel
2116
if (result !== null) {
2117
result += '\n';
2118
}
2119
} else if (typeof readline == 'function') {
2120
// Command line.
2121
result = readline();
2122
if (result !== null) {
2123
result += '\n';
2124
}
2125
}
2126
if (!result) {
2127
return null;
2128
}
2129
tty.input = intArrayFromString(result, true);
2130
}
2131
return tty.input.shift();
2132
},put_char:function(tty, val) {
2133
if (val === null || val === 10) {
2134
out(UTF8ArrayToString(tty.output, 0));
2135
tty.output = [];
2136
} else {
2137
if (val != 0) tty.output.push(val); // val == 0 would cut text output off in the middle.
2138
}
2139
},flush:function(tty) {
2140
if (tty.output && tty.output.length > 0) {
2141
out(UTF8ArrayToString(tty.output, 0));
2142
tty.output = [];
2143
}
2144
}},default_tty1_ops:{put_char:function(tty, val) {
2145
if (val === null || val === 10) {
2146
err(UTF8ArrayToString(tty.output, 0));
2147
tty.output = [];
2148
} else {
2149
if (val != 0) tty.output.push(val);
2150
}
2151
},flush:function(tty) {
2152
if (tty.output && tty.output.length > 0) {
2153
err(UTF8ArrayToString(tty.output, 0));
2154
tty.output = [];
2155
}
2156
}}};
2157
2158
var MEMFS={ops_table:null,mount:function(mount) {
2159
return MEMFS.createNode(null, '/', 16384 | 511 /* 0777 */, 0);
2160
},createNode:function(parent, name, mode, dev) {
2161
if (FS.isBlkdev(mode) || FS.isFIFO(mode)) {
2162
// no supported
2163
throw new FS.ErrnoError(63);
2164
}
2165
if (!MEMFS.ops_table) {
2166
MEMFS.ops_table = {
2167
dir: {
2168
node: {
2169
getattr: MEMFS.node_ops.getattr,
2170
setattr: MEMFS.node_ops.setattr,
2171
lookup: MEMFS.node_ops.lookup,
2172
mknod: MEMFS.node_ops.mknod,
2173
rename: MEMFS.node_ops.rename,
2174
unlink: MEMFS.node_ops.unlink,
2175
rmdir: MEMFS.node_ops.rmdir,
2176
readdir: MEMFS.node_ops.readdir,
2177
symlink: MEMFS.node_ops.symlink
2178
},
2179
stream: {
2180
llseek: MEMFS.stream_ops.llseek
2181
}
2182
},
2183
file: {
2184
node: {
2185
getattr: MEMFS.node_ops.getattr,
2186
setattr: MEMFS.node_ops.setattr
2187
},
2188
stream: {
2189
llseek: MEMFS.stream_ops.llseek,
2190
read: MEMFS.stream_ops.read,
2191
write: MEMFS.stream_ops.write,
2192
allocate: MEMFS.stream_ops.allocate,
2193
mmap: MEMFS.stream_ops.mmap,
2194
msync: MEMFS.stream_ops.msync
2195
}
2196
},
2197
link: {
2198
node: {
2199
getattr: MEMFS.node_ops.getattr,
2200
setattr: MEMFS.node_ops.setattr,
2201
readlink: MEMFS.node_ops.readlink
2202
},
2203
stream: {}
2204
},
2205
chrdev: {
2206
node: {
2207
getattr: MEMFS.node_ops.getattr,
2208
setattr: MEMFS.node_ops.setattr
2209
},
2210
stream: FS.chrdev_stream_ops
2211
}
2212
};
2213
}
2214
var node = FS.createNode(parent, name, mode, dev);
2215
if (FS.isDir(node.mode)) {
2216
node.node_ops = MEMFS.ops_table.dir.node;
2217
node.stream_ops = MEMFS.ops_table.dir.stream;
2218
node.contents = {};
2219
} else if (FS.isFile(node.mode)) {
2220
node.node_ops = MEMFS.ops_table.file.node;
2221
node.stream_ops = MEMFS.ops_table.file.stream;
2222
node.usedBytes = 0; // The actual number of bytes used in the typed array, as opposed to contents.length which gives the whole capacity.
2223
// 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
2224
// for performance, and used by default. However, typed arrays are not resizable like normal JS arrays are, so there is a small disk size
2225
// penalty involved for appending file writes that continuously grow a file similar to std::vector capacity vs used -scheme.
2226
node.contents = null;
2227
} else if (FS.isLink(node.mode)) {
2228
node.node_ops = MEMFS.ops_table.link.node;
2229
node.stream_ops = MEMFS.ops_table.link.stream;
2230
} else if (FS.isChrdev(node.mode)) {
2231
node.node_ops = MEMFS.ops_table.chrdev.node;
2232
node.stream_ops = MEMFS.ops_table.chrdev.stream;
2233
}
2234
node.timestamp = Date.now();
2235
// add the new node to the parent
2236
if (parent) {
2237
parent.contents[name] = node;
2238
}
2239
return node;
2240
},getFileDataAsRegularArray:function(node) {
2241
if (node.contents && node.contents.subarray) {
2242
var arr = [];
2243
for (var i = 0; i < node.usedBytes; ++i) arr.push(node.contents[i]);
2244
return arr; // Returns a copy of the original data.
2245
}
2246
return node.contents; // No-op, the file contents are already in a JS array. Return as-is.
2247
},getFileDataAsTypedArray:function(node) {
2248
if (!node.contents) return new Uint8Array(0);
2249
if (node.contents.subarray) return node.contents.subarray(0, node.usedBytes); // Make sure to not return excess unused bytes.
2250
return new Uint8Array(node.contents);
2251
},expandFileStorage:function(node, newCapacity) {
2252
var prevCapacity = node.contents ? node.contents.length : 0;
2253
if (prevCapacity >= newCapacity) return; // No need to expand, the storage was already large enough.
2254
// Don't expand strictly to the given requested limit if it's only a very small increase, but instead geometrically grow capacity.
2255
// For small filesizes (<1MB), perform size*2 geometric increase, but for large sizes, do a much more conservative size*1.125 increase to
2256
// avoid overshooting the allocation cap by a very large margin.
2257
var CAPACITY_DOUBLING_MAX = 1024 * 1024;
2258
newCapacity = Math.max(newCapacity, (prevCapacity * (prevCapacity < CAPACITY_DOUBLING_MAX ? 2.0 : 1.125)) | 0);
2259
if (prevCapacity != 0) newCapacity = Math.max(newCapacity, 256); // At minimum allocate 256b for each file when expanding.
2260
var oldContents = node.contents;
2261
node.contents = new Uint8Array(newCapacity); // Allocate new storage.
2262
if (node.usedBytes > 0) node.contents.set(oldContents.subarray(0, node.usedBytes), 0); // Copy old data over to the new storage.
2263
return;
2264
},resizeFileStorage:function(node, newSize) {
2265
if (node.usedBytes == newSize) return;
2266
if (newSize == 0) {
2267
node.contents = null; // Fully decommit when requesting a resize to zero.
2268
node.usedBytes = 0;
2269
return;
2270
}
2271
if (!node.contents || node.contents.subarray) { // Resize a typed array if that is being used as the backing store.
2272
var oldContents = node.contents;
2273
node.contents = new Uint8Array(newSize); // Allocate new storage.
2274
if (oldContents) {
2275
node.contents.set(oldContents.subarray(0, Math.min(newSize, node.usedBytes))); // Copy old data over to the new storage.
2276
}
2277
node.usedBytes = newSize;
2278
return;
2279
}
2280
// Backing with a JS array.
2281
if (!node.contents) node.contents = [];
2282
if (node.contents.length > newSize) node.contents.length = newSize;
2283
else while (node.contents.length < newSize) node.contents.push(0);
2284
node.usedBytes = newSize;
2285
},node_ops:{getattr:function(node) {
2286
var attr = {};
2287
// device numbers reuse inode numbers.
2288
attr.dev = FS.isChrdev(node.mode) ? node.id : 1;
2289
attr.ino = node.id;
2290
attr.mode = node.mode;
2291
attr.nlink = 1;
2292
attr.uid = 0;
2293
attr.gid = 0;
2294
attr.rdev = node.rdev;
2295
if (FS.isDir(node.mode)) {
2296
attr.size = 4096;
2297
} else if (FS.isFile(node.mode)) {
2298
attr.size = node.usedBytes;
2299
} else if (FS.isLink(node.mode)) {
2300
attr.size = node.link.length;
2301
} else {
2302
attr.size = 0;
2303
}
2304
attr.atime = new Date(node.timestamp);
2305
attr.mtime = new Date(node.timestamp);
2306
attr.ctime = new Date(node.timestamp);
2307
// NOTE: In our implementation, st_blocks = Math.ceil(st_size/st_blksize),
2308
// but this is not required by the standard.
2309
attr.blksize = 4096;
2310
attr.blocks = Math.ceil(attr.size / attr.blksize);
2311
return attr;
2312
},setattr:function(node, attr) {
2313
if (attr.mode !== undefined) {
2314
node.mode = attr.mode;
2315
}
2316
if (attr.timestamp !== undefined) {
2317
node.timestamp = attr.timestamp;
2318
}
2319
if (attr.size !== undefined) {
2320
MEMFS.resizeFileStorage(node, attr.size);
2321
}
2322
},lookup:function(parent, name) {
2323
throw FS.genericErrors[44];
2324
},mknod:function(parent, name, mode, dev) {
2325
return MEMFS.createNode(parent, name, mode, dev);
2326
},rename:function(old_node, new_dir, new_name) {
2327
// if we're overwriting a directory at new_name, make sure it's empty.
2328
if (FS.isDir(old_node.mode)) {
2329
var new_node;
2330
try {
2331
new_node = FS.lookupNode(new_dir, new_name);
2332
} catch (e) {
2333
}
2334
if (new_node) {
2335
for (var i in new_node.contents) {
2336
throw new FS.ErrnoError(55);
2337
}
2338
}
2339
}
2340
// do the internal rewiring
2341
delete old_node.parent.contents[old_node.name];
2342
old_node.name = new_name;
2343
new_dir.contents[new_name] = old_node;
2344
old_node.parent = new_dir;
2345
},unlink:function(parent, name) {
2346
delete parent.contents[name];
2347
},rmdir:function(parent, name) {
2348
var node = FS.lookupNode(parent, name);
2349
for (var i in node.contents) {
2350
throw new FS.ErrnoError(55);
2351
}
2352
delete parent.contents[name];
2353
},readdir:function(node) {
2354
var entries = ['.', '..'];
2355
for (var key in node.contents) {
2356
if (!node.contents.hasOwnProperty(key)) {
2357
continue;
2358
}
2359
entries.push(key);
2360
}
2361
return entries;
2362
},symlink:function(parent, newname, oldpath) {
2363
var node = MEMFS.createNode(parent, newname, 511 /* 0777 */ | 40960, 0);
2364
node.link = oldpath;
2365
return node;
2366
},readlink:function(node) {
2367
if (!FS.isLink(node.mode)) {
2368
throw new FS.ErrnoError(28);
2369
}
2370
return node.link;
2371
}},stream_ops:{read:function(stream, buffer, offset, length, position) {
2372
var contents = stream.node.contents;
2373
if (position >= stream.node.usedBytes) return 0;
2374
var size = Math.min(stream.node.usedBytes - position, length);
2375
assert(size >= 0);
2376
if (size > 8 && contents.subarray) { // non-trivial, and typed array
2377
buffer.set(contents.subarray(position, position + size), offset);
2378
} else {
2379
for (var i = 0; i < size; i++) buffer[offset + i] = contents[position + i];
2380
}
2381
return size;
2382
},write:function(stream, buffer, offset, length, position, canOwn) {
2383
// The data buffer should be a typed array view
2384
assert(!(buffer instanceof ArrayBuffer));
2385
2386
if (!length) return 0;
2387
var node = stream.node;
2388
node.timestamp = Date.now();
2389
2390
if (buffer.subarray && (!node.contents || node.contents.subarray)) { // This write is from a typed array to a typed array?
2391
if (canOwn) {
2392
assert(position === 0, 'canOwn must imply no weird position inside the file');
2393
node.contents = buffer.subarray(offset, offset + length);
2394
node.usedBytes = length;
2395
return length;
2396
} 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.
2397
node.contents = buffer.slice(offset, offset + length);
2398
node.usedBytes = length;
2399
return length;
2400
} else if (position + length <= node.usedBytes) { // Writing to an already allocated and used subrange of the file?
2401
node.contents.set(buffer.subarray(offset, offset + length), position);
2402
return length;
2403
}
2404
}
2405
2406
// Appending to an existing file and we need to reallocate, or source data did not come as a typed array.
2407
MEMFS.expandFileStorage(node, position+length);
2408
if (node.contents.subarray && buffer.subarray) node.contents.set(buffer.subarray(offset, offset + length), position); // Use typed array write if available.
2409
else {
2410
for (var i = 0; i < length; i++) {
2411
node.contents[position + i] = buffer[offset + i]; // Or fall back to manual write if not.
2412
}
2413
}
2414
node.usedBytes = Math.max(node.usedBytes, position+length);
2415
return length;
2416
},llseek:function(stream, offset, whence) {
2417
var position = offset;
2418
if (whence === 1) {
2419
position += stream.position;
2420
} else if (whence === 2) {
2421
if (FS.isFile(stream.node.mode)) {
2422
position += stream.node.usedBytes;
2423
}
2424
}
2425
if (position < 0) {
2426
throw new FS.ErrnoError(28);
2427
}
2428
return position;
2429
},allocate:function(stream, offset, length) {
2430
MEMFS.expandFileStorage(stream.node, offset + length);
2431
stream.node.usedBytes = Math.max(stream.node.usedBytes, offset + length);
2432
},mmap:function(stream, buffer, offset, length, position, prot, flags) {
2433
// The data buffer should be a typed array view
2434
assert(!(buffer instanceof ArrayBuffer));
2435
if (!FS.isFile(stream.node.mode)) {
2436
throw new FS.ErrnoError(43);
2437
}
2438
var ptr;
2439
var allocated;
2440
var contents = stream.node.contents;
2441
// Only make a new copy when MAP_PRIVATE is specified.
2442
if ( !(flags & 2) &&
2443
contents.buffer === buffer.buffer ) {
2444
// We can't emulate MAP_SHARED when the file is not backed by the buffer
2445
// we're mapping to (e.g. the HEAP buffer).
2446
allocated = false;
2447
ptr = contents.byteOffset;
2448
} else {
2449
// Try to avoid unnecessary slices.
2450
if (position > 0 || position + length < contents.length) {
2451
if (contents.subarray) {
2452
contents = contents.subarray(position, position + length);
2453
} else {
2454
contents = Array.prototype.slice.call(contents, position, position + length);
2455
}
2456
}
2457
allocated = true;
2458
// malloc() can lead to growing the heap. If targeting the heap, we need to
2459
// re-acquire the heap buffer object in case growth had occurred.
2460
var fromHeap = (buffer.buffer == HEAP8.buffer);
2461
ptr = _malloc(length);
2462
if (!ptr) {
2463
throw new FS.ErrnoError(48);
2464
}
2465
(fromHeap ? HEAP8 : buffer).set(contents, ptr);
2466
}
2467
return { ptr: ptr, allocated: allocated };
2468
},msync:function(stream, buffer, offset, length, mmapFlags) {
2469
if (!FS.isFile(stream.node.mode)) {
2470
throw new FS.ErrnoError(43);
2471
}
2472
if (mmapFlags & 2) {
2473
// MAP_PRIVATE calls need not to be synced back to underlying fs
2474
return 0;
2475
}
2476
2477
var bytesWritten = MEMFS.stream_ops.write(stream, buffer, 0, length, offset, false);
2478
// should we check if bytesWritten and length are the same?
2479
return 0;
2480
}}};
2481
2482
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"};
2483
2484
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) {
2485
if (!(e instanceof FS.ErrnoError)) throw e + ' : ' + stackTrace();
2486
return ___setErrNo(e.errno);
2487
},lookupPath:function(path, opts) {
2488
path = PATH_FS.resolve(FS.cwd(), path);
2489
opts = opts || {};
2490
2491
if (!path) return { path: '', node: null };
2492
2493
var defaults = {
2494
follow_mount: true,
2495
recurse_count: 0
2496
};
2497
for (var key in defaults) {
2498
if (opts[key] === undefined) {
2499
opts[key] = defaults[key];
2500
}
2501
}
2502
2503
if (opts.recurse_count > 8) { // max recursive lookup of 8
2504
throw new FS.ErrnoError(32);
2505
}
2506
2507
// split the path
2508
var parts = PATH.normalizeArray(path.split('/').filter(function(p) {
2509
return !!p;
2510
}), false);
2511
2512
// start at the root
2513
var current = FS.root;
2514
var current_path = '/';
2515
2516
for (var i = 0; i < parts.length; i++) {
2517
var islast = (i === parts.length-1);
2518
if (islast && opts.parent) {
2519
// stop resolving
2520
break;
2521
}
2522
2523
current = FS.lookupNode(current, parts[i]);
2524
current_path = PATH.join2(current_path, parts[i]);
2525
2526
// jump to the mount's root node if this is a mountpoint
2527
if (FS.isMountpoint(current)) {
2528
if (!islast || (islast && opts.follow_mount)) {
2529
current = current.mounted.root;
2530
}
2531
}
2532
2533
// by default, lookupPath will not follow a symlink if it is the final path component.
2534
// setting opts.follow = true will override this behavior.
2535
if (!islast || opts.follow) {
2536
var count = 0;
2537
while (FS.isLink(current.mode)) {
2538
var link = FS.readlink(current_path);
2539
current_path = PATH_FS.resolve(PATH.dirname(current_path), link);
2540
2541
var lookup = FS.lookupPath(current_path, { recurse_count: opts.recurse_count });
2542
current = lookup.node;
2543
2544
if (count++ > 40) { // limit max consecutive symlinks to 40 (SYMLOOP_MAX).
2545
throw new FS.ErrnoError(32);
2546
}
2547
}
2548
}
2549
}
2550
2551
return { path: current_path, node: current };
2552
},getPath:function(node) {
2553
var path;
2554
while (true) {
2555
if (FS.isRoot(node)) {
2556
var mount = node.mount.mountpoint;
2557
if (!path) return mount;
2558
return mount[mount.length-1] !== '/' ? mount + '/' + path : mount + path;
2559
}
2560
path = path ? node.name + '/' + path : node.name;
2561
node = node.parent;
2562
}
2563
},hashName:function(parentid, name) {
2564
var hash = 0;
2565
2566
2567
for (var i = 0; i < name.length; i++) {
2568
hash = ((hash << 5) - hash + name.charCodeAt(i)) | 0;
2569
}
2570
return ((parentid + hash) >>> 0) % FS.nameTable.length;
2571
},hashAddNode:function(node) {
2572
var hash = FS.hashName(node.parent.id, node.name);
2573
node.name_next = FS.nameTable[hash];
2574
FS.nameTable[hash] = node;
2575
},hashRemoveNode:function(node) {
2576
var hash = FS.hashName(node.parent.id, node.name);
2577
if (FS.nameTable[hash] === node) {
2578
FS.nameTable[hash] = node.name_next;
2579
} else {
2580
var current = FS.nameTable[hash];
2581
while (current) {
2582
if (current.name_next === node) {
2583
current.name_next = node.name_next;
2584
break;
2585
}
2586
current = current.name_next;
2587
}
2588
}
2589
},lookupNode:function(parent, name) {
2590
var errCode = FS.mayLookup(parent);
2591
if (errCode) {
2592
throw new FS.ErrnoError(errCode, parent);
2593
}
2594
var hash = FS.hashName(parent.id, name);
2595
for (var node = FS.nameTable[hash]; node; node = node.name_next) {
2596
var nodeName = node.name;
2597
if (node.parent.id === parent.id && nodeName === name) {
2598
return node;
2599
}
2600
}
2601
// if we failed to find it in the cache, call into the VFS
2602
return FS.lookup(parent, name);
2603
},createNode:function(parent, name, mode, rdev) {
2604
var node = new FS.FSNode(parent, name, mode, rdev);
2605
2606
FS.hashAddNode(node);
2607
2608
return node;
2609
},destroyNode:function(node) {
2610
FS.hashRemoveNode(node);
2611
},isRoot:function(node) {
2612
return node === node.parent;
2613
},isMountpoint:function(node) {
2614
return !!node.mounted;
2615
},isFile:function(mode) {
2616
return (mode & 61440) === 32768;
2617
},isDir:function(mode) {
2618
return (mode & 61440) === 16384;
2619
},isLink:function(mode) {
2620
return (mode & 61440) === 40960;
2621
},isChrdev:function(mode) {
2622
return (mode & 61440) === 8192;
2623
},isBlkdev:function(mode) {
2624
return (mode & 61440) === 24576;
2625
},isFIFO:function(mode) {
2626
return (mode & 61440) === 4096;
2627
},isSocket:function(mode) {
2628
return (mode & 49152) === 49152;
2629
},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) {
2630
var flags = FS.flagModes[str];
2631
if (typeof flags === 'undefined') {
2632
throw new Error('Unknown file open mode: ' + str);
2633
}
2634
return flags;
2635
},flagsToPermissionString:function(flag) {
2636
var perms = ['r', 'w', 'rw'][flag & 3];
2637
if ((flag & 512)) {
2638
perms += 'w';
2639
}
2640
return perms;
2641
},nodePermissions:function(node, perms) {
2642
if (FS.ignorePermissions) {
2643
return 0;
2644
}
2645
// return 0 if any user, group or owner bits are set.
2646
if (perms.indexOf('r') !== -1 && !(node.mode & 292)) {
2647
return 2;
2648
} else if (perms.indexOf('w') !== -1 && !(node.mode & 146)) {
2649
return 2;
2650
} else if (perms.indexOf('x') !== -1 && !(node.mode & 73)) {
2651
return 2;
2652
}
2653
return 0;
2654
},mayLookup:function(dir) {
2655
var errCode = FS.nodePermissions(dir, 'x');
2656
if (errCode) return errCode;
2657
if (!dir.node_ops.lookup) return 2;
2658
return 0;
2659
},mayCreate:function(dir, name) {
2660
try {
2661
var node = FS.lookupNode(dir, name);
2662
return 20;
2663
} catch (e) {
2664
}
2665
return FS.nodePermissions(dir, 'wx');
2666
},mayDelete:function(dir, name, isdir) {
2667
var node;
2668
try {
2669
node = FS.lookupNode(dir, name);
2670
} catch (e) {
2671
return e.errno;
2672
}
2673
var errCode = FS.nodePermissions(dir, 'wx');
2674
if (errCode) {
2675
return errCode;
2676
}
2677
if (isdir) {
2678
if (!FS.isDir(node.mode)) {
2679
return 54;
2680
}
2681
if (FS.isRoot(node) || FS.getPath(node) === FS.cwd()) {
2682
return 10;
2683
}
2684
} else {
2685
if (FS.isDir(node.mode)) {
2686
return 31;
2687
}
2688
}
2689
return 0;
2690
},mayOpen:function(node, flags) {
2691
if (!node) {
2692
return 44;
2693
}
2694
if (FS.isLink(node.mode)) {
2695
return 32;
2696
} else if (FS.isDir(node.mode)) {
2697
if (FS.flagsToPermissionString(flags) !== 'r' || // opening for write
2698
(flags & 512)) { // TODO: check for O_SEARCH? (== search for dir only)
2699
return 31;
2700
}
2701
}
2702
return FS.nodePermissions(node, FS.flagsToPermissionString(flags));
2703
},MAX_OPEN_FDS:4096,nextfd:function(fd_start, fd_end) {
2704
fd_start = fd_start || 0;
2705
fd_end = fd_end || FS.MAX_OPEN_FDS;
2706
for (var fd = fd_start; fd <= fd_end; fd++) {
2707
if (!FS.streams[fd]) {
2708
return fd;
2709
}
2710
}
2711
throw new FS.ErrnoError(33);
2712
},getStream:function(fd) {
2713
return FS.streams[fd];
2714
},createStream:function(stream, fd_start, fd_end) {
2715
if (!FS.FSStream) {
2716
FS.FSStream = /** @constructor */ function(){};
2717
FS.FSStream.prototype = {
2718
object: {
2719
get: function() { return this.node; },
2720
set: function(val) { this.node = val; }
2721
},
2722
isRead: {
2723
get: function() { return (this.flags & 2097155) !== 1; }
2724
},
2725
isWrite: {
2726
get: function() { return (this.flags & 2097155) !== 0; }
2727
},
2728
isAppend: {
2729
get: function() { return (this.flags & 1024); }
2730
}
2731
};
2732
}
2733
// clone it, so we can return an instance of FSStream
2734
var newStream = new FS.FSStream();
2735
for (var p in stream) {
2736
newStream[p] = stream[p];
2737
}
2738
stream = newStream;
2739
var fd = FS.nextfd(fd_start, fd_end);
2740
stream.fd = fd;
2741
FS.streams[fd] = stream;
2742
return stream;
2743
},closeStream:function(fd) {
2744
FS.streams[fd] = null;
2745
},chrdev_stream_ops:{open:function(stream) {
2746
var device = FS.getDevice(stream.node.rdev);
2747
// override node's stream ops with the device's
2748
stream.stream_ops = device.stream_ops;
2749
// forward the open call
2750
if (stream.stream_ops.open) {
2751
stream.stream_ops.open(stream);
2752
}
2753
},llseek:function() {
2754
throw new FS.ErrnoError(70);
2755
}},major:function(dev) {
2756
return ((dev) >> 8);
2757
},minor:function(dev) {
2758
return ((dev) & 0xff);
2759
},makedev:function(ma, mi) {
2760
return ((ma) << 8 | (mi));
2761
},registerDevice:function(dev, ops) {
2762
FS.devices[dev] = { stream_ops: ops };
2763
},getDevice:function(dev) {
2764
return FS.devices[dev];
2765
},getMounts:function(mount) {
2766
var mounts = [];
2767
var check = [mount];
2768
2769
while (check.length) {
2770
var m = check.pop();
2771
2772
mounts.push(m);
2773
2774
check.push.apply(check, m.mounts);
2775
}
2776
2777
return mounts;
2778
},syncfs:function(populate, callback) {
2779
if (typeof(populate) === 'function') {
2780
callback = populate;
2781
populate = false;
2782
}
2783
2784
FS.syncFSRequests++;
2785
2786
if (FS.syncFSRequests > 1) {
2787
err('warning: ' + FS.syncFSRequests + ' FS.syncfs operations in flight at once, probably just doing extra work');
2788
}
2789
2790
var mounts = FS.getMounts(FS.root.mount);
2791
var completed = 0;
2792
2793
function doCallback(errCode) {
2794
assert(FS.syncFSRequests > 0);
2795
FS.syncFSRequests--;
2796
return callback(errCode);
2797
}
2798
2799
function done(errCode) {
2800
if (errCode) {
2801
if (!done.errored) {
2802
done.errored = true;
2803
return doCallback(errCode);
2804
}
2805
return;
2806
}
2807
if (++completed >= mounts.length) {
2808
doCallback(null);
2809
}
2810
};
2811
2812
// sync all mounts
2813
mounts.forEach(function (mount) {
2814
if (!mount.type.syncfs) {
2815
return done(null);
2816
}
2817
mount.type.syncfs(mount, populate, done);
2818
});
2819
},mount:function(type, opts, mountpoint) {
2820
if (typeof type === 'string') {
2821
// The filesystem was not included, and instead we have an error
2822
// message stored in the variable.
2823
throw type;
2824
}
2825
var root = mountpoint === '/';
2826
var pseudo = !mountpoint;
2827
var node;
2828
2829
if (root && FS.root) {
2830
throw new FS.ErrnoError(10);
2831
} else if (!root && !pseudo) {
2832
var lookup = FS.lookupPath(mountpoint, { follow_mount: false });
2833
2834
mountpoint = lookup.path; // use the absolute path
2835
node = lookup.node;
2836
2837
if (FS.isMountpoint(node)) {
2838
throw new FS.ErrnoError(10);
2839
}
2840
2841
if (!FS.isDir(node.mode)) {
2842
throw new FS.ErrnoError(54);
2843
}
2844
}
2845
2846
var mount = {
2847
type: type,
2848
opts: opts,
2849
mountpoint: mountpoint,
2850
mounts: []
2851
};
2852
2853
// create a root node for the fs
2854
var mountRoot = type.mount(mount);
2855
mountRoot.mount = mount;
2856
mount.root = mountRoot;
2857
2858
if (root) {
2859
FS.root = mountRoot;
2860
} else if (node) {
2861
// set as a mountpoint
2862
node.mounted = mount;
2863
2864
// add the new mount to the current mount's children
2865
if (node.mount) {
2866
node.mount.mounts.push(mount);
2867
}
2868
}
2869
2870
return mountRoot;
2871
},unmount:function (mountpoint) {
2872
var lookup = FS.lookupPath(mountpoint, { follow_mount: false });
2873
2874
if (!FS.isMountpoint(lookup.node)) {
2875
throw new FS.ErrnoError(28);
2876
}
2877
2878
// destroy the nodes for this mount, and all its child mounts
2879
var node = lookup.node;
2880
var mount = node.mounted;
2881
var mounts = FS.getMounts(mount);
2882
2883
Object.keys(FS.nameTable).forEach(function (hash) {
2884
var current = FS.nameTable[hash];
2885
2886
while (current) {
2887
var next = current.name_next;
2888
2889
if (mounts.indexOf(current.mount) !== -1) {
2890
FS.destroyNode(current);
2891
}
2892
2893
current = next;
2894
}
2895
});
2896
2897
// no longer a mountpoint
2898
node.mounted = null;
2899
2900
// remove this mount from the child mounts
2901
var idx = node.mount.mounts.indexOf(mount);
2902
assert(idx !== -1);
2903
node.mount.mounts.splice(idx, 1);
2904
},lookup:function(parent, name) {
2905
return parent.node_ops.lookup(parent, name);
2906
},mknod:function(path, mode, dev) {
2907
var lookup = FS.lookupPath(path, { parent: true });
2908
var parent = lookup.node;
2909
var name = PATH.basename(path);
2910
if (!name || name === '.' || name === '..') {
2911
throw new FS.ErrnoError(28);
2912
}
2913
var errCode = FS.mayCreate(parent, name);
2914
if (errCode) {
2915
throw new FS.ErrnoError(errCode);
2916
}
2917
if (!parent.node_ops.mknod) {
2918
throw new FS.ErrnoError(63);
2919
}
2920
return parent.node_ops.mknod(parent, name, mode, dev);
2921
},create:function(path, mode) {
2922
mode = mode !== undefined ? mode : 438 /* 0666 */;
2923
mode &= 4095;
2924
mode |= 32768;
2925
return FS.mknod(path, mode, 0);
2926
},mkdir:function(path, mode) {
2927
mode = mode !== undefined ? mode : 511 /* 0777 */;
2928
mode &= 511 | 512;
2929
mode |= 16384;
2930
return FS.mknod(path, mode, 0);
2931
},mkdirTree:function(path, mode) {
2932
var dirs = path.split('/');
2933
var d = '';
2934
for (var i = 0; i < dirs.length; ++i) {
2935
if (!dirs[i]) continue;
2936
d += '/' + dirs[i];
2937
try {
2938
FS.mkdir(d, mode);
2939
} catch(e) {
2940
if (e.errno != 20) throw e;
2941
}
2942
}
2943
},mkdev:function(path, mode, dev) {
2944
if (typeof(dev) === 'undefined') {
2945
dev = mode;
2946
mode = 438 /* 0666 */;
2947
}
2948
mode |= 8192;
2949
return FS.mknod(path, mode, dev);
2950
},symlink:function(oldpath, newpath) {
2951
if (!PATH_FS.resolve(oldpath)) {
2952
throw new FS.ErrnoError(44);
2953
}
2954
var lookup = FS.lookupPath(newpath, { parent: true });
2955
var parent = lookup.node;
2956
if (!parent) {
2957
throw new FS.ErrnoError(44);
2958
}
2959
var newname = PATH.basename(newpath);
2960
var errCode = FS.mayCreate(parent, newname);
2961
if (errCode) {
2962
throw new FS.ErrnoError(errCode);
2963
}
2964
if (!parent.node_ops.symlink) {
2965
throw new FS.ErrnoError(63);
2966
}
2967
return parent.node_ops.symlink(parent, newname, oldpath);
2968
},rename:function(old_path, new_path) {
2969
var old_dirname = PATH.dirname(old_path);
2970
var new_dirname = PATH.dirname(new_path);
2971
var old_name = PATH.basename(old_path);
2972
var new_name = PATH.basename(new_path);
2973
// parents must exist
2974
var lookup, old_dir, new_dir;
2975
try {
2976
lookup = FS.lookupPath(old_path, { parent: true });
2977
old_dir = lookup.node;
2978
lookup = FS.lookupPath(new_path, { parent: true });
2979
new_dir = lookup.node;
2980
} catch (e) {
2981
throw new FS.ErrnoError(10);
2982
}
2983
if (!old_dir || !new_dir) throw new FS.ErrnoError(44);
2984
// need to be part of the same mount
2985
if (old_dir.mount !== new_dir.mount) {
2986
throw new FS.ErrnoError(75);
2987
}
2988
// source must exist
2989
var old_node = FS.lookupNode(old_dir, old_name);
2990
// old path should not be an ancestor of the new path
2991
var relative = PATH_FS.relative(old_path, new_dirname);
2992
if (relative.charAt(0) !== '.') {
2993
throw new FS.ErrnoError(28);
2994
}
2995
// new path should not be an ancestor of the old path
2996
relative = PATH_FS.relative(new_path, old_dirname);
2997
if (relative.charAt(0) !== '.') {
2998
throw new FS.ErrnoError(55);
2999
}
3000
// see if the new path already exists
3001
var new_node;
3002
try {
3003
new_node = FS.lookupNode(new_dir, new_name);
3004
} catch (e) {
3005
// not fatal
3006
}
3007
// early out if nothing needs to change
3008
if (old_node === new_node) {
3009
return;
3010
}
3011
// we'll need to delete the old entry
3012
var isdir = FS.isDir(old_node.mode);
3013
var errCode = FS.mayDelete(old_dir, old_name, isdir);
3014
if (errCode) {
3015
throw new FS.ErrnoError(errCode);
3016
}
3017
// need delete permissions if we'll be overwriting.
3018
// need create permissions if new doesn't already exist.
3019
errCode = new_node ?
3020
FS.mayDelete(new_dir, new_name, isdir) :
3021
FS.mayCreate(new_dir, new_name);
3022
if (errCode) {
3023
throw new FS.ErrnoError(errCode);
3024
}
3025
if (!old_dir.node_ops.rename) {
3026
throw new FS.ErrnoError(63);
3027
}
3028
if (FS.isMountpoint(old_node) || (new_node && FS.isMountpoint(new_node))) {
3029
throw new FS.ErrnoError(10);
3030
}
3031
// if we are going to change the parent, check write permissions
3032
if (new_dir !== old_dir) {
3033
errCode = FS.nodePermissions(old_dir, 'w');
3034
if (errCode) {
3035
throw new FS.ErrnoError(errCode);
3036
}
3037
}
3038
try {
3039
if (FS.trackingDelegate['willMovePath']) {
3040
FS.trackingDelegate['willMovePath'](old_path, new_path);
3041
}
3042
} catch(e) {
3043
err("FS.trackingDelegate['willMovePath']('"+old_path+"', '"+new_path+"') threw an exception: " + e.message);
3044
}
3045
// remove the node from the lookup hash
3046
FS.hashRemoveNode(old_node);
3047
// do the underlying fs rename
3048
try {
3049
old_dir.node_ops.rename(old_node, new_dir, new_name);
3050
} catch (e) {
3051
throw e;
3052
} finally {
3053
// add the node back to the hash (in case node_ops.rename
3054
// changed its name)
3055
FS.hashAddNode(old_node);
3056
}
3057
try {
3058
if (FS.trackingDelegate['onMovePath']) FS.trackingDelegate['onMovePath'](old_path, new_path);
3059
} catch(e) {
3060
err("FS.trackingDelegate['onMovePath']('"+old_path+"', '"+new_path+"') threw an exception: " + e.message);
3061
}
3062
},rmdir:function(path) {
3063
var lookup = FS.lookupPath(path, { parent: true });
3064
var parent = lookup.node;
3065
var name = PATH.basename(path);
3066
var node = FS.lookupNode(parent, name);
3067
var errCode = FS.mayDelete(parent, name, true);
3068
if (errCode) {
3069
throw new FS.ErrnoError(errCode);
3070
}
3071
if (!parent.node_ops.rmdir) {
3072
throw new FS.ErrnoError(63);
3073
}
3074
if (FS.isMountpoint(node)) {
3075
throw new FS.ErrnoError(10);
3076
}
3077
try {
3078
if (FS.trackingDelegate['willDeletePath']) {
3079
FS.trackingDelegate['willDeletePath'](path);
3080
}
3081
} catch(e) {
3082
err("FS.trackingDelegate['willDeletePath']('"+path+"') threw an exception: " + e.message);
3083
}
3084
parent.node_ops.rmdir(parent, name);
3085
FS.destroyNode(node);
3086
try {
3087
if (FS.trackingDelegate['onDeletePath']) FS.trackingDelegate['onDeletePath'](path);
3088
} catch(e) {
3089
err("FS.trackingDelegate['onDeletePath']('"+path+"') threw an exception: " + e.message);
3090
}
3091
},readdir:function(path) {
3092
var lookup = FS.lookupPath(path, { follow: true });
3093
var node = lookup.node;
3094
if (!node.node_ops.readdir) {
3095
throw new FS.ErrnoError(54);
3096
}
3097
return node.node_ops.readdir(node);
3098
},unlink:function(path) {
3099
var lookup = FS.lookupPath(path, { parent: true });
3100
var parent = lookup.node;
3101
var name = PATH.basename(path);
3102
var node = FS.lookupNode(parent, name);
3103
var errCode = FS.mayDelete(parent, name, false);
3104
if (errCode) {
3105
// According to POSIX, we should map EISDIR to EPERM, but
3106
// we instead do what Linux does (and we must, as we use
3107
// the musl linux libc).
3108
throw new FS.ErrnoError(errCode);
3109
}
3110
if (!parent.node_ops.unlink) {
3111
throw new FS.ErrnoError(63);
3112
}
3113
if (FS.isMountpoint(node)) {
3114
throw new FS.ErrnoError(10);
3115
}
3116
try {
3117
if (FS.trackingDelegate['willDeletePath']) {
3118
FS.trackingDelegate['willDeletePath'](path);
3119
}
3120
} catch(e) {
3121
err("FS.trackingDelegate['willDeletePath']('"+path+"') threw an exception: " + e.message);
3122
}
3123
parent.node_ops.unlink(parent, name);
3124
FS.destroyNode(node);
3125
try {
3126
if (FS.trackingDelegate['onDeletePath']) FS.trackingDelegate['onDeletePath'](path);
3127
} catch(e) {
3128
err("FS.trackingDelegate['onDeletePath']('"+path+"') threw an exception: " + e.message);
3129
}
3130
},readlink:function(path) {
3131
var lookup = FS.lookupPath(path);
3132
var link = lookup.node;
3133
if (!link) {
3134
throw new FS.ErrnoError(44);
3135
}
3136
if (!link.node_ops.readlink) {
3137
throw new FS.ErrnoError(28);
3138
}
3139
return PATH_FS.resolve(FS.getPath(link.parent), link.node_ops.readlink(link));
3140
},stat:function(path, dontFollow) {
3141
var lookup = FS.lookupPath(path, { follow: !dontFollow });
3142
var node = lookup.node;
3143
if (!node) {
3144
throw new FS.ErrnoError(44);
3145
}
3146
if (!node.node_ops.getattr) {
3147
throw new FS.ErrnoError(63);
3148
}
3149
return node.node_ops.getattr(node);
3150
},lstat:function(path) {
3151
return FS.stat(path, true);
3152
},chmod:function(path, mode, dontFollow) {
3153
var node;
3154
if (typeof path === 'string') {
3155
var lookup = FS.lookupPath(path, { follow: !dontFollow });
3156
node = lookup.node;
3157
} else {
3158
node = path;
3159
}
3160
if (!node.node_ops.setattr) {
3161
throw new FS.ErrnoError(63);
3162
}
3163
node.node_ops.setattr(node, {
3164
mode: (mode & 4095) | (node.mode & ~4095),
3165
timestamp: Date.now()
3166
});
3167
},lchmod:function(path, mode) {
3168
FS.chmod(path, mode, true);
3169
},fchmod:function(fd, mode) {
3170
var stream = FS.getStream(fd);
3171
if (!stream) {
3172
throw new FS.ErrnoError(8);
3173
}
3174
FS.chmod(stream.node, mode);
3175
},chown:function(path, uid, gid, dontFollow) {
3176
var node;
3177
if (typeof path === 'string') {
3178
var lookup = FS.lookupPath(path, { follow: !dontFollow });
3179
node = lookup.node;
3180
} else {
3181
node = path;
3182
}
3183
if (!node.node_ops.setattr) {
3184
throw new FS.ErrnoError(63);
3185
}
3186
node.node_ops.setattr(node, {
3187
timestamp: Date.now()
3188
// we ignore the uid / gid for now
3189
});
3190
},lchown:function(path, uid, gid) {
3191
FS.chown(path, uid, gid, true);
3192
},fchown:function(fd, uid, gid) {
3193
var stream = FS.getStream(fd);
3194
if (!stream) {
3195
throw new FS.ErrnoError(8);
3196
}
3197
FS.chown(stream.node, uid, gid);
3198
},truncate:function(path, len) {
3199
if (len < 0) {
3200
throw new FS.ErrnoError(28);
3201
}
3202
var node;
3203
if (typeof path === 'string') {
3204
var lookup = FS.lookupPath(path, { follow: true });
3205
node = lookup.node;
3206
} else {
3207
node = path;
3208
}
3209
if (!node.node_ops.setattr) {
3210
throw new FS.ErrnoError(63);
3211
}
3212
if (FS.isDir(node.mode)) {
3213
throw new FS.ErrnoError(31);
3214
}
3215
if (!FS.isFile(node.mode)) {
3216
throw new FS.ErrnoError(28);
3217
}
3218
var errCode = FS.nodePermissions(node, 'w');
3219
if (errCode) {
3220
throw new FS.ErrnoError(errCode);
3221
}
3222
node.node_ops.setattr(node, {
3223
size: len,
3224
timestamp: Date.now()
3225
});
3226
},ftruncate:function(fd, len) {
3227
var stream = FS.getStream(fd);
3228
if (!stream) {
3229
throw new FS.ErrnoError(8);
3230
}
3231
if ((stream.flags & 2097155) === 0) {
3232
throw new FS.ErrnoError(28);
3233
}
3234
FS.truncate(stream.node, len);
3235
},utime:function(path, atime, mtime) {
3236
var lookup = FS.lookupPath(path, { follow: true });
3237
var node = lookup.node;
3238
node.node_ops.setattr(node, {
3239
timestamp: Math.max(atime, mtime)
3240
});
3241
},open:function(path, flags, mode, fd_start, fd_end) {
3242
if (path === "") {
3243
throw new FS.ErrnoError(44);
3244
}
3245
flags = typeof flags === 'string' ? FS.modeStringToFlags(flags) : flags;
3246
mode = typeof mode === 'undefined' ? 438 /* 0666 */ : mode;
3247
if ((flags & 64)) {
3248
mode = (mode & 4095) | 32768;
3249
} else {
3250
mode = 0;
3251
}
3252
var node;
3253
if (typeof path === 'object') {
3254
node = path;
3255
} else {
3256
path = PATH.normalize(path);
3257
try {
3258
var lookup = FS.lookupPath(path, {
3259
follow: !(flags & 131072)
3260
});
3261
node = lookup.node;
3262
} catch (e) {
3263
// ignore
3264
}
3265
}
3266
// perhaps we need to create the node
3267
var created = false;
3268
if ((flags & 64)) {
3269
if (node) {
3270
// if O_CREAT and O_EXCL are set, error out if the node already exists
3271
if ((flags & 128)) {
3272
throw new FS.ErrnoError(20);
3273
}
3274
} else {
3275
// node doesn't exist, try to create it
3276
node = FS.mknod(path, mode, 0);
3277
created = true;
3278
}
3279
}
3280
if (!node) {
3281
throw new FS.ErrnoError(44);
3282
}
3283
// can't truncate a device
3284
if (FS.isChrdev(node.mode)) {
3285
flags &= ~512;
3286
}
3287
// if asked only for a directory, then this must be one
3288
if ((flags & 65536) && !FS.isDir(node.mode)) {
3289
throw new FS.ErrnoError(54);
3290
}
3291
// check permissions, if this is not a file we just created now (it is ok to
3292
// create and write to a file with read-only permissions; it is read-only
3293
// for later use)
3294
if (!created) {
3295
var errCode = FS.mayOpen(node, flags);
3296
if (errCode) {
3297
throw new FS.ErrnoError(errCode);
3298
}
3299
}
3300
// do truncation if necessary
3301
if ((flags & 512)) {
3302
FS.truncate(node, 0);
3303
}
3304
// we've already handled these, don't pass down to the underlying vfs
3305
flags &= ~(128 | 512);
3306
3307
// register the stream with the filesystem
3308
var stream = FS.createStream({
3309
node: node,
3310
path: FS.getPath(node), // we want the absolute path to the node
3311
flags: flags,
3312
seekable: true,
3313
position: 0,
3314
stream_ops: node.stream_ops,
3315
// used by the file family libc calls (fopen, fwrite, ferror, etc.)
3316
ungotten: [],
3317
error: false
3318
}, fd_start, fd_end);
3319
// call the new stream's open function
3320
if (stream.stream_ops.open) {
3321
stream.stream_ops.open(stream);
3322
}
3323
if (Module['logReadFiles'] && !(flags & 1)) {
3324
if (!FS.readFiles) FS.readFiles = {};
3325
if (!(path in FS.readFiles)) {
3326
FS.readFiles[path] = 1;
3327
err("FS.trackingDelegate error on read file: " + path);
3328
}
3329
}
3330
try {
3331
if (FS.trackingDelegate['onOpenFile']) {
3332
var trackingFlags = 0;
3333
if ((flags & 2097155) !== 1) {
3334
trackingFlags |= FS.tracking.openFlags.READ;
3335
}
3336
if ((flags & 2097155) !== 0) {
3337
trackingFlags |= FS.tracking.openFlags.WRITE;
3338
}
3339
FS.trackingDelegate['onOpenFile'](path, trackingFlags);
3340
}
3341
} catch(e) {
3342
err("FS.trackingDelegate['onOpenFile']('"+path+"', flags) threw an exception: " + e.message);
3343
}
3344
return stream;
3345
},close:function(stream) {
3346
if (FS.isClosed(stream)) {
3347
throw new FS.ErrnoError(8);
3348
}
3349
if (stream.getdents) stream.getdents = null; // free readdir state
3350
try {
3351
if (stream.stream_ops.close) {
3352
stream.stream_ops.close(stream);
3353
}
3354
} catch (e) {
3355
throw e;
3356
} finally {
3357
FS.closeStream(stream.fd);
3358
}
3359
stream.fd = null;
3360
},isClosed:function(stream) {
3361
return stream.fd === null;
3362
},llseek:function(stream, offset, whence) {
3363
if (FS.isClosed(stream)) {
3364
throw new FS.ErrnoError(8);
3365
}
3366
if (!stream.seekable || !stream.stream_ops.llseek) {
3367
throw new FS.ErrnoError(70);
3368
}
3369
if (whence != 0 && whence != 1 && whence != 2) {
3370
throw new FS.ErrnoError(28);
3371
}
3372
stream.position = stream.stream_ops.llseek(stream, offset, whence);
3373
stream.ungotten = [];
3374
return stream.position;
3375
},read:function(stream, buffer, offset, length, position) {
3376
if (length < 0 || position < 0) {
3377
throw new FS.ErrnoError(28);
3378
}
3379
if (FS.isClosed(stream)) {
3380
throw new FS.ErrnoError(8);
3381
}
3382
if ((stream.flags & 2097155) === 1) {
3383
throw new FS.ErrnoError(8);
3384
}
3385
if (FS.isDir(stream.node.mode)) {
3386
throw new FS.ErrnoError(31);
3387
}
3388
if (!stream.stream_ops.read) {
3389
throw new FS.ErrnoError(28);
3390
}
3391
var seeking = typeof position !== 'undefined';
3392
if (!seeking) {
3393
position = stream.position;
3394
} else if (!stream.seekable) {
3395
throw new FS.ErrnoError(70);
3396
}
3397
var bytesRead = stream.stream_ops.read(stream, buffer, offset, length, position);
3398
if (!seeking) stream.position += bytesRead;
3399
return bytesRead;
3400
},write:function(stream, buffer, offset, length, position, canOwn) {
3401
if (length < 0 || position < 0) {
3402
throw new FS.ErrnoError(28);
3403
}
3404
if (FS.isClosed(stream)) {
3405
throw new FS.ErrnoError(8);
3406
}
3407
if ((stream.flags & 2097155) === 0) {
3408
throw new FS.ErrnoError(8);
3409
}
3410
if (FS.isDir(stream.node.mode)) {
3411
throw new FS.ErrnoError(31);
3412
}
3413
if (!stream.stream_ops.write) {
3414
throw new FS.ErrnoError(28);
3415
}
3416
if (stream.flags & 1024) {
3417
// seek to the end before writing in append mode
3418
FS.llseek(stream, 0, 2);
3419
}
3420
var seeking = typeof position !== 'undefined';
3421
if (!seeking) {
3422
position = stream.position;
3423
} else if (!stream.seekable) {
3424
throw new FS.ErrnoError(70);
3425
}
3426
var bytesWritten = stream.stream_ops.write(stream, buffer, offset, length, position, canOwn);
3427
if (!seeking) stream.position += bytesWritten;
3428
try {
3429
if (stream.path && FS.trackingDelegate['onWriteToFile']) FS.trackingDelegate['onWriteToFile'](stream.path);
3430
} catch(e) {
3431
err("FS.trackingDelegate['onWriteToFile']('"+stream.path+"') threw an exception: " + e.message);
3432
}
3433
return bytesWritten;
3434
},allocate:function(stream, offset, length) {
3435
if (FS.isClosed(stream)) {
3436
throw new FS.ErrnoError(8);
3437
}
3438
if (offset < 0 || length <= 0) {
3439
throw new FS.ErrnoError(28);
3440
}
3441
if ((stream.flags & 2097155) === 0) {
3442
throw new FS.ErrnoError(8);
3443
}
3444
if (!FS.isFile(stream.node.mode) && !FS.isDir(stream.node.mode)) {
3445
throw new FS.ErrnoError(43);
3446
}
3447
if (!stream.stream_ops.allocate) {
3448
throw new FS.ErrnoError(138);
3449
}
3450
stream.stream_ops.allocate(stream, offset, length);
3451
},mmap:function(stream, buffer, offset, length, position, prot, flags) {
3452
// User requests writing to file (prot & PROT_WRITE != 0).
3453
// Checking if we have permissions to write to the file unless
3454
// MAP_PRIVATE flag is set. According to POSIX spec it is possible
3455
// to write to file opened in read-only mode with MAP_PRIVATE flag,
3456
// as all modifications will be visible only in the memory of
3457
// the current process.
3458
if ((prot & 2) !== 0
3459
&& (flags & 2) === 0
3460
&& (stream.flags & 2097155) !== 2) {
3461
throw new FS.ErrnoError(2);
3462
}
3463
if ((stream.flags & 2097155) === 1) {
3464
throw new FS.ErrnoError(2);
3465
}
3466
if (!stream.stream_ops.mmap) {
3467
throw new FS.ErrnoError(43);
3468
}
3469
return stream.stream_ops.mmap(stream, buffer, offset, length, position, prot, flags);
3470
},msync:function(stream, buffer, offset, length, mmapFlags) {
3471
if (!stream || !stream.stream_ops.msync) {
3472
return 0;
3473
}
3474
return stream.stream_ops.msync(stream, buffer, offset, length, mmapFlags);
3475
},munmap:function(stream) {
3476
return 0;
3477
},ioctl:function(stream, cmd, arg) {
3478
if (!stream.stream_ops.ioctl) {
3479
throw new FS.ErrnoError(59);
3480
}
3481
return stream.stream_ops.ioctl(stream, cmd, arg);
3482
},readFile:function(path, opts) {
3483
opts = opts || {};
3484
opts.flags = opts.flags || 'r';
3485
opts.encoding = opts.encoding || 'binary';
3486
if (opts.encoding !== 'utf8' && opts.encoding !== 'binary') {
3487
throw new Error('Invalid encoding type "' + opts.encoding + '"');
3488
}
3489
var ret;
3490
var stream = FS.open(path, opts.flags);
3491
var stat = FS.stat(path);
3492
var length = stat.size;
3493
var buf = new Uint8Array(length);
3494
FS.read(stream, buf, 0, length, 0);
3495
if (opts.encoding === 'utf8') {
3496
ret = UTF8ArrayToString(buf, 0);
3497
} else if (opts.encoding === 'binary') {
3498
ret = buf;
3499
}
3500
FS.close(stream);
3501
return ret;
3502
},writeFile:function(path, data, opts) {
3503
opts = opts || {};
3504
opts.flags = opts.flags || 'w';
3505
var stream = FS.open(path, opts.flags, opts.mode);
3506
if (typeof data === 'string') {
3507
var buf = new Uint8Array(lengthBytesUTF8(data)+1);
3508
var actualNumBytes = stringToUTF8Array(data, buf, 0, buf.length);
3509
FS.write(stream, buf, 0, actualNumBytes, undefined, opts.canOwn);
3510
} else if (ArrayBuffer.isView(data)) {
3511
FS.write(stream, data, 0, data.byteLength, undefined, opts.canOwn);
3512
} else {
3513
throw new Error('Unsupported data type');
3514
}
3515
FS.close(stream);
3516
},cwd:function() {
3517
return FS.currentPath;
3518
},chdir:function(path) {
3519
var lookup = FS.lookupPath(path, { follow: true });
3520
if (lookup.node === null) {
3521
throw new FS.ErrnoError(44);
3522
}
3523
if (!FS.isDir(lookup.node.mode)) {
3524
throw new FS.ErrnoError(54);
3525
}
3526
var errCode = FS.nodePermissions(lookup.node, 'x');
3527
if (errCode) {
3528
throw new FS.ErrnoError(errCode);
3529
}
3530
FS.currentPath = lookup.path;
3531
},createDefaultDirectories:function() {
3532
FS.mkdir('/tmp');
3533
FS.mkdir('/home');
3534
FS.mkdir('/home/web_user');
3535
},createDefaultDevices:function() {
3536
// create /dev
3537
FS.mkdir('/dev');
3538
// setup /dev/null
3539
FS.registerDevice(FS.makedev(1, 3), {
3540
read: function() { return 0; },
3541
write: function(stream, buffer, offset, length, pos) { return length; }
3542
});
3543
FS.mkdev('/dev/null', FS.makedev(1, 3));
3544
// setup /dev/tty and /dev/tty1
3545
// stderr needs to print output using Module['printErr']
3546
// so we register a second tty just for it.
3547
TTY.register(FS.makedev(5, 0), TTY.default_tty_ops);
3548
TTY.register(FS.makedev(6, 0), TTY.default_tty1_ops);
3549
FS.mkdev('/dev/tty', FS.makedev(5, 0));
3550
FS.mkdev('/dev/tty1', FS.makedev(6, 0));
3551
// setup /dev/[u]random
3552
var random_device;
3553
if (typeof crypto === 'object' && typeof crypto['getRandomValues'] === 'function') {
3554
// for modern web browsers
3555
var randomBuffer = new Uint8Array(1);
3556
random_device = function() { crypto.getRandomValues(randomBuffer); return randomBuffer[0]; };
3557
} else
3558
if (ENVIRONMENT_IS_NODE) {
3559
// for nodejs with or without crypto support included
3560
try {
3561
var crypto_module = require('crypto');
3562
// nodejs has crypto support
3563
random_device = function() { return crypto_module['randomBytes'](1)[0]; };
3564
} catch (e) {
3565
// nodejs doesn't have crypto support
3566
}
3567
} else
3568
{}
3569
if (!random_device) {
3570
// we couldn't find a proper implementation, as Math.random() is not suitable for /dev/random, see emscripten-core/emscripten/pull/7096
3571
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 } };"); };
3572
}
3573
FS.createDevice('/dev', 'random', random_device);
3574
FS.createDevice('/dev', 'urandom', random_device);
3575
// we're not going to emulate the actual shm device,
3576
// just create the tmp dirs that reside in it commonly
3577
FS.mkdir('/dev/shm');
3578
FS.mkdir('/dev/shm/tmp');
3579
},createSpecialDirectories:function() {
3580
// create /proc/self/fd which allows /proc/self/fd/6 => readlink gives the name of the stream for fd 6 (see test_unistd_ttyname)
3581
FS.mkdir('/proc');
3582
FS.mkdir('/proc/self');
3583
FS.mkdir('/proc/self/fd');
3584
FS.mount({
3585
mount: function() {
3586
var node = FS.createNode('/proc/self', 'fd', 16384 | 511 /* 0777 */, 73);
3587
node.node_ops = {
3588
lookup: function(parent, name) {
3589
var fd = +name;
3590
var stream = FS.getStream(fd);
3591
if (!stream) throw new FS.ErrnoError(8);
3592
var ret = {
3593
parent: null,
3594
mount: { mountpoint: 'fake' },
3595
node_ops: { readlink: function() { return stream.path } }
3596
};
3597
ret.parent = ret; // make it look like a simple root node
3598
return ret;
3599
}
3600
};
3601
return node;
3602
}
3603
}, {}, '/proc/self/fd');
3604
},createStandardStreams:function() {
3605
// TODO deprecate the old functionality of a single
3606
// input / output callback and that utilizes FS.createDevice
3607
// and instead require a unique set of stream ops
3608
3609
// by default, we symlink the standard streams to the
3610
// default tty devices. however, if the standard streams
3611
// have been overwritten we create a unique device for
3612
// them instead.
3613
if (Module['stdin']) {
3614
FS.createDevice('/dev', 'stdin', Module['stdin']);
3615
} else {
3616
FS.symlink('/dev/tty', '/dev/stdin');
3617
}
3618
if (Module['stdout']) {
3619
FS.createDevice('/dev', 'stdout', null, Module['stdout']);
3620
} else {
3621
FS.symlink('/dev/tty', '/dev/stdout');
3622
}
3623
if (Module['stderr']) {
3624
FS.createDevice('/dev', 'stderr', null, Module['stderr']);
3625
} else {
3626
FS.symlink('/dev/tty1', '/dev/stderr');
3627
}
3628
3629
// open default streams for the stdin, stdout and stderr devices
3630
var stdin = FS.open('/dev/stdin', 'r');
3631
var stdout = FS.open('/dev/stdout', 'w');
3632
var stderr = FS.open('/dev/stderr', 'w');
3633
assert(stdin.fd === 0, 'invalid handle for stdin (' + stdin.fd + ')');
3634
assert(stdout.fd === 1, 'invalid handle for stdout (' + stdout.fd + ')');
3635
assert(stderr.fd === 2, 'invalid handle for stderr (' + stderr.fd + ')');
3636
},ensureErrnoError:function() {
3637
if (FS.ErrnoError) return;
3638
FS.ErrnoError = /** @this{Object} */ function ErrnoError(errno, node) {
3639
this.node = node;
3640
this.setErrno = /** @this{Object} */ function(errno) {
3641
this.errno = errno;
3642
for (var key in ERRNO_CODES) {
3643
if (ERRNO_CODES[key] === errno) {
3644
this.code = key;
3645
break;
3646
}
3647
}
3648
};
3649
this.setErrno(errno);
3650
this.message = ERRNO_MESSAGES[errno];
3651
3652
// Try to get a maximally helpful stack trace. On Node.js, getting Error.stack
3653
// now ensures it shows what we want.
3654
if (this.stack) {
3655
// Define the stack property for Node.js 4, which otherwise errors on the next line.
3656
Object.defineProperty(this, "stack", { value: (new Error).stack, writable: true });
3657
this.stack = demangleAll(this.stack);
3658
}
3659
};
3660
FS.ErrnoError.prototype = new Error();
3661
FS.ErrnoError.prototype.constructor = FS.ErrnoError;
3662
// Some errors may happen quite a bit, to avoid overhead we reuse them (and suffer a lack of stack info)
3663
[44].forEach(function(code) {
3664
FS.genericErrors[code] = new FS.ErrnoError(code);
3665
FS.genericErrors[code].stack = '<generic error, no stack>';
3666
});
3667
},staticInit:function() {
3668
FS.ensureErrnoError();
3669
3670
FS.nameTable = new Array(4096);
3671
3672
FS.mount(MEMFS, {}, '/');
3673
3674
FS.createDefaultDirectories();
3675
FS.createDefaultDevices();
3676
FS.createSpecialDirectories();
3677
3678
FS.filesystems = {
3679
'MEMFS': MEMFS,
3680
};
3681
},init:function(input, output, error) {
3682
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)');
3683
FS.init.initialized = true;
3684
3685
FS.ensureErrnoError();
3686
3687
// Allow Module.stdin etc. to provide defaults, if none explicitly passed to us here
3688
Module['stdin'] = input || Module['stdin'];
3689
Module['stdout'] = output || Module['stdout'];
3690
Module['stderr'] = error || Module['stderr'];
3691
3692
FS.createStandardStreams();
3693
},quit:function() {
3694
FS.init.initialized = false;
3695
// force-flush all streams, so we get musl std streams printed out
3696
var fflush = Module['_fflush'];
3697
if (fflush) fflush(0);
3698
// close all of our streams
3699
for (var i = 0; i < FS.streams.length; i++) {
3700
var stream = FS.streams[i];
3701
if (!stream) {
3702
continue;
3703
}
3704
FS.close(stream);
3705
}
3706
},getMode:function(canRead, canWrite) {
3707
var mode = 0;
3708
if (canRead) mode |= 292 | 73;
3709
if (canWrite) mode |= 146;
3710
return mode;
3711
},joinPath:function(parts, forceRelative) {
3712
var path = PATH.join.apply(null, parts);
3713
if (forceRelative && path[0] == '/') path = path.substr(1);
3714
return path;
3715
},absolutePath:function(relative, base) {
3716
return PATH_FS.resolve(base, relative);
3717
},standardizePath:function(path) {
3718
return PATH.normalize(path);
3719
},findObject:function(path, dontResolveLastLink) {
3720
var ret = FS.analyzePath(path, dontResolveLastLink);
3721
if (ret.exists) {
3722
return ret.object;
3723
} else {
3724
___setErrNo(ret.error);
3725
return null;
3726
}
3727
},analyzePath:function(path, dontResolveLastLink) {
3728
// operate from within the context of the symlink's target
3729
try {
3730
var lookup = FS.lookupPath(path, { follow: !dontResolveLastLink });
3731
path = lookup.path;
3732
} catch (e) {
3733
}
3734
var ret = {
3735
isRoot: false, exists: false, error: 0, name: null, path: null, object: null,
3736
parentExists: false, parentPath: null, parentObject: null
3737
};
3738
try {
3739
var lookup = FS.lookupPath(path, { parent: true });
3740
ret.parentExists = true;
3741
ret.parentPath = lookup.path;
3742
ret.parentObject = lookup.node;
3743
ret.name = PATH.basename(path);
3744
lookup = FS.lookupPath(path, { follow: !dontResolveLastLink });
3745
ret.exists = true;
3746
ret.path = lookup.path;
3747
ret.object = lookup.node;
3748
ret.name = lookup.node.name;
3749
ret.isRoot = lookup.path === '/';
3750
} catch (e) {
3751
ret.error = e.errno;
3752
};
3753
return ret;
3754
},createFolder:function(parent, name, canRead, canWrite) {
3755
var path = PATH.join2(typeof parent === 'string' ? parent : FS.getPath(parent), name);
3756
var mode = FS.getMode(canRead, canWrite);
3757
return FS.mkdir(path, mode);
3758
},createPath:function(parent, path, canRead, canWrite) {
3759
parent = typeof parent === 'string' ? parent : FS.getPath(parent);
3760
var parts = path.split('/').reverse();
3761
while (parts.length) {
3762
var part = parts.pop();
3763
if (!part) continue;
3764
var current = PATH.join2(parent, part);
3765
try {
3766
FS.mkdir(current);
3767
} catch (e) {
3768
// ignore EEXIST
3769
}
3770
parent = current;
3771
}
3772
return current;
3773
},createFile:function(parent, name, properties, canRead, canWrite) {
3774
var path = PATH.join2(typeof parent === 'string' ? parent : FS.getPath(parent), name);
3775
var mode = FS.getMode(canRead, canWrite);
3776
return FS.create(path, mode);
3777
},createDataFile:function(parent, name, data, canRead, canWrite, canOwn) {
3778
var path = name ? PATH.join2(typeof parent === 'string' ? parent : FS.getPath(parent), name) : parent;
3779
var mode = FS.getMode(canRead, canWrite);
3780
var node = FS.create(path, mode);
3781
if (data) {
3782
if (typeof data === 'string') {
3783
var arr = new Array(data.length);
3784
for (var i = 0, len = data.length; i < len; ++i) arr[i] = data.charCodeAt(i);
3785
data = arr;
3786
}
3787
// make sure we can write to the file
3788
FS.chmod(node, mode | 146);
3789
var stream = FS.open(node, 'w');
3790
FS.write(stream, data, 0, data.length, 0, canOwn);
3791
FS.close(stream);
3792
FS.chmod(node, mode);
3793
}
3794
return node;
3795
},createDevice:function(parent, name, input, output) {
3796
var path = PATH.join2(typeof parent === 'string' ? parent : FS.getPath(parent), name);
3797
var mode = FS.getMode(!!input, !!output);
3798
if (!FS.createDevice.major) FS.createDevice.major = 64;
3799
var dev = FS.makedev(FS.createDevice.major++, 0);
3800
// Create a fake device that a set of stream ops to emulate
3801
// the old behavior.
3802
FS.registerDevice(dev, {
3803
open: function(stream) {
3804
stream.seekable = false;
3805
},
3806
close: function(stream) {
3807
// flush any pending line data
3808
if (output && output.buffer && output.buffer.length) {
3809
output(10);
3810
}
3811
},
3812
read: function(stream, buffer, offset, length, pos /* ignored */) {
3813
var bytesRead = 0;
3814
for (var i = 0; i < length; i++) {
3815
var result;
3816
try {
3817
result = input();
3818
} catch (e) {
3819
throw new FS.ErrnoError(29);
3820
}
3821
if (result === undefined && bytesRead === 0) {
3822
throw new FS.ErrnoError(6);
3823
}
3824
if (result === null || result === undefined) break;
3825
bytesRead++;
3826
buffer[offset+i] = result;
3827
}
3828
if (bytesRead) {
3829
stream.node.timestamp = Date.now();
3830
}
3831
return bytesRead;
3832
},
3833
write: function(stream, buffer, offset, length, pos) {
3834
for (var i = 0; i < length; i++) {
3835
try {
3836
output(buffer[offset+i]);
3837
} catch (e) {
3838
throw new FS.ErrnoError(29);
3839
}
3840
}
3841
if (length) {
3842
stream.node.timestamp = Date.now();
3843
}
3844
return i;
3845
}
3846
});
3847
return FS.mkdev(path, mode, dev);
3848
},createLink:function(parent, name, target, canRead, canWrite) {
3849
var path = PATH.join2(typeof parent === 'string' ? parent : FS.getPath(parent), name);
3850
return FS.symlink(target, path);
3851
},forceLoadFile:function(obj) {
3852
if (obj.isDevice || obj.isFolder || obj.link || obj.contents) return true;
3853
var success = true;
3854
if (typeof XMLHttpRequest !== 'undefined') {
3855
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.");
3856
} else if (read_) {
3857
// Command-line.
3858
try {
3859
// WARNING: Can't read binary files in V8's d8 or tracemonkey's js, as
3860
// read() will try to parse UTF8.
3861
obj.contents = intArrayFromString(read_(obj.url), true);
3862
obj.usedBytes = obj.contents.length;
3863
} catch (e) {
3864
success = false;
3865
}
3866
} else {
3867
throw new Error('Cannot load without read() or XMLHttpRequest.');
3868
}
3869
if (!success) ___setErrNo(29);
3870
return success;
3871
},createLazyFile:function(parent, name, url, canRead, canWrite) {
3872
// Lazy chunked Uint8Array (implements get and length from Uint8Array). Actual getting is abstracted away for eventual reuse.
3873
/** @constructor */
3874
function LazyUint8Array() {
3875
this.lengthKnown = false;
3876
this.chunks = []; // Loaded chunks. Index is the chunk number
3877
}
3878
LazyUint8Array.prototype.get = /** @this{Object} */ function LazyUint8Array_get(idx) {
3879
if (idx > this.length-1 || idx < 0) {
3880
return undefined;
3881
}
3882
var chunkOffset = idx % this.chunkSize;
3883
var chunkNum = (idx / this.chunkSize)|0;
3884
return this.getter(chunkNum)[chunkOffset];
3885
};
3886
LazyUint8Array.prototype.setDataGetter = function LazyUint8Array_setDataGetter(getter) {
3887
this.getter = getter;
3888
};
3889
LazyUint8Array.prototype.cacheLength = function LazyUint8Array_cacheLength() {
3890
// Find length
3891
var xhr = new XMLHttpRequest();
3892
xhr.open('HEAD', url, false);
3893
xhr.send(null);
3894
if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) throw new Error("Couldn't load " + url + ". Status: " + xhr.status);
3895
var datalength = Number(xhr.getResponseHeader("Content-length"));
3896
var header;
3897
var hasByteServing = (header = xhr.getResponseHeader("Accept-Ranges")) && header === "bytes";
3898
var usesGzip = (header = xhr.getResponseHeader("Content-Encoding")) && header === "gzip";
3899
3900
var chunkSize = 1024*1024; // Chunk size in bytes
3901
3902
if (!hasByteServing) chunkSize = datalength;
3903
3904
// Function to get a range from the remote URL.
3905
var doXHR = (function(from, to) {
3906
if (from > to) throw new Error("invalid range (" + from + ", " + to + ") or no bytes requested!");
3907
if (to > datalength-1) throw new Error("only " + datalength + " bytes available! programmer error!");
3908
3909
// TODO: Use mozResponseArrayBuffer, responseStream, etc. if available.
3910
var xhr = new XMLHttpRequest();
3911
xhr.open('GET', url, false);
3912
if (datalength !== chunkSize) xhr.setRequestHeader("Range", "bytes=" + from + "-" + to);
3913
3914
// Some hints to the browser that we want binary data.
3915
if (typeof Uint8Array != 'undefined') xhr.responseType = 'arraybuffer';
3916
if (xhr.overrideMimeType) {
3917
xhr.overrideMimeType('text/plain; charset=x-user-defined');
3918
}
3919
3920
xhr.send(null);
3921
if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304)) throw new Error("Couldn't load " + url + ". Status: " + xhr.status);
3922
if (xhr.response !== undefined) {
3923
return new Uint8Array(/** @type{Array<number>} */(xhr.response || []));
3924
} else {
3925
return intArrayFromString(xhr.responseText || '', true);
3926
}
3927
});
3928
var lazyArray = this;
3929
lazyArray.setDataGetter(function(chunkNum) {
3930
var start = chunkNum * chunkSize;
3931
var end = (chunkNum+1) * chunkSize - 1; // including this byte
3932
end = Math.min(end, datalength-1); // if datalength-1 is selected, this is the last block
3933
if (typeof(lazyArray.chunks[chunkNum]) === "undefined") {
3934
lazyArray.chunks[chunkNum] = doXHR(start, end);
3935
}
3936
if (typeof(lazyArray.chunks[chunkNum]) === "undefined") throw new Error("doXHR failed!");
3937
return lazyArray.chunks[chunkNum];
3938
});
3939
3940
if (usesGzip || !datalength) {
3941
// if the server uses gzip or doesn't supply the length, we have to download the whole file to get the (uncompressed) length
3942
chunkSize = datalength = 1; // this will force getter(0)/doXHR do download the whole file
3943
datalength = this.getter(0).length;
3944
chunkSize = datalength;
3945
out("LazyFiles on gzip forces download of the whole file when length is accessed");
3946
}
3947
3948
this._length = datalength;
3949
this._chunkSize = chunkSize;
3950
this.lengthKnown = true;
3951
};
3952
if (typeof XMLHttpRequest !== 'undefined') {
3953
if (!ENVIRONMENT_IS_WORKER) throw 'Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc';
3954
var lazyArray = new LazyUint8Array();
3955
Object.defineProperties(lazyArray, {
3956
length: {
3957
get: /** @this{Object} */ function() {
3958
if(!this.lengthKnown) {
3959
this.cacheLength();
3960
}
3961
return this._length;
3962
}
3963
},
3964
chunkSize: {
3965
get: /** @this{Object} */ function() {
3966
if(!this.lengthKnown) {
3967
this.cacheLength();
3968
}
3969
return this._chunkSize;
3970
}
3971
}
3972
});
3973
3974
var properties = { isDevice: false, contents: lazyArray };
3975
} else {
3976
var properties = { isDevice: false, url: url };
3977
}
3978
3979
var node = FS.createFile(parent, name, properties, canRead, canWrite);
3980
// This is a total hack, but I want to get this lazy file code out of the
3981
// core of MEMFS. If we want to keep this lazy file concept I feel it should
3982
// be its own thin LAZYFS proxying calls to MEMFS.
3983
if (properties.contents) {
3984
node.contents = properties.contents;
3985
} else if (properties.url) {
3986
node.contents = null;
3987
node.url = properties.url;
3988
}
3989
// Add a function that defers querying the file size until it is asked the first time.
3990
Object.defineProperties(node, {
3991
usedBytes: {
3992
get: /** @this {FSNode} */ function() { return this.contents.length; }
3993
}
3994
});
3995
// override each stream op with one that tries to force load the lazy file first
3996
var stream_ops = {};
3997
var keys = Object.keys(node.stream_ops);
3998
keys.forEach(function(key) {
3999
var fn = node.stream_ops[key];
4000
stream_ops[key] = function forceLoadLazyFile() {
4001
if (!FS.forceLoadFile(node)) {
4002
throw new FS.ErrnoError(29);
4003
}
4004
return fn.apply(null, arguments);
4005
};
4006
});
4007
// use a custom read function
4008
stream_ops.read = function stream_ops_read(stream, buffer, offset, length, position) {
4009
if (!FS.forceLoadFile(node)) {
4010
throw new FS.ErrnoError(29);
4011
}
4012
var contents = stream.node.contents;
4013
if (position >= contents.length)
4014
return 0;
4015
var size = Math.min(contents.length - position, length);
4016
assert(size >= 0);
4017
if (contents.slice) { // normal array
4018
for (var i = 0; i < size; i++) {
4019
buffer[offset + i] = contents[position + i];
4020
}
4021
} else {
4022
for (var i = 0; i < size; i++) { // LazyUint8Array from sync binary XHR
4023
buffer[offset + i] = contents.get(position + i);
4024
}
4025
}
4026
return size;
4027
};
4028
node.stream_ops = stream_ops;
4029
return node;
4030
},createPreloadedFile:function(parent, name, url, canRead, canWrite, onload, onerror, dontCreateFile, canOwn, preFinish) {
4031
Browser.init(); // XXX perhaps this method should move onto Browser?
4032
// TODO we should allow people to just pass in a complete filename instead
4033
// of parent and name being that we just join them anyways
4034
var fullname = name ? PATH_FS.resolve(PATH.join2(parent, name)) : parent;
4035
var dep = getUniqueRunDependency('cp ' + fullname); // might have several active requests for the same fullname
4036
function processData(byteArray) {
4037
function finish(byteArray) {
4038
if (preFinish) preFinish();
4039
if (!dontCreateFile) {
4040
FS.createDataFile(parent, name, byteArray, canRead, canWrite, canOwn);
4041
}
4042
if (onload) onload();
4043
removeRunDependency(dep);
4044
}
4045
var handled = false;
4046
Module['preloadPlugins'].forEach(function(plugin) {
4047
if (handled) return;
4048
if (plugin['canHandle'](fullname)) {
4049
plugin['handle'](byteArray, fullname, finish, function() {
4050
if (onerror) onerror();
4051
removeRunDependency(dep);
4052
});
4053
handled = true;
4054
}
4055
});
4056
if (!handled) finish(byteArray);
4057
}
4058
addRunDependency(dep);
4059
if (typeof url == 'string') {
4060
Browser.asyncLoad(url, function(byteArray) {
4061
processData(byteArray);
4062
}, onerror);
4063
} else {
4064
processData(url);
4065
}
4066
},indexedDB:function() {
4067
return window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
4068
},DB_NAME:function() {
4069
return 'EM_FS_' + window.location.pathname;
4070
},DB_VERSION:20,DB_STORE_NAME:"FILE_DATA",saveFilesToDB:function(paths, onload, onerror) {
4071
onload = onload || function(){};
4072
onerror = onerror || function(){};
4073
var indexedDB = FS.indexedDB();
4074
try {
4075
var openRequest = indexedDB.open(FS.DB_NAME(), FS.DB_VERSION);
4076
} catch (e) {
4077
return onerror(e);
4078
}
4079
openRequest.onupgradeneeded = function openRequest_onupgradeneeded() {
4080
out('creating db');
4081
var db = openRequest.result;
4082
db.createObjectStore(FS.DB_STORE_NAME);
4083
};
4084
openRequest.onsuccess = function openRequest_onsuccess() {
4085
var db = openRequest.result;
4086
var transaction = db.transaction([FS.DB_STORE_NAME], 'readwrite');
4087
var files = transaction.objectStore(FS.DB_STORE_NAME);
4088
var ok = 0, fail = 0, total = paths.length;
4089
function finish() {
4090
if (fail == 0) onload(); else onerror();
4091
}
4092
paths.forEach(function(path) {
4093
var putRequest = files.put(FS.analyzePath(path).object.contents, path);
4094
putRequest.onsuccess = function putRequest_onsuccess() { ok++; if (ok + fail == total) finish() };
4095
putRequest.onerror = function putRequest_onerror() { fail++; if (ok + fail == total) finish() };
4096
});
4097
transaction.onerror = onerror;
4098
};
4099
openRequest.onerror = onerror;
4100
},loadFilesFromDB:function(paths, onload, onerror) {
4101
onload = onload || function(){};
4102
onerror = onerror || function(){};
4103
var indexedDB = FS.indexedDB();
4104
try {
4105
var openRequest = indexedDB.open(FS.DB_NAME(), FS.DB_VERSION);
4106
} catch (e) {
4107
return onerror(e);
4108
}
4109
openRequest.onupgradeneeded = onerror; // no database to load from
4110
openRequest.onsuccess = function openRequest_onsuccess() {
4111
var db = openRequest.result;
4112
try {
4113
var transaction = db.transaction([FS.DB_STORE_NAME], 'readonly');
4114
} catch(e) {
4115
onerror(e);
4116
return;
4117
}
4118
var files = transaction.objectStore(FS.DB_STORE_NAME);
4119
var ok = 0, fail = 0, total = paths.length;
4120
function finish() {
4121
if (fail == 0) onload(); else onerror();
4122
}
4123
paths.forEach(function(path) {
4124
var getRequest = files.get(path);
4125
getRequest.onsuccess = function getRequest_onsuccess() {
4126
if (FS.analyzePath(path).exists) {
4127
FS.unlink(path);
4128
}
4129
FS.createDataFile(PATH.dirname(path), PATH.basename(path), getRequest.result, true, true, true);
4130
ok++;
4131
if (ok + fail == total) finish();
4132
};
4133
getRequest.onerror = function getRequest_onerror() { fail++; if (ok + fail == total) finish() };
4134
});
4135
transaction.onerror = onerror;
4136
};
4137
openRequest.onerror = onerror;
4138
}};var SYSCALLS={mappings:{},DEFAULT_POLLMASK:5,umask:511,calculateAt:function(dirfd, path) {
4139
if (path[0] !== '/') {
4140
// relative path
4141
var dir;
4142
if (dirfd === -100) {
4143
dir = FS.cwd();
4144
} else {
4145
var dirstream = FS.getStream(dirfd);
4146
if (!dirstream) throw new FS.ErrnoError(8);
4147
dir = dirstream.path;
4148
}
4149
path = PATH.join2(dir, path);
4150
}
4151
return path;
4152
},doStat:function(func, path, buf) {
4153
try {
4154
var stat = func(path);
4155
} catch (e) {
4156
if (e && e.node && PATH.normalize(path) !== PATH.normalize(FS.getPath(e.node))) {
4157
// an error occurred while trying to look up the path; we should just report ENOTDIR
4158
return -54;
4159
}
4160
throw e;
4161
}
4162
HEAP32[((buf)>>2)]=stat.dev;
4163
HEAP32[(((buf)+(4))>>2)]=0;
4164
HEAP32[(((buf)+(8))>>2)]=stat.ino;
4165
HEAP32[(((buf)+(12))>>2)]=stat.mode;
4166
HEAP32[(((buf)+(16))>>2)]=stat.nlink;
4167
HEAP32[(((buf)+(20))>>2)]=stat.uid;
4168
HEAP32[(((buf)+(24))>>2)]=stat.gid;
4169
HEAP32[(((buf)+(28))>>2)]=stat.rdev;
4170
HEAP32[(((buf)+(32))>>2)]=0;
4171
(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]);
4172
HEAP32[(((buf)+(48))>>2)]=4096;
4173
HEAP32[(((buf)+(52))>>2)]=stat.blocks;
4174
HEAP32[(((buf)+(56))>>2)]=(stat.atime.getTime() / 1000)|0;
4175
HEAP32[(((buf)+(60))>>2)]=0;
4176
HEAP32[(((buf)+(64))>>2)]=(stat.mtime.getTime() / 1000)|0;
4177
HEAP32[(((buf)+(68))>>2)]=0;
4178
HEAP32[(((buf)+(72))>>2)]=(stat.ctime.getTime() / 1000)|0;
4179
HEAP32[(((buf)+(76))>>2)]=0;
4180
(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]);
4181
return 0;
4182
},doMsync:function(addr, stream, len, flags, offset) {
4183
var buffer = HEAPU8.slice(addr, addr + len);
4184
FS.msync(stream, buffer, offset, len, flags);
4185
},doMkdir:function(path, mode) {
4186
// remove a trailing slash, if one - /a/b/ has basename of '', but
4187
// we want to create b in the context of this function
4188
path = PATH.normalize(path);
4189
if (path[path.length-1] === '/') path = path.substr(0, path.length-1);
4190
FS.mkdir(path, mode, 0);
4191
return 0;
4192
},doMknod:function(path, mode, dev) {
4193
// we don't want this in the JS API as it uses mknod to create all nodes.
4194
switch (mode & 61440) {
4195
case 32768:
4196
case 8192:
4197
case 24576:
4198
case 4096:
4199
case 49152:
4200
break;
4201
default: return -28;
4202
}
4203
FS.mknod(path, mode, dev);
4204
return 0;
4205
},doReadlink:function(path, buf, bufsize) {
4206
if (bufsize <= 0) return -28;
4207
var ret = FS.readlink(path);
4208
4209
var len = Math.min(bufsize, lengthBytesUTF8(ret));
4210
var endChar = HEAP8[buf+len];
4211
stringToUTF8(ret, buf, bufsize+1);
4212
// readlink is one of the rare functions that write out a C string, but does never append a null to the output buffer(!)
4213
// stringToUTF8() always appends a null byte, so restore the character under the null byte after the write.
4214
HEAP8[buf+len] = endChar;
4215
4216
return len;
4217
},doAccess:function(path, amode) {
4218
if (amode & ~7) {
4219
// need a valid mode
4220
return -28;
4221
}
4222
var node;
4223
var lookup = FS.lookupPath(path, { follow: true });
4224
node = lookup.node;
4225
if (!node) {
4226
return -44;
4227
}
4228
var perms = '';
4229
if (amode & 4) perms += 'r';
4230
if (amode & 2) perms += 'w';
4231
if (amode & 1) perms += 'x';
4232
if (perms /* otherwise, they've just passed F_OK */ && FS.nodePermissions(node, perms)) {
4233
return -2;
4234
}
4235
return 0;
4236
},doDup:function(path, flags, suggestFD) {
4237
var suggest = FS.getStream(suggestFD);
4238
if (suggest) FS.close(suggest);
4239
return FS.open(path, flags, 0, suggestFD, suggestFD).fd;
4240
},doReadv:function(stream, iov, iovcnt, offset) {
4241
var ret = 0;
4242
for (var i = 0; i < iovcnt; i++) {
4243
var ptr = HEAP32[(((iov)+(i*8))>>2)];
4244
var len = HEAP32[(((iov)+(i*8 + 4))>>2)];
4245
var curr = FS.read(stream, HEAP8,ptr, len, offset);
4246
if (curr < 0) return -1;
4247
ret += curr;
4248
if (curr < len) break; // nothing more to read
4249
}
4250
return ret;
4251
},doWritev:function(stream, iov, iovcnt, offset) {
4252
var ret = 0;
4253
for (var i = 0; i < iovcnt; i++) {
4254
var ptr = HEAP32[(((iov)+(i*8))>>2)];
4255
var len = HEAP32[(((iov)+(i*8 + 4))>>2)];
4256
var curr = FS.write(stream, HEAP8,ptr, len, offset);
4257
if (curr < 0) return -1;
4258
ret += curr;
4259
}
4260
return ret;
4261
},varargs:undefined,get:function() {
4262
assert(SYSCALLS.varargs != undefined);
4263
SYSCALLS.varargs += 4;
4264
var ret = HEAP32[(((SYSCALLS.varargs)-(4))>>2)];
4265
return ret;
4266
},getStr:function(ptr) {
4267
var ret = UTF8ToString(ptr);
4268
return ret;
4269
},getStreamFromFD:function(fd) {
4270
var stream = FS.getStream(fd);
4271
if (!stream) throw new FS.ErrnoError(8);
4272
return stream;
4273
},get64:function(low, high) {
4274
if (low >= 0) assert(high === 0);
4275
else assert(high === -1);
4276
return low;
4277
}};function ___syscall221(fd, cmd, varargs) {SYSCALLS.varargs = varargs;
4278
try {
4279
// fcntl64
4280
var stream = SYSCALLS.getStreamFromFD(fd);
4281
switch (cmd) {
4282
case 0: {
4283
var arg = SYSCALLS.get();
4284
if (arg < 0) {
4285
return -28;
4286
}
4287
var newStream;
4288
newStream = FS.open(stream.path, stream.flags, 0, arg);
4289
return newStream.fd;
4290
}
4291
case 1:
4292
case 2:
4293
return 0; // FD_CLOEXEC makes no sense for a single process.
4294
case 3:
4295
return stream.flags;
4296
case 4: {
4297
var arg = SYSCALLS.get();
4298
stream.flags |= arg;
4299
return 0;
4300
}
4301
case 12:
4302
/* 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 */ {
4303
4304
var arg = SYSCALLS.get();
4305
var offset = 0;
4306
// We're always unlocked.
4307
HEAP16[(((arg)+(offset))>>1)]=2;
4308
return 0;
4309
}
4310
case 13:
4311
case 14:
4312
/* 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 */
4313
/* 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 */
4314
4315
4316
return 0; // Pretend that the locking is successful.
4317
case 16:
4318
case 8:
4319
return -28; // These are for sockets. We don't have them fully implemented yet.
4320
case 9:
4321
// 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.
4322
___setErrNo(28);
4323
return -1;
4324
default: {
4325
return -28;
4326
}
4327
}
4328
} catch (e) {
4329
if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
4330
return -e.errno;
4331
}
4332
}
4333
4334
function ___syscall5(path, flags, varargs) {SYSCALLS.varargs = varargs;
4335
try {
4336
// open
4337
var pathname = SYSCALLS.getStr(path);
4338
var mode = SYSCALLS.get();
4339
var stream = FS.open(pathname, flags, mode);
4340
return stream.fd;
4341
} catch (e) {
4342
if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
4343
return -e.errno;
4344
}
4345
}
4346
4347
function ___syscall54(fd, op, varargs) {SYSCALLS.varargs = varargs;
4348
try {
4349
// ioctl
4350
var stream = SYSCALLS.getStreamFromFD(fd);
4351
switch (op) {
4352
case 21509:
4353
case 21505: {
4354
if (!stream.tty) return -59;
4355
return 0;
4356
}
4357
case 21510:
4358
case 21511:
4359
case 21512:
4360
case 21506:
4361
case 21507:
4362
case 21508: {
4363
if (!stream.tty) return -59;
4364
return 0; // no-op, not actually adjusting terminal settings
4365
}
4366
case 21519: {
4367
if (!stream.tty) return -59;
4368
var argp = SYSCALLS.get();
4369
HEAP32[((argp)>>2)]=0;
4370
return 0;
4371
}
4372
case 21520: {
4373
if (!stream.tty) return -59;
4374
return -28; // not supported
4375
}
4376
case 21531: {
4377
var argp = SYSCALLS.get();
4378
return FS.ioctl(stream, op, argp);
4379
}
4380
case 21523: {
4381
// TODO: in theory we should write to the winsize struct that gets
4382
// passed in, but for now musl doesn't read anything on it
4383
if (!stream.tty) return -59;
4384
return 0;
4385
}
4386
case 21524: {
4387
// TODO: technically, this ioctl call should change the window size.
4388
// but, since emscripten doesn't have any concept of a terminal window
4389
// yet, we'll just silently throw it away as we do TIOCGWINSZ
4390
if (!stream.tty) return -59;
4391
return 0;
4392
}
4393
default: abort('bad ioctl syscall ' + op);
4394
}
4395
} catch (e) {
4396
if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
4397
return -e.errno;
4398
}
4399
}
4400
4401
function _abort() {
4402
abort();
4403
}
4404
4405
function _atexit(func, arg) {
4406
warnOnce('atexit() called, but EXIT_RUNTIME is not set, so atexits() will not be called. set EXIT_RUNTIME to 1 (see the FAQ)');
4407
__ATEXIT__.unshift({ func: func, arg: arg });
4408
}
4409
4410
4411
var _emscripten_get_now;if (ENVIRONMENT_IS_NODE) {
4412
_emscripten_get_now = function() {
4413
var t = process['hrtime']();
4414
return t[0] * 1e3 + t[1] / 1e6;
4415
};
4416
} else if (typeof dateNow !== 'undefined') {
4417
_emscripten_get_now = dateNow;
4418
} else _emscripten_get_now = function() { return performance.now(); }
4419
;
4420
4421
var _emscripten_get_now_is_monotonic=true;;function _clock_gettime(clk_id, tp) {
4422
// int clock_gettime(clockid_t clk_id, struct timespec *tp);
4423
var now;
4424
if (clk_id === 0) {
4425
now = Date.now();
4426
} else if ((clk_id === 1 || clk_id === 4) && _emscripten_get_now_is_monotonic) {
4427
now = _emscripten_get_now();
4428
} else {
4429
___setErrNo(28);
4430
return -1;
4431
}
4432
HEAP32[((tp)>>2)]=(now/1000)|0; // seconds
4433
HEAP32[(((tp)+(4))>>2)]=((now % 1000)*1000*1000)|0; // nanoseconds
4434
return 0;
4435
}
4436
4437
function _dlclose(handle) {
4438
abort("To use dlopen, you need to use Emscripten's linking support, see https://github.com/emscripten-core/emscripten/wiki/Linking");
4439
}
4440
4441
function _dlerror() {
4442
abort("To use dlopen, you need to use Emscripten's linking support, see https://github.com/emscripten-core/emscripten/wiki/Linking");
4443
}
4444
4445
function _dlsym(handle, symbol) {
4446
abort("To use dlopen, you need to use Emscripten's linking support, see https://github.com/emscripten-core/emscripten/wiki/Linking");
4447
}
4448
4449
4450
4451
4452
4453
function _emscripten_set_main_loop_timing(mode, value) {
4454
Browser.mainLoop.timingMode = mode;
4455
Browser.mainLoop.timingValue = value;
4456
4457
if (!Browser.mainLoop.func) {
4458
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.');
4459
return 1; // Return non-zero on failure, can't set timing mode when there is no main loop.
4460
}
4461
4462
if (mode == 0 /*EM_TIMING_SETTIMEOUT*/) {
4463
Browser.mainLoop.scheduler = function Browser_mainLoop_scheduler_setTimeout() {
4464
var timeUntilNextTick = Math.max(0, Browser.mainLoop.tickStartTime + value - _emscripten_get_now())|0;
4465
setTimeout(Browser.mainLoop.runner, timeUntilNextTick); // doing this each time means that on exception, we stop
4466
};
4467
Browser.mainLoop.method = 'timeout';
4468
} else if (mode == 1 /*EM_TIMING_RAF*/) {
4469
Browser.mainLoop.scheduler = function Browser_mainLoop_scheduler_rAF() {
4470
Browser.requestAnimationFrame(Browser.mainLoop.runner);
4471
};
4472
Browser.mainLoop.method = 'rAF';
4473
} else if (mode == 2 /*EM_TIMING_SETIMMEDIATE*/) {
4474
if (typeof setImmediate === 'undefined') {
4475
// Emulate setImmediate. (note: not a complete polyfill, we don't emulate clearImmediate() to keep code size to minimum, since not needed)
4476
var setImmediates = [];
4477
var emscriptenMainLoopMessageId = 'setimmediate';
4478
var Browser_setImmediate_messageHandler = function(event) {
4479
// 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,
4480
// so check for both cases.
4481
if (event.data === emscriptenMainLoopMessageId || event.data.target === emscriptenMainLoopMessageId) {
4482
event.stopPropagation();
4483
setImmediates.shift()();
4484
}
4485
}
4486
addEventListener("message", Browser_setImmediate_messageHandler, true);
4487
setImmediate = /** @type{function(function(): ?, ...?): number} */(function Browser_emulated_setImmediate(func) {
4488
setImmediates.push(func);
4489
if (ENVIRONMENT_IS_WORKER) {
4490
if (Module['setImmediates'] === undefined) Module['setImmediates'] = [];
4491
Module['setImmediates'].push(func);
4492
postMessage({target: emscriptenMainLoopMessageId}); // In --proxy-to-worker, route the message via proxyClient.js
4493
} else postMessage(emscriptenMainLoopMessageId, "*"); // On the main thread, can just send the message to itself.
4494
})
4495
}
4496
Browser.mainLoop.scheduler = function Browser_mainLoop_scheduler_setImmediate() {
4497
setImmediate(Browser.mainLoop.runner);
4498
};
4499
Browser.mainLoop.method = 'immediate';
4500
}
4501
return 0;
4502
}/** @param {number|boolean=} noSetTiming */
4503
function _emscripten_set_main_loop(func, fps, simulateInfiniteLoop, arg, noSetTiming) {
4504
noExitRuntime = true;
4505
4506
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.');
4507
4508
Browser.mainLoop.func = func;
4509
Browser.mainLoop.arg = arg;
4510
4511
var browserIterationFunc;
4512
if (typeof arg !== 'undefined') {
4513
browserIterationFunc = function() {
4514
Module['dynCall_vi'](func, arg);
4515
};
4516
} else {
4517
browserIterationFunc = function() {
4518
Module['dynCall_v'](func);
4519
};
4520
}
4521
4522
var thisMainLoopId = Browser.mainLoop.currentlyRunningMainloop;
4523
4524
Browser.mainLoop.runner = function Browser_mainLoop_runner() {
4525
if (ABORT) return;
4526
if (Browser.mainLoop.queue.length > 0) {
4527
var start = Date.now();
4528
var blocker = Browser.mainLoop.queue.shift();
4529
blocker.func(blocker.arg);
4530
if (Browser.mainLoop.remainingBlockers) {
4531
var remaining = Browser.mainLoop.remainingBlockers;
4532
var next = remaining%1 == 0 ? remaining-1 : Math.floor(remaining);
4533
if (blocker.counted) {
4534
Browser.mainLoop.remainingBlockers = next;
4535
} else {
4536
// not counted, but move the progress along a tiny bit
4537
next = next + 0.5; // do not steal all the next one's progress
4538
Browser.mainLoop.remainingBlockers = (8*remaining + next)/9;
4539
}
4540
}
4541
console.log('main loop blocker "' + blocker.name + '" took ' + (Date.now() - start) + ' ms'); //, left: ' + Browser.mainLoop.remainingBlockers);
4542
Browser.mainLoop.updateStatus();
4543
4544
// catches pause/resume main loop from blocker execution
4545
if (thisMainLoopId < Browser.mainLoop.currentlyRunningMainloop) return;
4546
4547
setTimeout(Browser.mainLoop.runner, 0);
4548
return;
4549
}
4550
4551
// catch pauses from non-main loop sources
4552
if (thisMainLoopId < Browser.mainLoop.currentlyRunningMainloop) return;
4553
4554
// Implement very basic swap interval control
4555
Browser.mainLoop.currentFrameNumber = Browser.mainLoop.currentFrameNumber + 1 | 0;
4556
if (Browser.mainLoop.timingMode == 1/*EM_TIMING_RAF*/ && Browser.mainLoop.timingValue > 1 && Browser.mainLoop.currentFrameNumber % Browser.mainLoop.timingValue != 0) {
4557
// Not the scheduled time to render this frame - skip.
4558
Browser.mainLoop.scheduler();
4559
return;
4560
} else if (Browser.mainLoop.timingMode == 0/*EM_TIMING_SETTIMEOUT*/) {
4561
Browser.mainLoop.tickStartTime = _emscripten_get_now();
4562
}
4563
4564
// Signal GL rendering layer that processing of a new frame is about to start. This helps it optimize
4565
// VBO double-buffering and reduce GPU stalls.
4566
4567
4568
4569
if (Browser.mainLoop.method === 'timeout' && Module.ctx) {
4570
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!');
4571
Browser.mainLoop.method = ''; // just warn once per call to set main loop
4572
}
4573
4574
Browser.mainLoop.runIter(browserIterationFunc);
4575
4576
checkStackCookie();
4577
4578
// catch pauses from the main loop itself
4579
if (thisMainLoopId < Browser.mainLoop.currentlyRunningMainloop) return;
4580
4581
// Queue new audio data. This is important to be right after the main loop invocation, so that we will immediately be able
4582
// to queue the newest produced audio samples.
4583
// TODO: Consider adding pre- and post- rAF callbacks so that GL.newRenderingFrameStarted() and SDL.audio.queueNewAudioData()
4584
// do not need to be hardcoded into this function, but can be more generic.
4585
if (typeof SDL === 'object' && SDL.audio && SDL.audio.queueNewAudioData) SDL.audio.queueNewAudioData();
4586
4587
Browser.mainLoop.scheduler();
4588
}
4589
4590
if (!noSetTiming) {
4591
if (fps && fps > 0) _emscripten_set_main_loop_timing(0/*EM_TIMING_SETTIMEOUT*/, 1000.0 / fps);
4592
else _emscripten_set_main_loop_timing(1/*EM_TIMING_RAF*/, 1); // Do rAF by rendering each frame (no decimating)
4593
4594
Browser.mainLoop.scheduler();
4595
}
4596
4597
if (simulateInfiniteLoop) {
4598
throw 'unwind';
4599
}
4600
}var Browser={mainLoop:{scheduler:null,method:"",currentlyRunningMainloop:0,func:null,arg:0,timingMode:0,timingValue:0,currentFrameNumber:0,queue:[],pause:function() {
4601
Browser.mainLoop.scheduler = null;
4602
Browser.mainLoop.currentlyRunningMainloop++; // Incrementing this signals the previous main loop that it's now become old, and it must return.
4603
},resume:function() {
4604
Browser.mainLoop.currentlyRunningMainloop++;
4605
var timingMode = Browser.mainLoop.timingMode;
4606
var timingValue = Browser.mainLoop.timingValue;
4607
var func = Browser.mainLoop.func;
4608
Browser.mainLoop.func = null;
4609
_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 */);
4610
_emscripten_set_main_loop_timing(timingMode, timingValue);
4611
Browser.mainLoop.scheduler();
4612
},updateStatus:function() {
4613
if (Module['setStatus']) {
4614
var message = Module['statusMessage'] || 'Please wait...';
4615
var remaining = Browser.mainLoop.remainingBlockers;
4616
var expected = Browser.mainLoop.expectedBlockers;
4617
if (remaining) {
4618
if (remaining < expected) {
4619
Module['setStatus'](message + ' (' + (expected - remaining) + '/' + expected + ')');
4620
} else {
4621
Module['setStatus'](message);
4622
}
4623
} else {
4624
Module['setStatus']('');
4625
}
4626
}
4627
},runIter:function(func) {
4628
if (ABORT) return;
4629
if (Module['preMainLoop']) {
4630
var preRet = Module['preMainLoop']();
4631
if (preRet === false) {
4632
return; // |return false| skips a frame
4633
}
4634
}
4635
try {
4636
func();
4637
} catch (e) {
4638
if (e instanceof ExitStatus) {
4639
return;
4640
} else {
4641
if (e && typeof e === 'object' && e.stack) err('exception thrown: ' + [e, e.stack]);
4642
throw e;
4643
}
4644
}
4645
if (Module['postMainLoop']) Module['postMainLoop']();
4646
}},isFullscreen:false,pointerLock:false,moduleContextCreatedCallbacks:[],workers:[],init:function() {
4647
if (!Module["preloadPlugins"]) Module["preloadPlugins"] = []; // needs to exist even in workers
4648
4649
if (Browser.initted) return;
4650
Browser.initted = true;
4651
4652
try {
4653
new Blob();
4654
Browser.hasBlobConstructor = true;
4655
} catch(e) {
4656
Browser.hasBlobConstructor = false;
4657
console.log("warning: no blob constructor, cannot create blobs with mimetypes");
4658
}
4659
Browser.BlobBuilder = typeof MozBlobBuilder != "undefined" ? MozBlobBuilder : (typeof WebKitBlobBuilder != "undefined" ? WebKitBlobBuilder : (!Browser.hasBlobConstructor ? console.log("warning: no BlobBuilder") : null));
4660
Browser.URLObject = typeof window != "undefined" ? (window.URL ? window.URL : window.webkitURL) : undefined;
4661
if (!Module.noImageDecoding && typeof Browser.URLObject === 'undefined') {
4662
console.log("warning: Browser does not support creating object URLs. Built-in browser image decoding will not be available.");
4663
Module.noImageDecoding = true;
4664
}
4665
4666
// Support for plugins that can process preloaded files. You can add more of these to
4667
// your app by creating and appending to Module.preloadPlugins.
4668
//
4669
// Each plugin is asked if it can handle a file based on the file's name. If it can,
4670
// it is given the file's raw data. When it is done, it calls a callback with the file's
4671
// (possibly modified) data. For example, a plugin might decompress a file, or it
4672
// might create some side data structure for use later (like an Image element, etc.).
4673
4674
var imagePlugin = {};
4675
imagePlugin['canHandle'] = function imagePlugin_canHandle(name) {
4676
return !Module.noImageDecoding && /\.(jpg|jpeg|png|bmp)$/i.test(name);
4677
};
4678
imagePlugin['handle'] = function imagePlugin_handle(byteArray, name, onload, onerror) {
4679
var b = null;
4680
if (Browser.hasBlobConstructor) {
4681
try {
4682
b = new Blob([byteArray], { type: Browser.getMimetype(name) });
4683
if (b.size !== byteArray.length) { // Safari bug #118630
4684
// Safari's Blob can only take an ArrayBuffer
4685
b = new Blob([(new Uint8Array(byteArray)).buffer], { type: Browser.getMimetype(name) });
4686
}
4687
} catch(e) {
4688
warnOnce('Blob constructor present but fails: ' + e + '; falling back to blob builder');
4689
}
4690
}
4691
if (!b) {
4692
var bb = new Browser.BlobBuilder();
4693
bb.append((new Uint8Array(byteArray)).buffer); // we need to pass a buffer, and must copy the array to get the right data range
4694
b = bb.getBlob();
4695
}
4696
var url = Browser.URLObject.createObjectURL(b);
4697
assert(typeof url == 'string', 'createObjectURL must return a url as a string');
4698
var img = new Image();
4699
img.onload = function img_onload() {
4700
assert(img.complete, 'Image ' + name + ' could not be decoded');
4701
var canvas = document.createElement('canvas');
4702
canvas.width = img.width;
4703
canvas.height = img.height;
4704
var ctx = canvas.getContext('2d');
4705
ctx.drawImage(img, 0, 0);
4706
Module["preloadedImages"][name] = canvas;
4707
Browser.URLObject.revokeObjectURL(url);
4708
if (onload) onload(byteArray);
4709
};
4710
img.onerror = function img_onerror(event) {
4711
console.log('Image ' + url + ' could not be decoded');
4712
if (onerror) onerror();
4713
};
4714
img.src = url;
4715
};
4716
Module['preloadPlugins'].push(imagePlugin);
4717
4718
var audioPlugin = {};
4719
audioPlugin['canHandle'] = function audioPlugin_canHandle(name) {
4720
return !Module.noAudioDecoding && name.substr(-4) in { '.ogg': 1, '.wav': 1, '.mp3': 1 };
4721
};
4722
audioPlugin['handle'] = function audioPlugin_handle(byteArray, name, onload, onerror) {
4723
var done = false;
4724
function finish(audio) {
4725
if (done) return;
4726
done = true;
4727
Module["preloadedAudios"][name] = audio;
4728
if (onload) onload(byteArray);
4729
}
4730
function fail() {
4731
if (done) return;
4732
done = true;
4733
Module["preloadedAudios"][name] = new Audio(); // empty shim
4734
if (onerror) onerror();
4735
}
4736
if (Browser.hasBlobConstructor) {
4737
try {
4738
var b = new Blob([byteArray], { type: Browser.getMimetype(name) });
4739
} catch(e) {
4740
return fail();
4741
}
4742
var url = Browser.URLObject.createObjectURL(b); // XXX we never revoke this!
4743
assert(typeof url == 'string', 'createObjectURL must return a url as a string');
4744
var audio = new Audio();
4745
audio.addEventListener('canplaythrough', function() { finish(audio) }, false); // use addEventListener due to chromium bug 124926
4746
audio.onerror = function audio_onerror(event) {
4747
if (done) return;
4748
console.log('warning: browser could not fully decode audio ' + name + ', trying slower base64 approach');
4749
function encode64(data) {
4750
var BASE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
4751
var PAD = '=';
4752
var ret = '';
4753
var leftchar = 0;
4754
var leftbits = 0;
4755
for (var i = 0; i < data.length; i++) {
4756
leftchar = (leftchar << 8) | data[i];
4757
leftbits += 8;
4758
while (leftbits >= 6) {
4759
var curr = (leftchar >> (leftbits-6)) & 0x3f;
4760
leftbits -= 6;
4761
ret += BASE[curr];
4762
}
4763
}
4764
if (leftbits == 2) {
4765
ret += BASE[(leftchar&3) << 4];
4766
ret += PAD + PAD;
4767
} else if (leftbits == 4) {
4768
ret += BASE[(leftchar&0xf) << 2];
4769
ret += PAD;
4770
}
4771
return ret;
4772
}
4773
audio.src = 'data:audio/x-' + name.substr(-3) + ';base64,' + encode64(byteArray);
4774
finish(audio); // we don't wait for confirmation this worked - but it's worth trying
4775
};
4776
audio.src = url;
4777
// workaround for chrome bug 124926 - we do not always get oncanplaythrough or onerror
4778
Browser.safeSetTimeout(function() {
4779
finish(audio); // try to use it even though it is not necessarily ready to play
4780
}, 10000);
4781
} else {
4782
return fail();
4783
}
4784
};
4785
Module['preloadPlugins'].push(audioPlugin);
4786
4787
4788
// Canvas event setup
4789
4790
function pointerLockChange() {
4791
Browser.pointerLock = document['pointerLockElement'] === Module['canvas'] ||
4792
document['mozPointerLockElement'] === Module['canvas'] ||
4793
document['webkitPointerLockElement'] === Module['canvas'] ||
4794
document['msPointerLockElement'] === Module['canvas'];
4795
}
4796
var canvas = Module['canvas'];
4797
if (canvas) {
4798
// forced aspect ratio can be enabled by defining 'forcedAspectRatio' on Module
4799
// Module['forcedAspectRatio'] = 4 / 3;
4800
4801
canvas.requestPointerLock = canvas['requestPointerLock'] ||
4802
canvas['mozRequestPointerLock'] ||
4803
canvas['webkitRequestPointerLock'] ||
4804
canvas['msRequestPointerLock'] ||
4805
function(){};
4806
canvas.exitPointerLock = document['exitPointerLock'] ||
4807
document['mozExitPointerLock'] ||
4808
document['webkitExitPointerLock'] ||
4809
document['msExitPointerLock'] ||
4810
function(){}; // no-op if function does not exist
4811
canvas.exitPointerLock = canvas.exitPointerLock.bind(document);
4812
4813
document.addEventListener('pointerlockchange', pointerLockChange, false);
4814
document.addEventListener('mozpointerlockchange', pointerLockChange, false);
4815
document.addEventListener('webkitpointerlockchange', pointerLockChange, false);
4816
document.addEventListener('mspointerlockchange', pointerLockChange, false);
4817
4818
if (Module['elementPointerLock']) {
4819
canvas.addEventListener("click", function(ev) {
4820
if (!Browser.pointerLock && Module['canvas'].requestPointerLock) {
4821
Module['canvas'].requestPointerLock();
4822
ev.preventDefault();
4823
}
4824
}, false);
4825
}
4826
}
4827
},createContext:function(canvas, useWebGL, setInModule, webGLContextAttributes) {
4828
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.
4829
4830
var ctx;
4831
var contextHandle;
4832
if (useWebGL) {
4833
// For GLES2/desktop GL compatibility, adjust a few defaults to be different to WebGL defaults, so that they align better with the desktop defaults.
4834
var contextAttributes = {
4835
antialias: false,
4836
alpha: false,
4837
majorVersion: 1,
4838
};
4839
4840
if (webGLContextAttributes) {
4841
for (var attribute in webGLContextAttributes) {
4842
contextAttributes[attribute] = webGLContextAttributes[attribute];
4843
}
4844
}
4845
4846
// 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
4847
// actually compiled in because application is not doing any GL operations. TODO: Ideally if GL is not being used, this function
4848
// Browser.createContext() should not even be emitted.
4849
if (typeof GL !== 'undefined') {
4850
contextHandle = GL.createContext(canvas, contextAttributes);
4851
if (contextHandle) {
4852
ctx = GL.getContext(contextHandle).GLctx;
4853
}
4854
}
4855
} else {
4856
ctx = canvas.getContext('2d');
4857
}
4858
4859
if (!ctx) return null;
4860
4861
if (setInModule) {
4862
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');
4863
4864
Module.ctx = ctx;
4865
if (useWebGL) GL.makeContextCurrent(contextHandle);
4866
Module.useWebGL = useWebGL;
4867
Browser.moduleContextCreatedCallbacks.forEach(function(callback) { callback() });
4868
Browser.init();
4869
}
4870
return ctx;
4871
},destroyContext:function(canvas, useWebGL, setInModule) {},fullscreenHandlersInstalled:false,lockPointer:undefined,resizeCanvas:undefined,requestFullscreen:function(lockPointer, resizeCanvas) {
4872
Browser.lockPointer = lockPointer;
4873
Browser.resizeCanvas = resizeCanvas;
4874
if (typeof Browser.lockPointer === 'undefined') Browser.lockPointer = true;
4875
if (typeof Browser.resizeCanvas === 'undefined') Browser.resizeCanvas = false;
4876
4877
var canvas = Module['canvas'];
4878
function fullscreenChange() {
4879
Browser.isFullscreen = false;
4880
var canvasContainer = canvas.parentNode;
4881
if ((document['fullscreenElement'] || document['mozFullScreenElement'] ||
4882
document['msFullscreenElement'] || document['webkitFullscreenElement'] ||
4883
document['webkitCurrentFullScreenElement']) === canvasContainer) {
4884
canvas.exitFullscreen = Browser.exitFullscreen;
4885
if (Browser.lockPointer) canvas.requestPointerLock();
4886
Browser.isFullscreen = true;
4887
if (Browser.resizeCanvas) {
4888
Browser.setFullscreenCanvasSize();
4889
} else {
4890
Browser.updateCanvasDimensions(canvas);
4891
}
4892
} else {
4893
// remove the full screen specific parent of the canvas again to restore the HTML structure from before going full screen
4894
canvasContainer.parentNode.insertBefore(canvas, canvasContainer);
4895
canvasContainer.parentNode.removeChild(canvasContainer);
4896
4897
if (Browser.resizeCanvas) {
4898
Browser.setWindowedCanvasSize();
4899
} else {
4900
Browser.updateCanvasDimensions(canvas);
4901
}
4902
}
4903
if (Module['onFullScreen']) Module['onFullScreen'](Browser.isFullscreen);
4904
if (Module['onFullscreen']) Module['onFullscreen'](Browser.isFullscreen);
4905
}
4906
4907
if (!Browser.fullscreenHandlersInstalled) {
4908
Browser.fullscreenHandlersInstalled = true;
4909
document.addEventListener('fullscreenchange', fullscreenChange, false);
4910
document.addEventListener('mozfullscreenchange', fullscreenChange, false);
4911
document.addEventListener('webkitfullscreenchange', fullscreenChange, false);
4912
document.addEventListener('MSFullscreenChange', fullscreenChange, false);
4913
}
4914
4915
// 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
4916
var canvasContainer = document.createElement("div");
4917
canvas.parentNode.insertBefore(canvasContainer, canvas);
4918
canvasContainer.appendChild(canvas);
4919
4920
// use parent of canvas as full screen root to allow aspect ratio correction (Firefox stretches the root to screen size)
4921
canvasContainer.requestFullscreen = canvasContainer['requestFullscreen'] ||
4922
canvasContainer['mozRequestFullScreen'] ||
4923
canvasContainer['msRequestFullscreen'] ||
4924
(canvasContainer['webkitRequestFullscreen'] ? function() { canvasContainer['webkitRequestFullscreen'](Element['ALLOW_KEYBOARD_INPUT']) } : null) ||
4925
(canvasContainer['webkitRequestFullScreen'] ? function() { canvasContainer['webkitRequestFullScreen'](Element['ALLOW_KEYBOARD_INPUT']) } : null);
4926
4927
canvasContainer.requestFullscreen();
4928
},requestFullScreen:function() {
4929
abort('Module.requestFullScreen has been replaced by Module.requestFullscreen (without a capital S)');
4930
},exitFullscreen:function() {
4931
// This is workaround for chrome. Trying to exit from fullscreen
4932
// not in fullscreen state will cause "TypeError: Document not active"
4933
// in chrome. See https://github.com/emscripten-core/emscripten/pull/8236
4934
if (!Browser.isFullscreen) {
4935
return false;
4936
}
4937
4938
var CFS = document['exitFullscreen'] ||
4939
document['cancelFullScreen'] ||
4940
document['mozCancelFullScreen'] ||
4941
document['msExitFullscreen'] ||
4942
document['webkitCancelFullScreen'] ||
4943
(function() {});
4944
CFS.apply(document, []);
4945
return true;
4946
},nextRAF:0,fakeRequestAnimationFrame:function(func) {
4947
// try to keep 60fps between calls to here
4948
var now = Date.now();
4949
if (Browser.nextRAF === 0) {
4950
Browser.nextRAF = now + 1000/60;
4951
} else {
4952
while (now + 2 >= Browser.nextRAF) { // fudge a little, to avoid timer jitter causing us to do lots of delay:0
4953
Browser.nextRAF += 1000/60;
4954
}
4955
}
4956
var delay = Math.max(Browser.nextRAF - now, 0);
4957
setTimeout(func, delay);
4958
},requestAnimationFrame:function(func) {
4959
if (typeof requestAnimationFrame === 'function') {
4960
requestAnimationFrame(func);
4961
return;
4962
}
4963
var RAF = Browser.fakeRequestAnimationFrame;
4964
RAF(func);
4965
},safeCallback:function(func) {
4966
return function() {
4967
if (!ABORT) return func.apply(null, arguments);
4968
};
4969
},allowAsyncCallbacks:true,queuedAsyncCallbacks:[],pauseAsyncCallbacks:function() {
4970
Browser.allowAsyncCallbacks = false;
4971
},resumeAsyncCallbacks:function() { // marks future callbacks as ok to execute, and synchronously runs any remaining ones right now
4972
Browser.allowAsyncCallbacks = true;
4973
if (Browser.queuedAsyncCallbacks.length > 0) {
4974
var callbacks = Browser.queuedAsyncCallbacks;
4975
Browser.queuedAsyncCallbacks = [];
4976
callbacks.forEach(function(func) {
4977
func();
4978
});
4979
}
4980
},safeRequestAnimationFrame:function(func) {
4981
return Browser.requestAnimationFrame(function() {
4982
if (ABORT) return;
4983
if (Browser.allowAsyncCallbacks) {
4984
func();
4985
} else {
4986
Browser.queuedAsyncCallbacks.push(func);
4987
}
4988
});
4989
},safeSetTimeout:function(func, timeout) {
4990
noExitRuntime = true;
4991
return setTimeout(function() {
4992
if (ABORT) return;
4993
if (Browser.allowAsyncCallbacks) {
4994
func();
4995
} else {
4996
Browser.queuedAsyncCallbacks.push(func);
4997
}
4998
}, timeout);
4999
},safeSetInterval:function(func, timeout) {
5000
noExitRuntime = true;
5001
return setInterval(function() {
5002
if (ABORT) return;
5003
if (Browser.allowAsyncCallbacks) {
5004
func();
5005
} // drop it on the floor otherwise, next interval will kick in
5006
}, timeout);
5007
},getMimetype:function(name) {
5008
return {
5009
'jpg': 'image/jpeg',
5010
'jpeg': 'image/jpeg',
5011
'png': 'image/png',
5012
'bmp': 'image/bmp',
5013
'ogg': 'audio/ogg',
5014
'wav': 'audio/wav',
5015
'mp3': 'audio/mpeg'
5016
}[name.substr(name.lastIndexOf('.')+1)];
5017
},getUserMedia:function(func) {
5018
if(!window.getUserMedia) {
5019
window.getUserMedia = navigator['getUserMedia'] ||
5020
navigator['mozGetUserMedia'];
5021
}
5022
window.getUserMedia(func);
5023
},getMovementX:function(event) {
5024
return event['movementX'] ||
5025
event['mozMovementX'] ||
5026
event['webkitMovementX'] ||
5027
0;
5028
},getMovementY:function(event) {
5029
return event['movementY'] ||
5030
event['mozMovementY'] ||
5031
event['webkitMovementY'] ||
5032
0;
5033
},getMouseWheelDelta:function(event) {
5034
var delta = 0;
5035
switch (event.type) {
5036
case 'DOMMouseScroll':
5037
// 3 lines make up a step
5038
delta = event.detail / 3;
5039
break;
5040
case 'mousewheel':
5041
// 120 units make up a step
5042
delta = event.wheelDelta / 120;
5043
break;
5044
case 'wheel':
5045
delta = event.deltaY
5046
switch(event.deltaMode) {
5047
case 0:
5048
// DOM_DELTA_PIXEL: 100 pixels make up a step
5049
delta /= 100;
5050
break;
5051
case 1:
5052
// DOM_DELTA_LINE: 3 lines make up a step
5053
delta /= 3;
5054
break;
5055
case 2:
5056
// DOM_DELTA_PAGE: A page makes up 80 steps
5057
delta *= 80;
5058
break;
5059
default:
5060
throw 'unrecognized mouse wheel delta mode: ' + event.deltaMode;
5061
}
5062
break;
5063
default:
5064
throw 'unrecognized mouse wheel event: ' + event.type;
5065
}
5066
return delta;
5067
},mouseX:0,mouseY:0,mouseMovementX:0,mouseMovementY:0,touches:{},lastTouches:{},calculateMouseEvent:function(event) { // event should be mousemove, mousedown or mouseup
5068
if (Browser.pointerLock) {
5069
// When the pointer is locked, calculate the coordinates
5070
// based on the movement of the mouse.
5071
// Workaround for Firefox bug 764498
5072
if (event.type != 'mousemove' &&
5073
('mozMovementX' in event)) {
5074
Browser.mouseMovementX = Browser.mouseMovementY = 0;
5075
} else {
5076
Browser.mouseMovementX = Browser.getMovementX(event);
5077
Browser.mouseMovementY = Browser.getMovementY(event);
5078
}
5079
5080
// check if SDL is available
5081
if (typeof SDL != "undefined") {
5082
Browser.mouseX = SDL.mouseX + Browser.mouseMovementX;
5083
Browser.mouseY = SDL.mouseY + Browser.mouseMovementY;
5084
} else {
5085
// just add the mouse delta to the current absolut mouse position
5086
// FIXME: ideally this should be clamped against the canvas size and zero
5087
Browser.mouseX += Browser.mouseMovementX;
5088
Browser.mouseY += Browser.mouseMovementY;
5089
}
5090
} else {
5091
// Otherwise, calculate the movement based on the changes
5092
// in the coordinates.
5093
var rect = Module["canvas"].getBoundingClientRect();
5094
var cw = Module["canvas"].width;
5095
var ch = Module["canvas"].height;
5096
5097
// Neither .scrollX or .pageXOffset are defined in a spec, but
5098
// we prefer .scrollX because it is currently in a spec draft.
5099
// (see: http://www.w3.org/TR/2013/WD-cssom-view-20131217/)
5100
var scrollX = ((typeof window.scrollX !== 'undefined') ? window.scrollX : window.pageXOffset);
5101
var scrollY = ((typeof window.scrollY !== 'undefined') ? window.scrollY : window.pageYOffset);
5102
// If this assert lands, it's likely because the browser doesn't support scrollX or pageXOffset
5103
// and we have no viable fallback.
5104
assert((typeof scrollX !== 'undefined') && (typeof scrollY !== 'undefined'), 'Unable to retrieve scroll position, mouse positions likely broken.');
5105
5106
if (event.type === 'touchstart' || event.type === 'touchend' || event.type === 'touchmove') {
5107
var touch = event.touch;
5108
if (touch === undefined) {
5109
return; // the "touch" property is only defined in SDL
5110
5111
}
5112
var adjustedX = touch.pageX - (scrollX + rect.left);
5113
var adjustedY = touch.pageY - (scrollY + rect.top);
5114
5115
adjustedX = adjustedX * (cw / rect.width);
5116
adjustedY = adjustedY * (ch / rect.height);
5117
5118
var coords = { x: adjustedX, y: adjustedY };
5119
5120
if (event.type === 'touchstart') {
5121
Browser.lastTouches[touch.identifier] = coords;
5122
Browser.touches[touch.identifier] = coords;
5123
} else if (event.type === 'touchend' || event.type === 'touchmove') {
5124
var last = Browser.touches[touch.identifier];
5125
if (!last) last = coords;
5126
Browser.lastTouches[touch.identifier] = last;
5127
Browser.touches[touch.identifier] = coords;
5128
}
5129
return;
5130
}
5131
5132
var x = event.pageX - (scrollX + rect.left);
5133
var y = event.pageY - (scrollY + rect.top);
5134
5135
// the canvas might be CSS-scaled compared to its backbuffer;
5136
// SDL-using content will want mouse coordinates in terms
5137
// of backbuffer units.
5138
x = x * (cw / rect.width);
5139
y = y * (ch / rect.height);
5140
5141
Browser.mouseMovementX = x - Browser.mouseX;
5142
Browser.mouseMovementY = y - Browser.mouseY;
5143
Browser.mouseX = x;
5144
Browser.mouseY = y;
5145
}
5146
},asyncLoad:function(url, onload, onerror, noRunDep) {
5147
var dep = !noRunDep ? getUniqueRunDependency('al ' + url) : '';
5148
readAsync(url, function(arrayBuffer) {
5149
assert(arrayBuffer, 'Loading data file "' + url + '" failed (no arrayBuffer).');
5150
onload(new Uint8Array(arrayBuffer));
5151
if (dep) removeRunDependency(dep);
5152
}, function(event) {
5153
if (onerror) {
5154
onerror();
5155
} else {
5156
throw 'Loading data file "' + url + '" failed.';
5157
}
5158
});
5159
if (dep) addRunDependency(dep);
5160
},resizeListeners:[],updateResizeListeners:function() {
5161
var canvas = Module['canvas'];
5162
Browser.resizeListeners.forEach(function(listener) {
5163
listener(canvas.width, canvas.height);
5164
});
5165
},setCanvasSize:function(width, height, noUpdates) {
5166
var canvas = Module['canvas'];
5167
Browser.updateCanvasDimensions(canvas, width, height);
5168
if (!noUpdates) Browser.updateResizeListeners();
5169
},windowedWidth:0,windowedHeight:0,setFullscreenCanvasSize:function() {
5170
// check if SDL is available
5171
if (typeof SDL != "undefined") {
5172
var flags = HEAPU32[((SDL.screen)>>2)];
5173
flags = flags | 0x00800000; // set SDL_FULLSCREEN flag
5174
HEAP32[((SDL.screen)>>2)]=flags
5175
}
5176
Browser.updateCanvasDimensions(Module['canvas']);
5177
Browser.updateResizeListeners();
5178
},setWindowedCanvasSize:function() {
5179
// check if SDL is available
5180
if (typeof SDL != "undefined") {
5181
var flags = HEAPU32[((SDL.screen)>>2)];
5182
flags = flags & ~0x00800000; // clear SDL_FULLSCREEN flag
5183
HEAP32[((SDL.screen)>>2)]=flags
5184
}
5185
Browser.updateCanvasDimensions(Module['canvas']);
5186
Browser.updateResizeListeners();
5187
},updateCanvasDimensions:function(canvas, wNative, hNative) {
5188
if (wNative && hNative) {
5189
canvas.widthNative = wNative;
5190
canvas.heightNative = hNative;
5191
} else {
5192
wNative = canvas.widthNative;
5193
hNative = canvas.heightNative;
5194
}
5195
var w = wNative;
5196
var h = hNative;
5197
if (Module['forcedAspectRatio'] && Module['forcedAspectRatio'] > 0) {
5198
if (w/h < Module['forcedAspectRatio']) {
5199
w = Math.round(h * Module['forcedAspectRatio']);
5200
} else {
5201
h = Math.round(w / Module['forcedAspectRatio']);
5202
}
5203
}
5204
if (((document['fullscreenElement'] || document['mozFullScreenElement'] ||
5205
document['msFullscreenElement'] || document['webkitFullscreenElement'] ||
5206
document['webkitCurrentFullScreenElement']) === canvas.parentNode) && (typeof screen != 'undefined')) {
5207
var factor = Math.min(screen.width / w, screen.height / h);
5208
w = Math.round(w * factor);
5209
h = Math.round(h * factor);
5210
}
5211
if (Browser.resizeCanvas) {
5212
if (canvas.width != w) canvas.width = w;
5213
if (canvas.height != h) canvas.height = h;
5214
if (typeof canvas.style != 'undefined') {
5215
canvas.style.removeProperty( "width");
5216
canvas.style.removeProperty("height");
5217
}
5218
} else {
5219
if (canvas.width != wNative) canvas.width = wNative;
5220
if (canvas.height != hNative) canvas.height = hNative;
5221
if (typeof canvas.style != 'undefined') {
5222
if (w != wNative || h != hNative) {
5223
canvas.style.setProperty( "width", w + "px", "important");
5224
canvas.style.setProperty("height", h + "px", "important");
5225
} else {
5226
canvas.style.removeProperty( "width");
5227
canvas.style.removeProperty("height");
5228
}
5229
}
5230
}
5231
},wgetRequests:{},nextWgetRequestHandle:0,getNextWgetRequestHandle:function() {
5232
var handle = Browser.nextWgetRequestHandle;
5233
Browser.nextWgetRequestHandle++;
5234
return handle;
5235
}};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) {
5236
EGL.errorCode = code;
5237
},chooseConfig:function(display, attribList, config, config_size, numConfigs) {
5238
if (display != 62000 /* Magic ID for Emscripten 'default display' */) {
5239
EGL.setErrorCode(0x3008 /* EGL_BAD_DISPLAY */);
5240
return 0;
5241
}
5242
5243
if (attribList) {
5244
// read attribList if it is non-null
5245
for(;;) {
5246
var param = HEAP32[((attribList)>>2)];
5247
if (param == 0x3021 /*EGL_ALPHA_SIZE*/) {
5248
var alphaSize = HEAP32[(((attribList)+(4))>>2)];
5249
EGL.contextAttributes.alpha = (alphaSize > 0);
5250
} else if (param == 0x3025 /*EGL_DEPTH_SIZE*/) {
5251
var depthSize = HEAP32[(((attribList)+(4))>>2)];
5252
EGL.contextAttributes.depth = (depthSize > 0);
5253
} else if (param == 0x3026 /*EGL_STENCIL_SIZE*/) {
5254
var stencilSize = HEAP32[(((attribList)+(4))>>2)];
5255
EGL.contextAttributes.stencil = (stencilSize > 0);
5256
} else if (param == 0x3031 /*EGL_SAMPLES*/) {
5257
var samples = HEAP32[(((attribList)+(4))>>2)];
5258
EGL.contextAttributes.antialias = (samples > 0);
5259
} else if (param == 0x3032 /*EGL_SAMPLE_BUFFERS*/) {
5260
var samples = HEAP32[(((attribList)+(4))>>2)];
5261
EGL.contextAttributes.antialias = (samples == 1);
5262
} else if (param == 0x3100 /*EGL_CONTEXT_PRIORITY_LEVEL_IMG*/) {
5263
var requestedPriority = HEAP32[(((attribList)+(4))>>2)];
5264
EGL.contextAttributes.lowLatency = (requestedPriority != 0x3103 /*EGL_CONTEXT_PRIORITY_LOW_IMG*/);
5265
} else if (param == 0x3038 /*EGL_NONE*/) {
5266
break;
5267
}
5268
attribList += 8;
5269
}
5270
}
5271
5272
if ((!config || !config_size) && !numConfigs) {
5273
EGL.setErrorCode(0x300C /* EGL_BAD_PARAMETER */);
5274
return 0;
5275
}
5276
if (numConfigs) {
5277
HEAP32[((numConfigs)>>2)]=1; // Total number of supported configs: 1.
5278
}
5279
if (config && config_size > 0) {
5280
HEAP32[((config)>>2)]=62002;
5281
}
5282
5283
EGL.setErrorCode(0x3000 /* EGL_SUCCESS */);
5284
return 1;
5285
}};function _eglBindAPI(api) {
5286
if (api == 0x30A0 /* EGL_OPENGL_ES_API */) {
5287
EGL.setErrorCode(0x3000 /* EGL_SUCCESS */);
5288
return 1;
5289
} else { // if (api == 0x30A1 /* EGL_OPENVG_API */ || api == 0x30A2 /* EGL_OPENGL_API */) {
5290
EGL.setErrorCode(0x300C /* EGL_BAD_PARAMETER */);
5291
return 0;
5292
}
5293
}
5294
5295
function _eglChooseConfig(display, attrib_list, configs, config_size, numConfigs) {
5296
return EGL.chooseConfig(display, attrib_list, configs, config_size, numConfigs);
5297
}
5298
5299
5300
5301
function __webgl_acquireInstancedArraysExtension(ctx) {
5302
// Extension available in WebGL 1 from Firefox 26 and Google Chrome 30 onwards. Core feature in WebGL 2.
5303
var ext = ctx.getExtension('ANGLE_instanced_arrays');
5304
if (ext) {
5305
ctx['vertexAttribDivisor'] = function(index, divisor) { ext['vertexAttribDivisorANGLE'](index, divisor); };
5306
ctx['drawArraysInstanced'] = function(mode, first, count, primcount) { ext['drawArraysInstancedANGLE'](mode, first, count, primcount); };
5307
ctx['drawElementsInstanced'] = function(mode, count, type, indices, primcount) { ext['drawElementsInstancedANGLE'](mode, count, type, indices, primcount); };
5308
}
5309
}
5310
5311
function __webgl_acquireVertexArrayObjectExtension(ctx) {
5312
// Extension available in WebGL 1 from Firefox 25 and WebKit 536.28/desktop Safari 6.0.3 onwards. Core feature in WebGL 2.
5313
var ext = ctx.getExtension('OES_vertex_array_object');
5314
if (ext) {
5315
ctx['createVertexArray'] = function() { return ext['createVertexArrayOES'](); };
5316
ctx['deleteVertexArray'] = function(vao) { ext['deleteVertexArrayOES'](vao); };
5317
ctx['bindVertexArray'] = function(vao) { ext['bindVertexArrayOES'](vao); };
5318
ctx['isVertexArray'] = function(vao) { return ext['isVertexArrayOES'](vao); };
5319
}
5320
}
5321
5322
function __webgl_acquireDrawBuffersExtension(ctx) {
5323
// Extension available in WebGL 1 from Firefox 28 onwards. Core feature in WebGL 2.
5324
var ext = ctx.getExtension('WEBGL_draw_buffers');
5325
if (ext) {
5326
ctx['drawBuffers'] = function(n, bufs) { ext['drawBuffersWEBGL'](n, bufs); };
5327
}
5328
}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() {
5329
var miniTempFloatBuffer = new Float32Array(GL.MINI_TEMP_BUFFER_SIZE);
5330
for (var i = 0; i < GL.MINI_TEMP_BUFFER_SIZE; i++) {
5331
GL.miniTempBufferFloatViews[i] = miniTempFloatBuffer.subarray(0, i+1);
5332
}
5333
5334
var miniTempIntBuffer = new Int32Array(GL.MINI_TEMP_BUFFER_SIZE);
5335
for (var i = 0; i < GL.MINI_TEMP_BUFFER_SIZE; i++) {
5336
GL.miniTempBufferIntViews[i] = miniTempIntBuffer.subarray(0, i+1);
5337
}
5338
},recordError:function recordError(errorCode) {
5339
if (!GL.lastError) {
5340
GL.lastError = errorCode;
5341
}
5342
},getNewId:function(table) {
5343
var ret = GL.counter++;
5344
for (var i = table.length; i < ret; i++) {
5345
table[i] = null;
5346
}
5347
return ret;
5348
},MINI_TEMP_BUFFER_SIZE:256,miniTempBufferFloatViews:[0],miniTempBufferIntViews:[0],getSource:function(shader, count, string, length) {
5349
var source = '';
5350
for (var i = 0; i < count; ++i) {
5351
var len = length ? HEAP32[(((length)+(i*4))>>2)] : -1;
5352
source += UTF8ToString(HEAP32[(((string)+(i*4))>>2)], len < 0 ? undefined : len);
5353
}
5354
return source;
5355
},createContext:function(canvas, webGLContextAttributes) {
5356
5357
5358
5359
5360
5361
var ctx =
5362
(canvas.getContext("webgl", webGLContextAttributes)
5363
// https://caniuse.com/#feat=webgl
5364
);
5365
5366
5367
if (!ctx) return 0;
5368
5369
var handle = GL.registerContext(ctx, webGLContextAttributes);
5370
5371
5372
5373
return handle;
5374
},registerContext:function(ctx, webGLContextAttributes) {
5375
var handle = _malloc(8); // Make space on the heap to store GL context attributes that need to be accessible as shared between threads.
5376
var context = {
5377
handle: handle,
5378
attributes: webGLContextAttributes,
5379
version: webGLContextAttributes.majorVersion,
5380
GLctx: ctx
5381
};
5382
5383
5384
// Store the created context object so that we can access the context given a canvas without having to pass the parameters again.
5385
if (ctx.canvas) ctx.canvas.GLctxObject = context;
5386
GL.contexts[handle] = context;
5387
if (typeof webGLContextAttributes.enableExtensionsByDefault === 'undefined' || webGLContextAttributes.enableExtensionsByDefault) {
5388
GL.initExtensions(context);
5389
}
5390
5391
5392
5393
5394
return handle;
5395
},makeContextCurrent:function(contextHandle) {
5396
5397
GL.currentContext = GL.contexts[contextHandle]; // Active Emscripten GL layer context object.
5398
Module.ctx = GLctx = GL.currentContext && GL.currentContext.GLctx; // Active WebGL context object.
5399
return !(contextHandle && !GLctx);
5400
},getContext:function(contextHandle) {
5401
return GL.contexts[contextHandle];
5402
},deleteContext:function(contextHandle) {
5403
if (GL.currentContext === GL.contexts[contextHandle]) GL.currentContext = null;
5404
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.
5405
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.
5406
_free(GL.contexts[contextHandle].handle);
5407
GL.contexts[contextHandle] = null;
5408
},initExtensions:function(context) {
5409
// If this function is called without a specific context object, init the extensions of the currently active context.
5410
if (!context) context = GL.currentContext;
5411
5412
if (context.initExtensionsDone) return;
5413
context.initExtensionsDone = true;
5414
5415
var GLctx = context.GLctx;
5416
5417
// Detect the presence of a few extensions manually, this GL interop layer itself will need to know if they exist.
5418
5419
if (context.version < 2) {
5420
__webgl_acquireInstancedArraysExtension(GLctx);
5421
__webgl_acquireVertexArrayObjectExtension(GLctx);
5422
__webgl_acquireDrawBuffersExtension(GLctx);
5423
}
5424
5425
GLctx.disjointTimerQueryExt = GLctx.getExtension("EXT_disjoint_timer_query");
5426
5427
// These are the 'safe' feature-enabling extensions that don't add any performance impact related to e.g. debugging, and
5428
// should be enabled by default so that client GLES2/GL code will not need to go through extra hoops to get its stuff working.
5429
// As new extensions are ratified at http://www.khronos.org/registry/webgl/extensions/ , feel free to add your new extensions
5430
// here, as long as they don't produce a performance impact for users that might not be using those extensions.
5431
// E.g. debugging-related extensions should probably be off by default.
5432
var automaticallyEnabledExtensions = [ // Khronos ratified WebGL extensions ordered by number (no debug extensions):
5433
"OES_texture_float", "OES_texture_half_float", "OES_standard_derivatives",
5434
"OES_vertex_array_object", "WEBGL_compressed_texture_s3tc", "WEBGL_depth_texture",
5435
"OES_element_index_uint", "EXT_texture_filter_anisotropic", "EXT_frag_depth",
5436
"WEBGL_draw_buffers", "ANGLE_instanced_arrays", "OES_texture_float_linear",
5437
"OES_texture_half_float_linear", "EXT_blend_minmax", "EXT_shader_texture_lod",
5438
"EXT_texture_norm16",
5439
// Community approved WebGL extensions ordered by number:
5440
"WEBGL_compressed_texture_pvrtc", "EXT_color_buffer_half_float", "WEBGL_color_buffer_float",
5441
"EXT_sRGB", "WEBGL_compressed_texture_etc1", "EXT_disjoint_timer_query",
5442
"WEBGL_compressed_texture_etc", "WEBGL_compressed_texture_astc", "EXT_color_buffer_float",
5443
"WEBGL_compressed_texture_s3tc_srgb", "EXT_disjoint_timer_query_webgl2",
5444
// Old style prefixed forms of extensions (but still currently used on e.g. iPhone Xs as
5445
// tested on iOS 12.4.1):
5446
"WEBKIT_WEBGL_compressed_texture_pvrtc"];
5447
5448
function shouldEnableAutomatically(extension) {
5449
var ret = false;
5450
automaticallyEnabledExtensions.forEach(function(include) {
5451
if (extension.indexOf(include) != -1) {
5452
ret = true;
5453
}
5454
});
5455
return ret;
5456
}
5457
5458
var exts = GLctx.getSupportedExtensions() || []; // .getSupportedExtensions() can return null if context is lost, so coerce to empty array.
5459
exts.forEach(function(ext) {
5460
if (automaticallyEnabledExtensions.indexOf(ext) != -1) {
5461
GLctx.getExtension(ext); // Calling .getExtension enables that extension permanently, no need to store the return value to be enabled.
5462
}
5463
});
5464
},populateUniformTable:function(program) {
5465
var p = GL.programs[program];
5466
var ptable = GL.programInfos[program] = {
5467
uniforms: {},
5468
maxUniformLength: 0, // This is eagerly computed below, since we already enumerate all uniforms anyway.
5469
maxAttributeLength: -1, // This is lazily computed and cached, computed when/if first asked, "-1" meaning not computed yet.
5470
maxUniformBlockNameLength: -1 // Lazily computed as well
5471
};
5472
5473
var utable = ptable.uniforms;
5474
// A program's uniform table maps the string name of an uniform to an integer location of that uniform.
5475
// The global GL.uniforms map maps integer locations to WebGLUniformLocations.
5476
var numUniforms = GLctx.getProgramParameter(p, 0x8B86/*GL_ACTIVE_UNIFORMS*/);
5477
for (var i = 0; i < numUniforms; ++i) {
5478
var u = GLctx.getActiveUniform(p, i);
5479
5480
var name = u.name;
5481
ptable.maxUniformLength = Math.max(ptable.maxUniformLength, name.length+1);
5482
5483
// If we are dealing with an array, e.g. vec4 foo[3], strip off the array index part to canonicalize that "foo", "foo[]",
5484
// and "foo[0]" will mean the same. Loop below will populate foo[1] and foo[2].
5485
if (name.slice(-1) == ']') {
5486
name = name.slice(0, name.lastIndexOf('['));
5487
}
5488
5489
// Optimize memory usage slightly: If we have an array of uniforms, e.g. 'vec3 colors[3];', then
5490
// only store the string 'colors' in utable, and 'colors[0]', 'colors[1]' and 'colors[2]' will be parsed as 'colors'+i.
5491
// Note that for the GL.uniforms table, we still need to fetch the all WebGLUniformLocations for all the indices.
5492
var loc = GLctx.getUniformLocation(p, name);
5493
if (loc) {
5494
var id = GL.getNewId(GL.uniforms);
5495
utable[name] = [u.size, id];
5496
GL.uniforms[id] = loc;
5497
5498
for (var j = 1; j < u.size; ++j) {
5499
var n = name + '['+j+']';
5500
loc = GLctx.getUniformLocation(p, n);
5501
id = GL.getNewId(GL.uniforms);
5502
5503
GL.uniforms[id] = loc;
5504
}
5505
}
5506
}
5507
}};function _eglCreateContext(display, config, hmm, contextAttribs) {
5508
if (display != 62000 /* Magic ID for Emscripten 'default display' */) {
5509
EGL.setErrorCode(0x3008 /* EGL_BAD_DISPLAY */);
5510
return 0;
5511
}
5512
5513
// EGL 1.4 spec says default EGL_CONTEXT_CLIENT_VERSION is GLES1, but this is not supported by Emscripten.
5514
// So user must pass EGL_CONTEXT_CLIENT_VERSION == 2 to initialize EGL.
5515
var glesContextVersion = 1;
5516
for(;;) {
5517
var param = HEAP32[((contextAttribs)>>2)];
5518
if (param == 0x3098 /*EGL_CONTEXT_CLIENT_VERSION*/) {
5519
glesContextVersion = HEAP32[(((contextAttribs)+(4))>>2)];
5520
} else if (param == 0x3038 /*EGL_NONE*/) {
5521
break;
5522
} else {
5523
/* EGL1.4 specifies only EGL_CONTEXT_CLIENT_VERSION as supported attribute */
5524
EGL.setErrorCode(0x3004 /*EGL_BAD_ATTRIBUTE*/);
5525
return 0;
5526
}
5527
contextAttribs += 8;
5528
}
5529
if (glesContextVersion != 2) {
5530
EGL.setErrorCode(0x3005 /* EGL_BAD_CONFIG */);
5531
return 0; /* EGL_NO_CONTEXT */
5532
}
5533
5534
EGL.contextAttributes.majorVersion = glesContextVersion - 1; // WebGL 1 is GLES 2, WebGL2 is GLES3
5535
EGL.contextAttributes.minorVersion = 0;
5536
5537
EGL.context = GL.createContext(Module['canvas'], EGL.contextAttributes);
5538
5539
if (EGL.context != 0) {
5540
EGL.setErrorCode(0x3000 /* EGL_SUCCESS */);
5541
5542
// Run callbacks so that GL emulation works
5543
GL.makeContextCurrent(EGL.context);
5544
Module.useWebGL = true;
5545
Browser.moduleContextCreatedCallbacks.forEach(function(callback) { callback() });
5546
5547
// Note: This function only creates a context, but it shall not make it active.
5548
GL.makeContextCurrent(null);
5549
return 62004; // Magic ID for Emscripten EGLContext
5550
} else {
5551
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.
5552
return 0; /* EGL_NO_CONTEXT */
5553
}
5554
}
5555
5556
function _eglCreateWindowSurface(display, config, win, attrib_list) {
5557
if (display != 62000 /* Magic ID for Emscripten 'default display' */) {
5558
EGL.setErrorCode(0x3008 /* EGL_BAD_DISPLAY */);
5559
return 0;
5560
}
5561
if (config != 62002 /* Magic ID for the only EGLConfig supported by Emscripten */) {
5562
EGL.setErrorCode(0x3005 /* EGL_BAD_CONFIG */);
5563
return 0;
5564
}
5565
// TODO: Examine attrib_list! Parameters that can be present there are:
5566
// - EGL_RENDER_BUFFER (must be EGL_BACK_BUFFER)
5567
// - EGL_VG_COLORSPACE (can't be set)
5568
// - EGL_VG_ALPHA_FORMAT (can't be set)
5569
EGL.setErrorCode(0x3000 /* EGL_SUCCESS */);
5570
return 62006; /* Magic ID for Emscripten 'default surface' */
5571
}
5572
5573
function _eglDestroyContext(display, context) {
5574
if (display != 62000 /* Magic ID for Emscripten 'default display' */) {
5575
EGL.setErrorCode(0x3008 /* EGL_BAD_DISPLAY */);
5576
return 0;
5577
}
5578
if (context != 62004 /* Magic ID for Emscripten EGLContext */) {
5579
EGL.setErrorCode(0x3006 /* EGL_BAD_CONTEXT */);
5580
return 0;
5581
}
5582
5583
GL.deleteContext(EGL.context);
5584
EGL.setErrorCode(0x3000 /* EGL_SUCCESS */);
5585
if (EGL.currentContext == context) {
5586
EGL.currentContext = 0;
5587
}
5588
return 1 /* EGL_TRUE */;
5589
}
5590
5591
function _eglDestroySurface(display, surface) {
5592
if (display != 62000 /* Magic ID for Emscripten 'default display' */) {
5593
EGL.setErrorCode(0x3008 /* EGL_BAD_DISPLAY */);
5594
return 0;
5595
}
5596
if (surface != 62006 /* Magic ID for the only EGLSurface supported by Emscripten */) {
5597
EGL.setErrorCode(0x300D /* EGL_BAD_SURFACE */);
5598
return 1;
5599
}
5600
if (EGL.currentReadSurface == surface) {
5601
EGL.currentReadSurface = 0;
5602
}
5603
if (EGL.currentDrawSurface == surface) {
5604
EGL.currentDrawSurface = 0;
5605
}
5606
EGL.setErrorCode(0x3000 /* EGL_SUCCESS */);
5607
return 1; /* Magic ID for Emscripten 'default surface' */
5608
}
5609
5610
function _eglGetConfigAttrib(display, config, attribute, value) {
5611
if (display != 62000 /* Magic ID for Emscripten 'default display' */) {
5612
EGL.setErrorCode(0x3008 /* EGL_BAD_DISPLAY */);
5613
return 0;
5614
}
5615
if (config != 62002 /* Magic ID for the only EGLConfig supported by Emscripten */) {
5616
EGL.setErrorCode(0x3005 /* EGL_BAD_CONFIG */);
5617
return 0;
5618
}
5619
if (!value) {
5620
EGL.setErrorCode(0x300C /* EGL_BAD_PARAMETER */);
5621
return 0;
5622
}
5623
EGL.setErrorCode(0x3000 /* EGL_SUCCESS */);
5624
switch(attribute) {
5625
case 0x3020: // EGL_BUFFER_SIZE
5626
HEAP32[((value)>>2)]=EGL.contextAttributes.alpha ? 32 : 24;
5627
return 1;
5628
case 0x3021: // EGL_ALPHA_SIZE
5629
HEAP32[((value)>>2)]=EGL.contextAttributes.alpha ? 8 : 0;
5630
return 1;
5631
case 0x3022: // EGL_BLUE_SIZE
5632
HEAP32[((value)>>2)]=8;
5633
return 1;
5634
case 0x3023: // EGL_GREEN_SIZE
5635
HEAP32[((value)>>2)]=8;
5636
return 1;
5637
case 0x3024: // EGL_RED_SIZE
5638
HEAP32[((value)>>2)]=8;
5639
return 1;
5640
case 0x3025: // EGL_DEPTH_SIZE
5641
HEAP32[((value)>>2)]=EGL.contextAttributes.depth ? 24 : 0;
5642
return 1;
5643
case 0x3026: // EGL_STENCIL_SIZE
5644
HEAP32[((value)>>2)]=EGL.contextAttributes.stencil ? 8 : 0;
5645
return 1;
5646
case 0x3027: // EGL_CONFIG_CAVEAT
5647
// We can return here one of EGL_NONE (0x3038), EGL_SLOW_CONFIG (0x3050) or EGL_NON_CONFORMANT_CONFIG (0x3051).
5648
HEAP32[((value)>>2)]=0x3038;
5649
return 1;
5650
case 0x3028: // EGL_CONFIG_ID
5651
HEAP32[((value)>>2)]=62002;
5652
return 1;
5653
case 0x3029: // EGL_LEVEL
5654
HEAP32[((value)>>2)]=0;
5655
return 1;
5656
case 0x302A: // EGL_MAX_PBUFFER_HEIGHT
5657
HEAP32[((value)>>2)]=4096;
5658
return 1;
5659
case 0x302B: // EGL_MAX_PBUFFER_PIXELS
5660
HEAP32[((value)>>2)]=16777216;
5661
return 1;
5662
case 0x302C: // EGL_MAX_PBUFFER_WIDTH
5663
HEAP32[((value)>>2)]=4096;
5664
return 1;
5665
case 0x302D: // EGL_NATIVE_RENDERABLE
5666
HEAP32[((value)>>2)]=0;
5667
return 1;
5668
case 0x302E: // EGL_NATIVE_VISUAL_ID
5669
HEAP32[((value)>>2)]=0;
5670
return 1;
5671
case 0x302F: // EGL_NATIVE_VISUAL_TYPE
5672
HEAP32[((value)>>2)]=0x3038;
5673
return 1;
5674
case 0x3031: // EGL_SAMPLES
5675
HEAP32[((value)>>2)]=EGL.contextAttributes.antialias ? 4 : 0;
5676
return 1;
5677
case 0x3032: // EGL_SAMPLE_BUFFERS
5678
HEAP32[((value)>>2)]=EGL.contextAttributes.antialias ? 1 : 0;
5679
return 1;
5680
case 0x3033: // EGL_SURFACE_TYPE
5681
HEAP32[((value)>>2)]=0x4;
5682
return 1;
5683
case 0x3034: // EGL_TRANSPARENT_TYPE
5684
// If this returns EGL_TRANSPARENT_RGB (0x3052), transparency is used through color-keying. No such thing applies to Emscripten canvas.
5685
HEAP32[((value)>>2)]=0x3038;
5686
return 1;
5687
case 0x3035: // EGL_TRANSPARENT_BLUE_VALUE
5688
case 0x3036: // EGL_TRANSPARENT_GREEN_VALUE
5689
case 0x3037: // EGL_TRANSPARENT_RED_VALUE
5690
// "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."
5691
HEAP32[((value)>>2)]=-1;
5692
return 1;
5693
case 0x3039: // EGL_BIND_TO_TEXTURE_RGB
5694
case 0x303A: // EGL_BIND_TO_TEXTURE_RGBA
5695
HEAP32[((value)>>2)]=0;
5696
return 1;
5697
case 0x303B: // EGL_MIN_SWAP_INTERVAL
5698
HEAP32[((value)>>2)]=0;
5699
return 1;
5700
case 0x303C: // EGL_MAX_SWAP_INTERVAL
5701
HEAP32[((value)>>2)]=1;
5702
return 1;
5703
case 0x303D: // EGL_LUMINANCE_SIZE
5704
case 0x303E: // EGL_ALPHA_MASK_SIZE
5705
HEAP32[((value)>>2)]=0;
5706
return 1;
5707
case 0x303F: // EGL_COLOR_BUFFER_TYPE
5708
// EGL has two types of buffers: EGL_RGB_BUFFER and EGL_LUMINANCE_BUFFER.
5709
HEAP32[((value)>>2)]=0x308E;
5710
return 1;
5711
case 0x3040: // EGL_RENDERABLE_TYPE
5712
// A bit combination of EGL_OPENGL_ES_BIT,EGL_OPENVG_BIT,EGL_OPENGL_ES2_BIT and EGL_OPENGL_BIT.
5713
HEAP32[((value)>>2)]=0x4;
5714
return 1;
5715
case 0x3042: // EGL_CONFORMANT
5716
// "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."
5717
HEAP32[((value)>>2)]=0;
5718
return 1;
5719
default:
5720
EGL.setErrorCode(0x3004 /* EGL_BAD_ATTRIBUTE */);
5721
return 0;
5722
}
5723
}
5724
5725
function _eglGetDisplay(nativeDisplayType) {
5726
EGL.setErrorCode(0x3000 /* EGL_SUCCESS */);
5727
// Note: As a 'conformant' implementation of EGL, we would prefer to init here only if the user
5728
// calls this function with EGL_DEFAULT_DISPLAY. Other display IDs would be preferred to be unsupported
5729
// and EGL_NO_DISPLAY returned. Uncomment the following code lines to do this.
5730
// Instead, an alternative route has been preferred, namely that the Emscripten EGL implementation
5731
// "emulates" X11, and eglGetDisplay is expected to accept/receive a pointer to an X11 Display object.
5732
// Therefore, be lax and allow anything to be passed in, and return the magic handle to our default EGLDisplay object.
5733
5734
// if (nativeDisplayType == 0 /* EGL_DEFAULT_DISPLAY */) {
5735
return 62000; // Magic ID for Emscripten 'default display'
5736
// }
5737
// else
5738
// return 0; // EGL_NO_DISPLAY
5739
}
5740
5741
function _eglGetError() {
5742
return EGL.errorCode;
5743
}
5744
5745
function _eglGetProcAddress(name_) {
5746
return _emscripten_GetProcAddress(name_);
5747
}
5748
5749
function _eglInitialize(display, majorVersion, minorVersion) {
5750
if (display == 62000 /* Magic ID for Emscripten 'default display' */) {
5751
if (majorVersion) {
5752
HEAP32[((majorVersion)>>2)]=1; // Advertise EGL Major version: '1'
5753
}
5754
if (minorVersion) {
5755
HEAP32[((minorVersion)>>2)]=4; // Advertise EGL Minor version: '4'
5756
}
5757
EGL.defaultDisplayInitialized = true;
5758
EGL.setErrorCode(0x3000 /* EGL_SUCCESS */);
5759
return 1;
5760
}
5761
else {
5762
EGL.setErrorCode(0x3008 /* EGL_BAD_DISPLAY */);
5763
return 0;
5764
}
5765
}
5766
5767
function _eglMakeCurrent(display, draw, read, context) {
5768
if (display != 62000 /* Magic ID for Emscripten 'default display' */) {
5769
EGL.setErrorCode(0x3008 /* EGL_BAD_DISPLAY */);
5770
return 0 /* EGL_FALSE */;
5771
}
5772
//\todo An EGL_NOT_INITIALIZED error is generated if EGL is not initialized for dpy.
5773
if (context != 0 && context != 62004 /* Magic ID for Emscripten EGLContext */) {
5774
EGL.setErrorCode(0x3006 /* EGL_BAD_CONTEXT */);
5775
return 0;
5776
}
5777
if ((read != 0 && read != 62006) || (draw != 0 && draw != 62006 /* Magic ID for Emscripten 'default surface' */)) {
5778
EGL.setErrorCode(0x300D /* EGL_BAD_SURFACE */);
5779
return 0;
5780
}
5781
5782
GL.makeContextCurrent(context ? EGL.context : null);
5783
5784
EGL.currentContext = context;
5785
EGL.currentDrawSurface = draw;
5786
EGL.currentReadSurface = read;
5787
EGL.setErrorCode(0x3000 /* EGL_SUCCESS */);
5788
return 1 /* EGL_TRUE */;
5789
}
5790
5791
function _eglQueryString(display, name) {
5792
if (display != 62000 /* Magic ID for Emscripten 'default display' */) {
5793
EGL.setErrorCode(0x3008 /* EGL_BAD_DISPLAY */);
5794
return 0;
5795
}
5796
//\todo An EGL_NOT_INITIALIZED error is generated if EGL is not initialized for dpy.
5797
EGL.setErrorCode(0x3000 /* EGL_SUCCESS */);
5798
if (EGL.stringCache[name]) return EGL.stringCache[name];
5799
var ret;
5800
switch(name) {
5801
case 0x3053 /* EGL_VENDOR */: ret = allocateUTF8("Emscripten"); break;
5802
case 0x3054 /* EGL_VERSION */: ret = allocateUTF8("1.4 Emscripten EGL"); break;
5803
case 0x3055 /* EGL_EXTENSIONS */: ret = allocateUTF8(""); break; // Currently not supporting any EGL extensions.
5804
case 0x308D /* EGL_CLIENT_APIS */: ret = allocateUTF8("OpenGL_ES"); break;
5805
default:
5806
EGL.setErrorCode(0x300C /* EGL_BAD_PARAMETER */);
5807
return 0;
5808
}
5809
EGL.stringCache[name] = ret;
5810
return ret;
5811
}
5812
5813
function _eglSwapBuffers() {
5814
5815
if (!EGL.defaultDisplayInitialized) {
5816
EGL.setErrorCode(0x3001 /* EGL_NOT_INITIALIZED */);
5817
} else if (!Module.ctx) {
5818
EGL.setErrorCode(0x3002 /* EGL_BAD_ACCESS */);
5819
} else if (Module.ctx.isContextLost()) {
5820
EGL.setErrorCode(0x300E /* EGL_CONTEXT_LOST */);
5821
} else {
5822
// According to documentation this does an implicit flush.
5823
// Due to discussion at https://github.com/emscripten-core/emscripten/pull/1871
5824
// the flush was removed since this _may_ result in slowing code down.
5825
//_glFlush();
5826
EGL.setErrorCode(0x3000 /* EGL_SUCCESS */);
5827
return 1 /* EGL_TRUE */;
5828
}
5829
return 0 /* EGL_FALSE */;
5830
}
5831
5832
function _eglSwapInterval(display, interval) {
5833
if (display != 62000 /* Magic ID for Emscripten 'default display' */) {
5834
EGL.setErrorCode(0x3008 /* EGL_BAD_DISPLAY */);
5835
return 0;
5836
}
5837
if (interval == 0) _emscripten_set_main_loop_timing(0/*EM_TIMING_SETTIMEOUT*/, 0);
5838
else _emscripten_set_main_loop_timing(1/*EM_TIMING_RAF*/, interval);
5839
5840
EGL.setErrorCode(0x3000 /* EGL_SUCCESS */);
5841
return 1;
5842
}
5843
5844
function _eglTerminate(display) {
5845
if (display != 62000 /* Magic ID for Emscripten 'default display' */) {
5846
EGL.setErrorCode(0x3008 /* EGL_BAD_DISPLAY */);
5847
return 0;
5848
}
5849
EGL.currentContext = 0;
5850
EGL.currentReadSurface = 0;
5851
EGL.currentDrawSurface = 0;
5852
EGL.defaultDisplayInitialized = false;
5853
EGL.setErrorCode(0x3000 /* EGL_SUCCESS */);
5854
return 1;
5855
}
5856
5857
5858
function _eglWaitClient() {
5859
EGL.setErrorCode(0x3000 /* EGL_SUCCESS */);
5860
return 1;
5861
}function _eglWaitGL(
5862
) {
5863
return _eglWaitClient();
5864
}
5865
5866
function _eglWaitNative(nativeEngineId) {
5867
EGL.setErrorCode(0x3000 /* EGL_SUCCESS */);
5868
return 1;
5869
}
5870
5871
5872
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() {
5873
for(var i = JSEvents.eventHandlers.length-1; i >= 0; --i) {
5874
JSEvents._removeHandler(i);
5875
}
5876
JSEvents.eventHandlers = [];
5877
JSEvents.deferredCalls = [];
5878
},registerRemoveEventListeners:function() {
5879
if (!JSEvents.removeEventListenersRegistered) {
5880
__ATEXIT__.push(JSEvents.removeAllEventListeners);
5881
JSEvents.removeEventListenersRegistered = true;
5882
}
5883
},deferredCalls:[],deferCall:function(targetFunction, precedence, argsList) {
5884
function arraysHaveEqualContent(arrA, arrB) {
5885
if (arrA.length != arrB.length) return false;
5886
5887
for(var i in arrA) {
5888
if (arrA[i] != arrB[i]) return false;
5889
}
5890
return true;
5891
}
5892
// Test if the given call was already queued, and if so, don't add it again.
5893
for(var i in JSEvents.deferredCalls) {
5894
var call = JSEvents.deferredCalls[i];
5895
if (call.targetFunction == targetFunction && arraysHaveEqualContent(call.argsList, argsList)) {
5896
return;
5897
}
5898
}
5899
JSEvents.deferredCalls.push({
5900
targetFunction: targetFunction,
5901
precedence: precedence,
5902
argsList: argsList
5903
});
5904
5905
JSEvents.deferredCalls.sort(function(x,y) { return x.precedence < y.precedence; });
5906
},removeDeferredCalls:function(targetFunction) {
5907
for(var i = 0; i < JSEvents.deferredCalls.length; ++i) {
5908
if (JSEvents.deferredCalls[i].targetFunction == targetFunction) {
5909
JSEvents.deferredCalls.splice(i, 1);
5910
--i;
5911
}
5912
}
5913
},canPerformEventHandlerRequests:function() {
5914
return JSEvents.inEventHandler && JSEvents.currentEventHandler.allowsDeferredCalls;
5915
},runDeferredCalls:function() {
5916
if (!JSEvents.canPerformEventHandlerRequests()) {
5917
return;
5918
}
5919
for(var i = 0; i < JSEvents.deferredCalls.length; ++i) {
5920
var call = JSEvents.deferredCalls[i];
5921
JSEvents.deferredCalls.splice(i, 1);
5922
--i;
5923
call.targetFunction.apply(null, call.argsList);
5924
}
5925
},inEventHandler:0,currentEventHandler:null,eventHandlers:[],removeAllHandlersOnTarget:function(target, eventTypeString) {
5926
for(var i = 0; i < JSEvents.eventHandlers.length; ++i) {
5927
if (JSEvents.eventHandlers[i].target == target &&
5928
(!eventTypeString || eventTypeString == JSEvents.eventHandlers[i].eventTypeString)) {
5929
JSEvents._removeHandler(i--);
5930
}
5931
}
5932
},_removeHandler:function(i) {
5933
var h = JSEvents.eventHandlers[i];
5934
h.target.removeEventListener(h.eventTypeString, h.eventListenerFunc, h.useCapture);
5935
JSEvents.eventHandlers.splice(i, 1);
5936
},registerOrRemoveHandler:function(eventHandler) {
5937
var jsEventHandler = function jsEventHandler(event) {
5938
// Increment nesting count for the event handler.
5939
++JSEvents.inEventHandler;
5940
JSEvents.currentEventHandler = eventHandler;
5941
// Process any old deferred calls the user has placed.
5942
JSEvents.runDeferredCalls();
5943
// Process the actual event, calls back to user C code handler.
5944
eventHandler.handlerFunc(event);
5945
// Process any new deferred calls that were placed right now from this event handler.
5946
JSEvents.runDeferredCalls();
5947
// Out of event handler - restore nesting count.
5948
--JSEvents.inEventHandler;
5949
};
5950
5951
if (eventHandler.callbackfunc) {
5952
eventHandler.eventListenerFunc = jsEventHandler;
5953
eventHandler.target.addEventListener(eventHandler.eventTypeString, jsEventHandler, eventHandler.useCapture);
5954
JSEvents.eventHandlers.push(eventHandler);
5955
JSEvents.registerRemoveEventListeners();
5956
} else {
5957
for(var i = 0; i < JSEvents.eventHandlers.length; ++i) {
5958
if (JSEvents.eventHandlers[i].target == eventHandler.target
5959
&& JSEvents.eventHandlers[i].eventTypeString == eventHandler.eventTypeString) {
5960
JSEvents._removeHandler(i--);
5961
}
5962
}
5963
}
5964
},getNodeNameForTarget:function(target) {
5965
if (!target) return '';
5966
if (target == window) return '#window';
5967
if (target == screen) return '#screen';
5968
return (target && target.nodeName) ? target.nodeName : '';
5969
},fullscreenEnabled:function() {
5970
return document.fullscreenEnabled
5971
// Safari 13.0.3 on macOS Catalina 10.15.1 still ships with prefixed webkitFullscreenEnabled.
5972
// TODO: If Safari at some point ships with unprefixed version, update the version check above.
5973
|| document.webkitFullscreenEnabled
5974
;
5975
}};
5976
5977
var __currentFullscreenStrategy={};
5978
5979
5980
5981
5982
5983
5984
5985
5986
function __maybeCStringToJsString(cString) {
5987
return cString === cString + 0 ? UTF8ToString(cString) : cString;
5988
}
5989
5990
var __specialEventTargets=[0, typeof document !== 'undefined' ? document : 0, typeof window !== 'undefined' ? window : 0];function __findEventTarget(target) {
5991
var domElement = __specialEventTargets[target] || (typeof document !== 'undefined' ? document.querySelector(__maybeCStringToJsString(target)) : undefined);
5992
return domElement;
5993
}function __findCanvasEventTarget(target) { return __findEventTarget(target); }function _emscripten_get_canvas_element_size(target, width, height) {
5994
var canvas = __findCanvasEventTarget(target);
5995
if (!canvas) return -4;
5996
HEAP32[((width)>>2)]=canvas.width;
5997
HEAP32[((height)>>2)]=canvas.height;
5998
}function __get_canvas_element_size(target) {
5999
var stackTop = stackSave();
6000
var w = stackAlloc(8);
6001
var h = w + 4;
6002
6003
var targetInt = stackAlloc(target.id.length+1);
6004
stringToUTF8(target.id, targetInt, target.id.length+1);
6005
var ret = _emscripten_get_canvas_element_size(targetInt, w, h);
6006
var size = [HEAP32[((w)>>2)], HEAP32[((h)>>2)]];
6007
stackRestore(stackTop);
6008
return size;
6009
}
6010
6011
6012
function _emscripten_set_canvas_element_size(target, width, height) {
6013
var canvas = __findCanvasEventTarget(target);
6014
if (!canvas) return -4;
6015
canvas.width = width;
6016
canvas.height = height;
6017
return 0;
6018
}function __set_canvas_element_size(target, width, height) {
6019
if (!target.controlTransferredOffscreen) {
6020
target.width = width;
6021
target.height = height;
6022
} else {
6023
// This function is being called from high-level JavaScript code instead of asm.js/Wasm,
6024
// and it needs to synchronously proxy over to another thread, so marshal the string onto the heap to do the call.
6025
var stackTop = stackSave();
6026
var targetInt = stackAlloc(target.id.length+1);
6027
stringToUTF8(target.id, targetInt, target.id.length+1);
6028
_emscripten_set_canvas_element_size(targetInt, width, height);
6029
stackRestore(stackTop);
6030
}
6031
}function __registerRestoreOldStyle(canvas) {
6032
var canvasSize = __get_canvas_element_size(canvas);
6033
var oldWidth = canvasSize[0];
6034
var oldHeight = canvasSize[1];
6035
var oldCssWidth = canvas.style.width;
6036
var oldCssHeight = canvas.style.height;
6037
var oldBackgroundColor = canvas.style.backgroundColor; // Chrome reads color from here.
6038
var oldDocumentBackgroundColor = document.body.style.backgroundColor; // IE11 reads color from here.
6039
// Firefox always has black background color.
6040
var oldPaddingLeft = canvas.style.paddingLeft; // Chrome, FF, Safari
6041
var oldPaddingRight = canvas.style.paddingRight;
6042
var oldPaddingTop = canvas.style.paddingTop;
6043
var oldPaddingBottom = canvas.style.paddingBottom;
6044
var oldMarginLeft = canvas.style.marginLeft; // IE11
6045
var oldMarginRight = canvas.style.marginRight;
6046
var oldMarginTop = canvas.style.marginTop;
6047
var oldMarginBottom = canvas.style.marginBottom;
6048
var oldDocumentBodyMargin = document.body.style.margin;
6049
var oldDocumentOverflow = document.documentElement.style.overflow; // Chrome, Firefox
6050
var oldDocumentScroll = document.body.scroll; // IE
6051
var oldImageRendering = canvas.style.imageRendering;
6052
6053
function restoreOldStyle() {
6054
var fullscreenElement = document.fullscreenElement
6055
|| document.webkitFullscreenElement
6056
|| document.msFullscreenElement
6057
;
6058
if (!fullscreenElement) {
6059
document.removeEventListener('fullscreenchange', restoreOldStyle);
6060
6061
6062
// Unprefixed Fullscreen API shipped in Chromium 71 (https://bugs.chromium.org/p/chromium/issues/detail?id=383813)
6063
// 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.
6064
document.removeEventListener('webkitfullscreenchange', restoreOldStyle);
6065
6066
6067
__set_canvas_element_size(canvas, oldWidth, oldHeight);
6068
6069
canvas.style.width = oldCssWidth;
6070
canvas.style.height = oldCssHeight;
6071
canvas.style.backgroundColor = oldBackgroundColor; // Chrome
6072
// IE11 hack: assigning 'undefined' or an empty string to document.body.style.backgroundColor has no effect, so first assign back the default color
6073
// before setting the undefined value. Setting undefined value is also important, or otherwise we would later treat that as something that the user
6074
// had explicitly set so subsequent fullscreen transitions would not set background color properly.
6075
if (!oldDocumentBackgroundColor) document.body.style.backgroundColor = 'white';
6076
document.body.style.backgroundColor = oldDocumentBackgroundColor; // IE11
6077
canvas.style.paddingLeft = oldPaddingLeft; // Chrome, FF, Safari
6078
canvas.style.paddingRight = oldPaddingRight;
6079
canvas.style.paddingTop = oldPaddingTop;
6080
canvas.style.paddingBottom = oldPaddingBottom;
6081
canvas.style.marginLeft = oldMarginLeft; // IE11
6082
canvas.style.marginRight = oldMarginRight;
6083
canvas.style.marginTop = oldMarginTop;
6084
canvas.style.marginBottom = oldMarginBottom;
6085
document.body.style.margin = oldDocumentBodyMargin;
6086
document.documentElement.style.overflow = oldDocumentOverflow; // Chrome, Firefox
6087
document.body.scroll = oldDocumentScroll; // IE
6088
canvas.style.imageRendering = oldImageRendering;
6089
if (canvas.GLctxObject) canvas.GLctxObject.GLctx.viewport(0, 0, oldWidth, oldHeight);
6090
6091
if (__currentFullscreenStrategy.canvasResizedCallback) {
6092
dynCall_iiii(__currentFullscreenStrategy.canvasResizedCallback, 37, 0, __currentFullscreenStrategy.canvasResizedCallbackUserData);
6093
}
6094
}
6095
}
6096
document.addEventListener('fullscreenchange', restoreOldStyle);
6097
// Unprefixed Fullscreen API shipped in Chromium 71 (https://bugs.chromium.org/p/chromium/issues/detail?id=383813)
6098
// 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.
6099
document.addEventListener('webkitfullscreenchange', restoreOldStyle);
6100
return restoreOldStyle;
6101
}
6102
6103
function __setLetterbox(element, topBottom, leftRight) {
6104
// Cannot use margin to specify letterboxes in FF or Chrome, since those ignore margins in fullscreen mode.
6105
element.style.paddingLeft = element.style.paddingRight = leftRight + 'px';
6106
element.style.paddingTop = element.style.paddingBottom = topBottom + 'px';
6107
}
6108
6109
function __getBoundingClientRect(e) {
6110
return __specialEventTargets.indexOf(e) < 0 ? e.getBoundingClientRect() : {'left':0,'top':0};
6111
}function _JSEvents_resizeCanvasForFullscreen(target, strategy) {
6112
var restoreOldStyle = __registerRestoreOldStyle(target);
6113
var cssWidth = strategy.softFullscreen ? innerWidth : screen.width;
6114
var cssHeight = strategy.softFullscreen ? innerHeight : screen.height;
6115
var rect = __getBoundingClientRect(target);
6116
var windowedCssWidth = rect.width;
6117
var windowedCssHeight = rect.height;
6118
var canvasSize = __get_canvas_element_size(target);
6119
var windowedRttWidth = canvasSize[0];
6120
var windowedRttHeight = canvasSize[1];
6121
6122
if (strategy.scaleMode == 3) {
6123
__setLetterbox(target, (cssHeight - windowedCssHeight) / 2, (cssWidth - windowedCssWidth) / 2);
6124
cssWidth = windowedCssWidth;
6125
cssHeight = windowedCssHeight;
6126
} else if (strategy.scaleMode == 2) {
6127
if (cssWidth*windowedRttHeight < windowedRttWidth*cssHeight) {
6128
var desiredCssHeight = windowedRttHeight * cssWidth / windowedRttWidth;
6129
__setLetterbox(target, (cssHeight - desiredCssHeight) / 2, 0);
6130
cssHeight = desiredCssHeight;
6131
} else {
6132
var desiredCssWidth = windowedRttWidth * cssHeight / windowedRttHeight;
6133
__setLetterbox(target, 0, (cssWidth - desiredCssWidth) / 2);
6134
cssWidth = desiredCssWidth;
6135
}
6136
}
6137
6138
// If we are adding padding, must choose a background color or otherwise Chrome will give the
6139
// padding a default white color. Do it only if user has not customized their own background color.
6140
if (!target.style.backgroundColor) target.style.backgroundColor = 'black';
6141
// IE11 does the same, but requires the color to be set in the document body.
6142
if (!document.body.style.backgroundColor) document.body.style.backgroundColor = 'black'; // IE11
6143
// Firefox always shows black letterboxes independent of style color.
6144
6145
target.style.width = cssWidth + 'px';
6146
target.style.height = cssHeight + 'px';
6147
6148
if (strategy.filteringMode == 1) {
6149
target.style.imageRendering = 'optimizeSpeed';
6150
target.style.imageRendering = '-moz-crisp-edges';
6151
target.style.imageRendering = '-o-crisp-edges';
6152
target.style.imageRendering = '-webkit-optimize-contrast';
6153
target.style.imageRendering = 'optimize-contrast';
6154
target.style.imageRendering = 'crisp-edges';
6155
target.style.imageRendering = 'pixelated';
6156
}
6157
6158
var dpiScale = (strategy.canvasResolutionScaleMode == 2) ? devicePixelRatio : 1;
6159
if (strategy.canvasResolutionScaleMode != 0) {
6160
var newWidth = (cssWidth * dpiScale)|0;
6161
var newHeight = (cssHeight * dpiScale)|0;
6162
__set_canvas_element_size(target, newWidth, newHeight);
6163
if (target.GLctxObject) target.GLctxObject.GLctx.viewport(0, 0, newWidth, newHeight);
6164
}
6165
return restoreOldStyle;
6166
}function _JSEvents_requestFullscreen(target, strategy) {
6167
// EMSCRIPTEN_FULLSCREEN_SCALE_DEFAULT + EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_NONE is a mode where no extra logic is performed to the DOM elements.
6168
if (strategy.scaleMode != 0 || strategy.canvasResolutionScaleMode != 0) {
6169
_JSEvents_resizeCanvasForFullscreen(target, strategy);
6170
}
6171
6172
if (target.requestFullscreen) {
6173
target.requestFullscreen();
6174
} else if (target.webkitRequestFullscreen) {
6175
target.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
6176
} else {
6177
return JSEvents.fullscreenEnabled() ? -3 : -1;
6178
}
6179
6180
if (strategy.canvasResizedCallback) {
6181
dynCall_iiii(strategy.canvasResizedCallback, 37, 0, strategy.canvasResizedCallbackUserData);
6182
}
6183
6184
return 0;
6185
}function _emscripten_exit_fullscreen() {
6186
if (!JSEvents.fullscreenEnabled()) return -1;
6187
// Make sure no queued up calls will fire after this.
6188
JSEvents.removeDeferredCalls(_JSEvents_requestFullscreen);
6189
6190
var d = __specialEventTargets[1];
6191
if (d.exitFullscreen) {
6192
d.fullscreenElement && d.exitFullscreen();
6193
} else if (d.webkitExitFullscreen) {
6194
d.webkitFullscreenElement && d.webkitExitFullscreen();
6195
} else {
6196
return -1;
6197
}
6198
6199
return 0;
6200
}
6201
6202
6203
function __requestPointerLock(target) {
6204
if (target.requestPointerLock) {
6205
target.requestPointerLock();
6206
} else if (target.msRequestPointerLock) {
6207
target.msRequestPointerLock();
6208
} else {
6209
// document.body is known to accept pointer lock, so use that to differentiate if the user passed a bad element,
6210
// or if the whole browser just doesn't support the feature.
6211
if (document.body.requestPointerLock
6212
|| document.body.msRequestPointerLock
6213
) {
6214
return -3;
6215
} else {
6216
return -1;
6217
}
6218
}
6219
return 0;
6220
}function _emscripten_exit_pointerlock() {
6221
// Make sure no queued up calls will fire after this.
6222
JSEvents.removeDeferredCalls(__requestPointerLock);
6223
6224
if (document.exitPointerLock) {
6225
document.exitPointerLock();
6226
} else if (document.msExitPointerLock) {
6227
document.msExitPointerLock();
6228
} else {
6229
return -1;
6230
}
6231
return 0;
6232
}
6233
6234
function _emscripten_get_device_pixel_ratio() {
6235
return (typeof devicePixelRatio === 'number' && devicePixelRatio) || 1.0;
6236
}
6237
6238
function _emscripten_get_element_css_size(target, width, height) {
6239
target = __findEventTarget(target);
6240
if (!target) return -4;
6241
6242
var rect = __getBoundingClientRect(target);
6243
HEAPF64[((width)>>3)]=rect.width;
6244
HEAPF64[((height)>>3)]=rect.height;
6245
6246
return 0;
6247
}
6248
6249
6250
function __fillGamepadEventData(eventStruct, e) {
6251
HEAPF64[((eventStruct)>>3)]=e.timestamp;
6252
for(var i = 0; i < e.axes.length; ++i) {
6253
HEAPF64[(((eventStruct+i*8)+(16))>>3)]=e.axes[i];
6254
}
6255
for(var i = 0; i < e.buttons.length; ++i) {
6256
if (typeof(e.buttons[i]) === 'object') {
6257
HEAPF64[(((eventStruct+i*8)+(528))>>3)]=e.buttons[i].value;
6258
} else {
6259
HEAPF64[(((eventStruct+i*8)+(528))>>3)]=e.buttons[i];
6260
}
6261
}
6262
for(var i = 0; i < e.buttons.length; ++i) {
6263
if (typeof(e.buttons[i]) === 'object') {
6264
HEAP32[(((eventStruct+i*4)+(1040))>>2)]=e.buttons[i].pressed;
6265
} else {
6266
// Assigning a boolean to HEAP32, that's ok, but Closure would like to warn about it:
6267
/** @suppress {checkTypes} */
6268
HEAP32[(((eventStruct+i*4)+(1040))>>2)]=e.buttons[i] == 1;
6269
}
6270
}
6271
HEAP32[(((eventStruct)+(1296))>>2)]=e.connected;
6272
HEAP32[(((eventStruct)+(1300))>>2)]=e.index;
6273
HEAP32[(((eventStruct)+(8))>>2)]=e.axes.length;
6274
HEAP32[(((eventStruct)+(12))>>2)]=e.buttons.length;
6275
stringToUTF8(e.id, eventStruct + 1304, 64);
6276
stringToUTF8(e.mapping, eventStruct + 1368, 64);
6277
}function _emscripten_get_gamepad_status(index, gamepadState) {
6278
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!';
6279
6280
// INVALID_PARAM is returned on a Gamepad index that never was there.
6281
if (index < 0 || index >= JSEvents.lastGamepadState.length) return -5;
6282
6283
// NO_DATA is returned on a Gamepad index that was removed.
6284
// For previously disconnected gamepads there should be an empty slot (null/undefined/false) at the index.
6285
// This is because gamepads must keep their original position in the array.
6286
// For example, removing the first of two gamepads produces [null/undefined/false, gamepad].
6287
if (!JSEvents.lastGamepadState[index]) return -7;
6288
6289
__fillGamepadEventData(gamepadState, JSEvents.lastGamepadState[index]);
6290
return 0;
6291
}
6292
6293
function _emscripten_get_num_gamepads() {
6294
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!';
6295
// N.B. Do not call emscripten_get_num_gamepads() unless having first called emscripten_sample_gamepad_data(), and that has returned EMSCRIPTEN_RESULT_SUCCESS.
6296
// Otherwise the following line will throw an exception.
6297
return JSEvents.lastGamepadState.length;
6298
}
6299
6300
function _emscripten_get_sbrk_ptr() {
6301
return 14350080;
6302
}
6303
6304
function _emscripten_glActiveTexture(x0) { GLctx['activeTexture'](x0) }
6305
6306
function _emscripten_glAttachShader(program, shader) {
6307
GLctx.attachShader(GL.programs[program],
6308
GL.shaders[shader]);
6309
}
6310
6311
function _emscripten_glBeginQueryEXT(target, id) {
6312
GLctx.disjointTimerQueryExt['beginQueryEXT'](target, GL.timerQueriesEXT[id]);
6313
}
6314
6315
function _emscripten_glBindAttribLocation(program, index, name) {
6316
GLctx.bindAttribLocation(GL.programs[program], index, UTF8ToString(name));
6317
}
6318
6319
function _emscripten_glBindBuffer(target, buffer) {
6320
6321
GLctx.bindBuffer(target, GL.buffers[buffer]);
6322
}
6323
6324
function _emscripten_glBindFramebuffer(target, framebuffer) {
6325
6326
GLctx.bindFramebuffer(target, GL.framebuffers[framebuffer]);
6327
6328
}
6329
6330
function _emscripten_glBindRenderbuffer(target, renderbuffer) {
6331
GLctx.bindRenderbuffer(target, GL.renderbuffers[renderbuffer]);
6332
}
6333
6334
function _emscripten_glBindTexture(target, texture) {
6335
GLctx.bindTexture(target, GL.textures[texture]);
6336
}
6337
6338
function _emscripten_glBindVertexArrayOES(vao) {
6339
GLctx['bindVertexArray'](GL.vaos[vao]);
6340
}
6341
6342
function _emscripten_glBlendColor(x0, x1, x2, x3) { GLctx['blendColor'](x0, x1, x2, x3) }
6343
6344
function _emscripten_glBlendEquation(x0) { GLctx['blendEquation'](x0) }
6345
6346
function _emscripten_glBlendEquationSeparate(x0, x1) { GLctx['blendEquationSeparate'](x0, x1) }
6347
6348
function _emscripten_glBlendFunc(x0, x1) { GLctx['blendFunc'](x0, x1) }
6349
6350
function _emscripten_glBlendFuncSeparate(x0, x1, x2, x3) { GLctx['blendFuncSeparate'](x0, x1, x2, x3) }
6351
6352
function _emscripten_glBufferData(target, size, data, usage) {
6353
// 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
6354
// randomly mixing both uses in calling code, to avoid any potential JS engine JIT issues.
6355
GLctx.bufferData(target, data ? HEAPU8.subarray(data, data+size) : size, usage);
6356
}
6357
6358
function _emscripten_glBufferSubData(target, offset, size, data) {
6359
GLctx.bufferSubData(target, offset, HEAPU8.subarray(data, data+size));
6360
}
6361
6362
function _emscripten_glCheckFramebufferStatus(x0) { return GLctx['checkFramebufferStatus'](x0) }
6363
6364
function _emscripten_glClear(x0) { GLctx['clear'](x0) }
6365
6366
function _emscripten_glClearColor(x0, x1, x2, x3) { GLctx['clearColor'](x0, x1, x2, x3) }
6367
6368
function _emscripten_glClearDepthf(x0) { GLctx['clearDepth'](x0) }
6369
6370
function _emscripten_glClearStencil(x0) { GLctx['clearStencil'](x0) }
6371
6372
function _emscripten_glColorMask(red, green, blue, alpha) {
6373
GLctx.colorMask(!!red, !!green, !!blue, !!alpha);
6374
}
6375
6376
function _emscripten_glCompileShader(shader) {
6377
GLctx.compileShader(GL.shaders[shader]);
6378
}
6379
6380
function _emscripten_glCompressedTexImage2D(target, level, internalFormat, width, height, border, imageSize, data) {
6381
GLctx['compressedTexImage2D'](target, level, internalFormat, width, height, border, data ? HEAPU8.subarray((data),(data+imageSize)) : null);
6382
}
6383
6384
function _emscripten_glCompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, imageSize, data) {
6385
GLctx['compressedTexSubImage2D'](target, level, xoffset, yoffset, width, height, format, data ? HEAPU8.subarray((data),(data+imageSize)) : null);
6386
}
6387
6388
function _emscripten_glCopyTexImage2D(x0, x1, x2, x3, x4, x5, x6, x7) { GLctx['copyTexImage2D'](x0, x1, x2, x3, x4, x5, x6, x7) }
6389
6390
function _emscripten_glCopyTexSubImage2D(x0, x1, x2, x3, x4, x5, x6, x7) { GLctx['copyTexSubImage2D'](x0, x1, x2, x3, x4, x5, x6, x7) }
6391
6392
function _emscripten_glCreateProgram() {
6393
var id = GL.getNewId(GL.programs);
6394
var program = GLctx.createProgram();
6395
program.name = id;
6396
GL.programs[id] = program;
6397
return id;
6398
}
6399
6400
function _emscripten_glCreateShader(shaderType) {
6401
var id = GL.getNewId(GL.shaders);
6402
GL.shaders[id] = GLctx.createShader(shaderType);
6403
return id;
6404
}
6405
6406
function _emscripten_glCullFace(x0) { GLctx['cullFace'](x0) }
6407
6408
function _emscripten_glDeleteBuffers(n, buffers) {
6409
for (var i = 0; i < n; i++) {
6410
var id = HEAP32[(((buffers)+(i*4))>>2)];
6411
var buffer = GL.buffers[id];
6412
6413
// From spec: "glDeleteBuffers silently ignores 0's and names that do not
6414
// correspond to existing buffer objects."
6415
if (!buffer) continue;
6416
6417
GLctx.deleteBuffer(buffer);
6418
buffer.name = 0;
6419
GL.buffers[id] = null;
6420
6421
if (id == GL.currArrayBuffer) GL.currArrayBuffer = 0;
6422
if (id == GL.currElementArrayBuffer) GL.currElementArrayBuffer = 0;
6423
}
6424
}
6425
6426
function _emscripten_glDeleteFramebuffers(n, framebuffers) {
6427
for (var i = 0; i < n; ++i) {
6428
var id = HEAP32[(((framebuffers)+(i*4))>>2)];
6429
var framebuffer = GL.framebuffers[id];
6430
if (!framebuffer) continue; // GL spec: "glDeleteFramebuffers silently ignores 0s and names that do not correspond to existing framebuffer objects".
6431
GLctx.deleteFramebuffer(framebuffer);
6432
framebuffer.name = 0;
6433
GL.framebuffers[id] = null;
6434
}
6435
}
6436
6437
function _emscripten_glDeleteProgram(id) {
6438
if (!id) return;
6439
var program = GL.programs[id];
6440
if (!program) { // glDeleteProgram actually signals an error when deleting a nonexisting object, unlike some other GL delete functions.
6441
GL.recordError(0x501 /* GL_INVALID_VALUE */);
6442
return;
6443
}
6444
GLctx.deleteProgram(program);
6445
program.name = 0;
6446
GL.programs[id] = null;
6447
GL.programInfos[id] = null;
6448
}
6449
6450
function _emscripten_glDeleteQueriesEXT(n, ids) {
6451
for (var i = 0; i < n; i++) {
6452
var id = HEAP32[(((ids)+(i*4))>>2)];
6453
var query = GL.timerQueriesEXT[id];
6454
if (!query) continue; // GL spec: "unused names in ids are ignored, as is the name zero."
6455
GLctx.disjointTimerQueryExt['deleteQueryEXT'](query);
6456
GL.timerQueriesEXT[id] = null;
6457
}
6458
}
6459
6460
function _emscripten_glDeleteRenderbuffers(n, renderbuffers) {
6461
for (var i = 0; i < n; i++) {
6462
var id = HEAP32[(((renderbuffers)+(i*4))>>2)];
6463
var renderbuffer = GL.renderbuffers[id];
6464
if (!renderbuffer) continue; // GL spec: "glDeleteRenderbuffers silently ignores 0s and names that do not correspond to existing renderbuffer objects".
6465
GLctx.deleteRenderbuffer(renderbuffer);
6466
renderbuffer.name = 0;
6467
GL.renderbuffers[id] = null;
6468
}
6469
}
6470
6471
function _emscripten_glDeleteShader(id) {
6472
if (!id) return;
6473
var shader = GL.shaders[id];
6474
if (!shader) { // glDeleteShader actually signals an error when deleting a nonexisting object, unlike some other GL delete functions.
6475
GL.recordError(0x501 /* GL_INVALID_VALUE */);
6476
return;
6477
}
6478
GLctx.deleteShader(shader);
6479
GL.shaders[id] = null;
6480
}
6481
6482
function _emscripten_glDeleteTextures(n, textures) {
6483
for (var i = 0; i < n; i++) {
6484
var id = HEAP32[(((textures)+(i*4))>>2)];
6485
var texture = GL.textures[id];
6486
if (!texture) continue; // GL spec: "glDeleteTextures silently ignores 0s and names that do not correspond to existing textures".
6487
GLctx.deleteTexture(texture);
6488
texture.name = 0;
6489
GL.textures[id] = null;
6490
}
6491
}
6492
6493
function _emscripten_glDeleteVertexArraysOES(n, vaos) {
6494
for (var i = 0; i < n; i++) {
6495
var id = HEAP32[(((vaos)+(i*4))>>2)];
6496
GLctx['deleteVertexArray'](GL.vaos[id]);
6497
GL.vaos[id] = null;
6498
}
6499
}
6500
6501
function _emscripten_glDepthFunc(x0) { GLctx['depthFunc'](x0) }
6502
6503
function _emscripten_glDepthMask(flag) {
6504
GLctx.depthMask(!!flag);
6505
}
6506
6507
function _emscripten_glDepthRangef(x0, x1) { GLctx['depthRange'](x0, x1) }
6508
6509
function _emscripten_glDetachShader(program, shader) {
6510
GLctx.detachShader(GL.programs[program],
6511
GL.shaders[shader]);
6512
}
6513
6514
function _emscripten_glDisable(x0) { GLctx['disable'](x0) }
6515
6516
function _emscripten_glDisableVertexAttribArray(index) {
6517
GLctx.disableVertexAttribArray(index);
6518
}
6519
6520
function _emscripten_glDrawArrays(mode, first, count) {
6521
6522
GLctx.drawArrays(mode, first, count);
6523
6524
}
6525
6526
function _emscripten_glDrawArraysInstancedANGLE(mode, first, count, primcount) {
6527
GLctx['drawArraysInstanced'](mode, first, count, primcount);
6528
}
6529
6530
6531
var __tempFixedLengthArray=[];function _emscripten_glDrawBuffersWEBGL(n, bufs) {
6532
6533
var bufArray = __tempFixedLengthArray[n];
6534
for (var i = 0; i < n; i++) {
6535
bufArray[i] = HEAP32[(((bufs)+(i*4))>>2)];
6536
}
6537
6538
GLctx['drawBuffers'](bufArray);
6539
}
6540
6541
function _emscripten_glDrawElements(mode, count, type, indices) {
6542
6543
GLctx.drawElements(mode, count, type, indices);
6544
6545
}
6546
6547
function _emscripten_glDrawElementsInstancedANGLE(mode, count, type, indices, primcount) {
6548
GLctx['drawElementsInstanced'](mode, count, type, indices, primcount);
6549
}
6550
6551
function _emscripten_glEnable(x0) { GLctx['enable'](x0) }
6552
6553
function _emscripten_glEnableVertexAttribArray(index) {
6554
GLctx.enableVertexAttribArray(index);
6555
}
6556
6557
function _emscripten_glEndQueryEXT(target) {
6558
GLctx.disjointTimerQueryExt['endQueryEXT'](target);
6559
}
6560
6561
function _emscripten_glFinish() { GLctx['finish']() }
6562
6563
function _emscripten_glFlush() { GLctx['flush']() }
6564
6565
function _emscripten_glFramebufferRenderbuffer(target, attachment, renderbuffertarget, renderbuffer) {
6566
GLctx.framebufferRenderbuffer(target, attachment, renderbuffertarget,
6567
GL.renderbuffers[renderbuffer]);
6568
}
6569
6570
function _emscripten_glFramebufferTexture2D(target, attachment, textarget, texture, level) {
6571
GLctx.framebufferTexture2D(target, attachment, textarget,
6572
GL.textures[texture], level);
6573
}
6574
6575
function _emscripten_glFrontFace(x0) { GLctx['frontFace'](x0) }
6576
6577
6578
function __glGenObject(n, buffers, createFunction, objectTable
6579
) {
6580
for (var i = 0; i < n; i++) {
6581
var buffer = GLctx[createFunction]();
6582
var id = buffer && GL.getNewId(objectTable);
6583
if (buffer) {
6584
buffer.name = id;
6585
objectTable[id] = buffer;
6586
} else {
6587
GL.recordError(0x502 /* GL_INVALID_OPERATION */);
6588
}
6589
HEAP32[(((buffers)+(i*4))>>2)]=id;
6590
}
6591
}function _emscripten_glGenBuffers(n, buffers) {
6592
__glGenObject(n, buffers, 'createBuffer', GL.buffers
6593
);
6594
}
6595
6596
function _emscripten_glGenFramebuffers(n, ids) {
6597
__glGenObject(n, ids, 'createFramebuffer', GL.framebuffers
6598
);
6599
}
6600
6601
function _emscripten_glGenQueriesEXT(n, ids) {
6602
for (var i = 0; i < n; i++) {
6603
var query = GLctx.disjointTimerQueryExt['createQueryEXT']();
6604
if (!query) {
6605
GL.recordError(0x502 /* GL_INVALID_OPERATION */);
6606
while(i < n) HEAP32[(((ids)+(i++*4))>>2)]=0;
6607
return;
6608
}
6609
var id = GL.getNewId(GL.timerQueriesEXT);
6610
query.name = id;
6611
GL.timerQueriesEXT[id] = query;
6612
HEAP32[(((ids)+(i*4))>>2)]=id;
6613
}
6614
}
6615
6616
function _emscripten_glGenRenderbuffers(n, renderbuffers) {
6617
__glGenObject(n, renderbuffers, 'createRenderbuffer', GL.renderbuffers
6618
);
6619
}
6620
6621
function _emscripten_glGenTextures(n, textures) {
6622
__glGenObject(n, textures, 'createTexture', GL.textures
6623
);
6624
}
6625
6626
function _emscripten_glGenVertexArraysOES(n, arrays) {
6627
__glGenObject(n, arrays, 'createVertexArray', GL.vaos
6628
);
6629
}
6630
6631
function _emscripten_glGenerateMipmap(x0) { GLctx['generateMipmap'](x0) }
6632
6633
function _emscripten_glGetActiveAttrib(program, index, bufSize, length, size, type, name) {
6634
program = GL.programs[program];
6635
var info = GLctx.getActiveAttrib(program, index);
6636
if (!info) return; // If an error occurs, nothing will be written to length, size and type and name.
6637
6638
var numBytesWrittenExclNull = (bufSize > 0 && name) ? stringToUTF8(info.name, name, bufSize) : 0;
6639
if (length) HEAP32[((length)>>2)]=numBytesWrittenExclNull;
6640
if (size) HEAP32[((size)>>2)]=info.size;
6641
if (type) HEAP32[((type)>>2)]=info.type;
6642
}
6643
6644
function _emscripten_glGetActiveUniform(program, index, bufSize, length, size, type, name) {
6645
program = GL.programs[program];
6646
var info = GLctx.getActiveUniform(program, index);
6647
if (!info) return; // If an error occurs, nothing will be written to length, size, type and name.
6648
6649
var numBytesWrittenExclNull = (bufSize > 0 && name) ? stringToUTF8(info.name, name, bufSize) : 0;
6650
if (length) HEAP32[((length)>>2)]=numBytesWrittenExclNull;
6651
if (size) HEAP32[((size)>>2)]=info.size;
6652
if (type) HEAP32[((type)>>2)]=info.type;
6653
}
6654
6655
function _emscripten_glGetAttachedShaders(program, maxCount, count, shaders) {
6656
var result = GLctx.getAttachedShaders(GL.programs[program]);
6657
var len = result.length;
6658
if (len > maxCount) {
6659
len = maxCount;
6660
}
6661
HEAP32[((count)>>2)]=len;
6662
for (var i = 0; i < len; ++i) {
6663
var id = GL.shaders.indexOf(result[i]);
6664
HEAP32[(((shaders)+(i*4))>>2)]=id;
6665
}
6666
}
6667
6668
function _emscripten_glGetAttribLocation(program, name) {
6669
return GLctx.getAttribLocation(GL.programs[program], UTF8ToString(name));
6670
}
6671
6672
6673
6674
6675
function readI53FromI64(ptr) {
6676
return HEAPU32[ptr>>2] + HEAP32[ptr+4>>2] * 4294967296;
6677
}
6678
6679
function readI53FromU64(ptr) {
6680
return HEAPU32[ptr>>2] + HEAPU32[ptr+4>>2] * 4294967296;
6681
}function writeI53ToI64(ptr, num) {
6682
HEAPU32[ptr>>2] = num;
6683
HEAPU32[ptr+4>>2] = (num - HEAPU32[ptr>>2])/4294967296;
6684
var deserialized = (num >= 0) ? readI53FromU64(ptr) : readI53FromI64(ptr);
6685
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!');
6686
}function emscriptenWebGLGet(name_, p, type) {
6687
// Guard against user passing a null pointer.
6688
// Note that GLES2 spec does not say anything about how passing a null pointer should be treated.
6689
// Testing on desktop core GL 3, the application crashes on glGetIntegerv to a null pointer, but
6690
// better to report an error instead of doing anything random.
6691
if (!p) {
6692
GL.recordError(0x501 /* GL_INVALID_VALUE */);
6693
return;
6694
}
6695
var ret = undefined;
6696
switch(name_) { // Handle a few trivial GLES values
6697
case 0x8DFA: // GL_SHADER_COMPILER
6698
ret = 1;
6699
break;
6700
case 0x8DF8: // GL_SHADER_BINARY_FORMATS
6701
if (type != 0 && type != 1) {
6702
GL.recordError(0x500); // GL_INVALID_ENUM
6703
}
6704
return; // Do not write anything to the out pointer, since no binary formats are supported.
6705
case 0x8DF9: // GL_NUM_SHADER_BINARY_FORMATS
6706
ret = 0;
6707
break;
6708
case 0x86A2: // GL_NUM_COMPRESSED_TEXTURE_FORMATS
6709
// 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),
6710
// so implement it ourselves to allow C++ GLES2 code get the length.
6711
var formats = GLctx.getParameter(0x86A3 /*GL_COMPRESSED_TEXTURE_FORMATS*/);
6712
ret = formats ? formats.length : 0;
6713
break;
6714
}
6715
6716
if (ret === undefined) {
6717
var result = GLctx.getParameter(name_);
6718
switch (typeof(result)) {
6719
case "number":
6720
ret = result;
6721
break;
6722
case "boolean":
6723
ret = result ? 1 : 0;
6724
break;
6725
case "string":
6726
GL.recordError(0x500); // GL_INVALID_ENUM
6727
return;
6728
case "object":
6729
if (result === null) {
6730
// null is a valid result for some (e.g., which buffer is bound - perhaps nothing is bound), but otherwise
6731
// can mean an invalid name_, which we need to report as an error
6732
switch(name_) {
6733
case 0x8894: // ARRAY_BUFFER_BINDING
6734
case 0x8B8D: // CURRENT_PROGRAM
6735
case 0x8895: // ELEMENT_ARRAY_BUFFER_BINDING
6736
case 0x8CA6: // FRAMEBUFFER_BINDING
6737
case 0x8CA7: // RENDERBUFFER_BINDING
6738
case 0x8069: // TEXTURE_BINDING_2D
6739
case 0x85B5: // WebGL 2 GL_VERTEX_ARRAY_BINDING, or WebGL 1 extension OES_vertex_array_object GL_VERTEX_ARRAY_BINDING_OES
6740
case 0x8514: { // TEXTURE_BINDING_CUBE_MAP
6741
ret = 0;
6742
break;
6743
}
6744
default: {
6745
GL.recordError(0x500); // GL_INVALID_ENUM
6746
return;
6747
}
6748
}
6749
} else if (result instanceof Float32Array ||
6750
result instanceof Uint32Array ||
6751
result instanceof Int32Array ||
6752
result instanceof Array) {
6753
for (var i = 0; i < result.length; ++i) {
6754
switch (type) {
6755
case 0: HEAP32[(((p)+(i*4))>>2)]=result[i]; break;
6756
case 2: HEAPF32[(((p)+(i*4))>>2)]=result[i]; break;
6757
case 4: HEAP8[(((p)+(i))>>0)]=result[i] ? 1 : 0; break;
6758
}
6759
}
6760
return;
6761
} else {
6762
try {
6763
ret = result.name | 0;
6764
} catch(e) {
6765
GL.recordError(0x500); // GL_INVALID_ENUM
6766
err('GL_INVALID_ENUM in glGet' + type + 'v: Unknown object returned from WebGL getParameter(' + name_ + ')! (error: ' + e + ')');
6767
return;
6768
}
6769
}
6770
break;
6771
default:
6772
GL.recordError(0x500); // GL_INVALID_ENUM
6773
err('GL_INVALID_ENUM in glGet' + type + 'v: Native code calling glGet' + type + 'v(' + name_ + ') and it returns ' + result + ' of type ' + typeof(result) + '!');
6774
return;
6775
}
6776
}
6777
6778
switch (type) {
6779
case 1: writeI53ToI64(p, ret); break;
6780
case 0: HEAP32[((p)>>2)]=ret; break;
6781
case 2: HEAPF32[((p)>>2)]=ret; break;
6782
case 4: HEAP8[((p)>>0)]=ret ? 1 : 0; break;
6783
}
6784
}function _emscripten_glGetBooleanv(name_, p) {
6785
emscriptenWebGLGet(name_, p, 4);
6786
}
6787
6788
function _emscripten_glGetBufferParameteriv(target, value, data) {
6789
if (!data) {
6790
// GLES2 specification does not specify how to behave if data is a null pointer. Since calling this function does not make sense
6791
// if data == null, issue a GL error to notify user about it.
6792
GL.recordError(0x501 /* GL_INVALID_VALUE */);
6793
return;
6794
}
6795
HEAP32[((data)>>2)]=GLctx.getBufferParameter(target, value);
6796
}
6797
6798
function _emscripten_glGetError() {
6799
var error = GLctx.getError() || GL.lastError;
6800
GL.lastError = 0/*GL_NO_ERROR*/;
6801
return error;
6802
}
6803
6804
function _emscripten_glGetFloatv(name_, p) {
6805
emscriptenWebGLGet(name_, p, 2);
6806
}
6807
6808
function _emscripten_glGetFramebufferAttachmentParameteriv(target, attachment, pname, params) {
6809
var result = GLctx.getFramebufferAttachmentParameter(target, attachment, pname);
6810
if (result instanceof WebGLRenderbuffer ||
6811
result instanceof WebGLTexture) {
6812
result = result.name | 0;
6813
}
6814
HEAP32[((params)>>2)]=result;
6815
}
6816
6817
function _emscripten_glGetIntegerv(name_, p) {
6818
emscriptenWebGLGet(name_, p, 0);
6819
}
6820
6821
function _emscripten_glGetProgramInfoLog(program, maxLength, length, infoLog) {
6822
var log = GLctx.getProgramInfoLog(GL.programs[program]);
6823
if (log === null) log = '(unknown error)';
6824
var numBytesWrittenExclNull = (maxLength > 0 && infoLog) ? stringToUTF8(log, infoLog, maxLength) : 0;
6825
if (length) HEAP32[((length)>>2)]=numBytesWrittenExclNull;
6826
}
6827
6828
function _emscripten_glGetProgramiv(program, pname, p) {
6829
if (!p) {
6830
// GLES2 specification does not specify how to behave if p is a null pointer. Since calling this function does not make sense
6831
// if p == null, issue a GL error to notify user about it.
6832
GL.recordError(0x501 /* GL_INVALID_VALUE */);
6833
return;
6834
}
6835
6836
if (program >= GL.counter) {
6837
GL.recordError(0x501 /* GL_INVALID_VALUE */);
6838
return;
6839
}
6840
6841
var ptable = GL.programInfos[program];
6842
if (!ptable) {
6843
GL.recordError(0x502 /* GL_INVALID_OPERATION */);
6844
return;
6845
}
6846
6847
if (pname == 0x8B84) { // GL_INFO_LOG_LENGTH
6848
var log = GLctx.getProgramInfoLog(GL.programs[program]);
6849
if (log === null) log = '(unknown error)';
6850
HEAP32[((p)>>2)]=log.length + 1;
6851
} else if (pname == 0x8B87 /* GL_ACTIVE_UNIFORM_MAX_LENGTH */) {
6852
HEAP32[((p)>>2)]=ptable.maxUniformLength;
6853
} else if (pname == 0x8B8A /* GL_ACTIVE_ATTRIBUTE_MAX_LENGTH */) {
6854
if (ptable.maxAttributeLength == -1) {
6855
program = GL.programs[program];
6856
var numAttribs = GLctx.getProgramParameter(program, 0x8B89/*GL_ACTIVE_ATTRIBUTES*/);
6857
ptable.maxAttributeLength = 0; // Spec says if there are no active attribs, 0 must be returned.
6858
for (var i = 0; i < numAttribs; ++i) {
6859
var activeAttrib = GLctx.getActiveAttrib(program, i);
6860
ptable.maxAttributeLength = Math.max(ptable.maxAttributeLength, activeAttrib.name.length+1);
6861
}
6862
}
6863
HEAP32[((p)>>2)]=ptable.maxAttributeLength;
6864
} else if (pname == 0x8A35 /* GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH */) {
6865
if (ptable.maxUniformBlockNameLength == -1) {
6866
program = GL.programs[program];
6867
var numBlocks = GLctx.getProgramParameter(program, 0x8A36/*GL_ACTIVE_UNIFORM_BLOCKS*/);
6868
ptable.maxUniformBlockNameLength = 0;
6869
for (var i = 0; i < numBlocks; ++i) {
6870
var activeBlockName = GLctx.getActiveUniformBlockName(program, i);
6871
ptable.maxUniformBlockNameLength = Math.max(ptable.maxUniformBlockNameLength, activeBlockName.length+1);
6872
}
6873
}
6874
HEAP32[((p)>>2)]=ptable.maxUniformBlockNameLength;
6875
} else {
6876
HEAP32[((p)>>2)]=GLctx.getProgramParameter(GL.programs[program], pname);
6877
}
6878
}
6879
6880
function _emscripten_glGetQueryObjecti64vEXT(id, pname, params) {
6881
if (!params) {
6882
// GLES2 specification does not specify how to behave if params is a null pointer. Since calling this function does not make sense
6883
// if p == null, issue a GL error to notify user about it.
6884
GL.recordError(0x501 /* GL_INVALID_VALUE */);
6885
return;
6886
}
6887
var query = GL.timerQueriesEXT[id];
6888
var param = GLctx.disjointTimerQueryExt['getQueryObjectEXT'](query, pname);
6889
var ret;
6890
if (typeof param == 'boolean') {
6891
ret = param ? 1 : 0;
6892
} else {
6893
ret = param;
6894
}
6895
writeI53ToI64(params, ret);
6896
}
6897
6898
function _emscripten_glGetQueryObjectivEXT(id, pname, params) {
6899
if (!params) {
6900
// GLES2 specification does not specify how to behave if params is a null pointer. Since calling this function does not make sense
6901
// if p == null, issue a GL error to notify user about it.
6902
GL.recordError(0x501 /* GL_INVALID_VALUE */);
6903
return;
6904
}
6905
var query = GL.timerQueriesEXT[id];
6906
var param = GLctx.disjointTimerQueryExt['getQueryObjectEXT'](query, pname);
6907
var ret;
6908
if (typeof param == 'boolean') {
6909
ret = param ? 1 : 0;
6910
} else {
6911
ret = param;
6912
}
6913
HEAP32[((params)>>2)]=ret;
6914
}
6915
6916
function _emscripten_glGetQueryObjectui64vEXT(id, pname, params) {
6917
if (!params) {
6918
// GLES2 specification does not specify how to behave if params is a null pointer. Since calling this function does not make sense
6919
// if p == null, issue a GL error to notify user about it.
6920
GL.recordError(0x501 /* GL_INVALID_VALUE */);
6921
return;
6922
}
6923
var query = GL.timerQueriesEXT[id];
6924
var param = GLctx.disjointTimerQueryExt['getQueryObjectEXT'](query, pname);
6925
var ret;
6926
if (typeof param == 'boolean') {
6927
ret = param ? 1 : 0;
6928
} else {
6929
ret = param;
6930
}
6931
writeI53ToI64(params, ret);
6932
}
6933
6934
function _emscripten_glGetQueryObjectuivEXT(id, pname, params) {
6935
if (!params) {
6936
// GLES2 specification does not specify how to behave if params is a null pointer. Since calling this function does not make sense
6937
// if p == null, issue a GL error to notify user about it.
6938
GL.recordError(0x501 /* GL_INVALID_VALUE */);
6939
return;
6940
}
6941
var query = GL.timerQueriesEXT[id];
6942
var param = GLctx.disjointTimerQueryExt['getQueryObjectEXT'](query, pname);
6943
var ret;
6944
if (typeof param == 'boolean') {
6945
ret = param ? 1 : 0;
6946
} else {
6947
ret = param;
6948
}
6949
HEAP32[((params)>>2)]=ret;
6950
}
6951
6952
function _emscripten_glGetQueryivEXT(target, pname, params) {
6953
if (!params) {
6954
// GLES2 specification does not specify how to behave if params is a null pointer. Since calling this function does not make sense
6955
// if p == null, issue a GL error to notify user about it.
6956
GL.recordError(0x501 /* GL_INVALID_VALUE */);
6957
return;
6958
}
6959
HEAP32[((params)>>2)]=GLctx.disjointTimerQueryExt['getQueryEXT'](target, pname);
6960
}
6961
6962
function _emscripten_glGetRenderbufferParameteriv(target, pname, params) {
6963
if (!params) {
6964
// GLES2 specification does not specify how to behave if params is a null pointer. Since calling this function does not make sense
6965
// if params == null, issue a GL error to notify user about it.
6966
GL.recordError(0x501 /* GL_INVALID_VALUE */);
6967
return;
6968
}
6969
HEAP32[((params)>>2)]=GLctx.getRenderbufferParameter(target, pname);
6970
}
6971
6972
function _emscripten_glGetShaderInfoLog(shader, maxLength, length, infoLog) {
6973
var log = GLctx.getShaderInfoLog(GL.shaders[shader]);
6974
if (log === null) log = '(unknown error)';
6975
var numBytesWrittenExclNull = (maxLength > 0 && infoLog) ? stringToUTF8(log, infoLog, maxLength) : 0;
6976
if (length) HEAP32[((length)>>2)]=numBytesWrittenExclNull;
6977
}
6978
6979
function _emscripten_glGetShaderPrecisionFormat(shaderType, precisionType, range, precision) {
6980
var result = GLctx.getShaderPrecisionFormat(shaderType, precisionType);
6981
HEAP32[((range)>>2)]=result.rangeMin;
6982
HEAP32[(((range)+(4))>>2)]=result.rangeMax;
6983
HEAP32[((precision)>>2)]=result.precision;
6984
}
6985
6986
function _emscripten_glGetShaderSource(shader, bufSize, length, source) {
6987
var result = GLctx.getShaderSource(GL.shaders[shader]);
6988
if (!result) return; // If an error occurs, nothing will be written to length or source.
6989
var numBytesWrittenExclNull = (bufSize > 0 && source) ? stringToUTF8(result, source, bufSize) : 0;
6990
if (length) HEAP32[((length)>>2)]=numBytesWrittenExclNull;
6991
}
6992
6993
function _emscripten_glGetShaderiv(shader, pname, p) {
6994
if (!p) {
6995
// GLES2 specification does not specify how to behave if p is a null pointer. Since calling this function does not make sense
6996
// if p == null, issue a GL error to notify user about it.
6997
GL.recordError(0x501 /* GL_INVALID_VALUE */);
6998
return;
6999
}
7000
if (pname == 0x8B84) { // GL_INFO_LOG_LENGTH
7001
var log = GLctx.getShaderInfoLog(GL.shaders[shader]);
7002
if (log === null) log = '(unknown error)';
7003
HEAP32[((p)>>2)]=log.length + 1;
7004
} else if (pname == 0x8B88) { // GL_SHADER_SOURCE_LENGTH
7005
var source = GLctx.getShaderSource(GL.shaders[shader]);
7006
var sourceLength = (source === null || source.length == 0) ? 0 : source.length + 1;
7007
HEAP32[((p)>>2)]=sourceLength;
7008
} else {
7009
HEAP32[((p)>>2)]=GLctx.getShaderParameter(GL.shaders[shader], pname);
7010
}
7011
}
7012
7013
7014
function stringToNewUTF8(jsString) {
7015
var length = lengthBytesUTF8(jsString)+1;
7016
var cString = _malloc(length);
7017
stringToUTF8(jsString, cString, length);
7018
return cString;
7019
}function _emscripten_glGetString(name_) {
7020
if (GL.stringCache[name_]) return GL.stringCache[name_];
7021
var ret;
7022
switch(name_) {
7023
case 0x1F03 /* GL_EXTENSIONS */:
7024
var exts = GLctx.getSupportedExtensions() || []; // .getSupportedExtensions() can return null if context is lost, so coerce to empty array.
7025
exts = exts.concat(exts.map(function(e) { return "GL_" + e; }));
7026
ret = stringToNewUTF8(exts.join(' '));
7027
break;
7028
case 0x1F00 /* GL_VENDOR */:
7029
case 0x1F01 /* GL_RENDERER */:
7030
case 0x9245 /* UNMASKED_VENDOR_WEBGL */:
7031
case 0x9246 /* UNMASKED_RENDERER_WEBGL */:
7032
var s = GLctx.getParameter(name_);
7033
if (!s) {
7034
GL.recordError(0x500/*GL_INVALID_ENUM*/);
7035
}
7036
ret = stringToNewUTF8(s);
7037
break;
7038
7039
case 0x1F02 /* GL_VERSION */:
7040
var glVersion = GLctx.getParameter(0x1F02 /*GL_VERSION*/);
7041
// return GLES version string corresponding to the version of the WebGL context
7042
{
7043
glVersion = 'OpenGL ES 2.0 (' + glVersion + ')';
7044
}
7045
ret = stringToNewUTF8(glVersion);
7046
break;
7047
case 0x8B8C /* GL_SHADING_LANGUAGE_VERSION */:
7048
var glslVersion = GLctx.getParameter(0x8B8C /*GL_SHADING_LANGUAGE_VERSION*/);
7049
// extract the version number 'N.M' from the string 'WebGL GLSL ES N.M ...'
7050
var ver_re = /^WebGL GLSL ES ([0-9]\.[0-9][0-9]?)(?:$| .*)/;
7051
var ver_num = glslVersion.match(ver_re);
7052
if (ver_num !== null) {
7053
if (ver_num[1].length == 3) ver_num[1] = ver_num[1] + '0'; // ensure minor version has 2 digits
7054
glslVersion = 'OpenGL ES GLSL ES ' + ver_num[1] + ' (' + glslVersion + ')';
7055
}
7056
ret = stringToNewUTF8(glslVersion);
7057
break;
7058
default:
7059
GL.recordError(0x500/*GL_INVALID_ENUM*/);
7060
return 0;
7061
}
7062
GL.stringCache[name_] = ret;
7063
return ret;
7064
}
7065
7066
function _emscripten_glGetTexParameterfv(target, pname, params) {
7067
if (!params) {
7068
// GLES2 specification does not specify how to behave if params is a null pointer. Since calling this function does not make sense
7069
// if p == null, issue a GL error to notify user about it.
7070
GL.recordError(0x501 /* GL_INVALID_VALUE */);
7071
return;
7072
}
7073
HEAPF32[((params)>>2)]=GLctx.getTexParameter(target, pname);
7074
}
7075
7076
function _emscripten_glGetTexParameteriv(target, pname, params) {
7077
if (!params) {
7078
// GLES2 specification does not specify how to behave if params is a null pointer. Since calling this function does not make sense
7079
// if p == null, issue a GL error to notify user about it.
7080
GL.recordError(0x501 /* GL_INVALID_VALUE */);
7081
return;
7082
}
7083
HEAP32[((params)>>2)]=GLctx.getTexParameter(target, pname);
7084
}
7085
7086
7087
function jstoi_q(str) {
7088
// TODO: If issues below are resolved, add a suitable suppression or remove this comment.
7089
return parseInt(str, undefined /* https://github.com/google/closure-compiler/issues/3230 / https://github.com/google/closure-compiler/issues/3548 */);
7090
}function _emscripten_glGetUniformLocation(program, name) {
7091
name = UTF8ToString(name);
7092
7093
var arrayIndex = 0;
7094
// If user passed an array accessor "[index]", parse the array index off the accessor.
7095
if (name[name.length - 1] == ']') {
7096
var leftBrace = name.lastIndexOf('[');
7097
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]"
7098
name = name.slice(0, leftBrace);
7099
}
7100
7101
var uniformInfo = GL.programInfos[program] && GL.programInfos[program].uniforms[name]; // returns pair [ dimension_of_uniform_array, uniform_location ]
7102
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.
7103
return uniformInfo[1] + arrayIndex;
7104
} else {
7105
return -1;
7106
}
7107
}
7108
7109
7110
/** @suppress{checkTypes} */
7111
function emscriptenWebGLGetUniform(program, location, params, type) {
7112
if (!params) {
7113
// GLES2 specification does not specify how to behave if params is a null pointer. Since calling this function does not make sense
7114
// if params == null, issue a GL error to notify user about it.
7115
GL.recordError(0x501 /* GL_INVALID_VALUE */);
7116
return;
7117
}
7118
var data = GLctx.getUniform(GL.programs[program], GL.uniforms[location]);
7119
if (typeof data == 'number' || typeof data == 'boolean') {
7120
switch (type) {
7121
case 0: HEAP32[((params)>>2)]=data; break;
7122
case 2: HEAPF32[((params)>>2)]=data; break;
7123
default: throw 'internal emscriptenWebGLGetUniform() error, bad type: ' + type;
7124
}
7125
} else {
7126
for (var i = 0; i < data.length; i++) {
7127
switch (type) {
7128
case 0: HEAP32[(((params)+(i*4))>>2)]=data[i]; break;
7129
case 2: HEAPF32[(((params)+(i*4))>>2)]=data[i]; break;
7130
default: throw 'internal emscriptenWebGLGetUniform() error, bad type: ' + type;
7131
}
7132
}
7133
}
7134
}function _emscripten_glGetUniformfv(program, location, params) {
7135
emscriptenWebGLGetUniform(program, location, params, 2);
7136
}
7137
7138
function _emscripten_glGetUniformiv(program, location, params) {
7139
emscriptenWebGLGetUniform(program, location, params, 0);
7140
}
7141
7142
function _emscripten_glGetVertexAttribPointerv(index, pname, pointer) {
7143
if (!pointer) {
7144
// GLES2 specification does not specify how to behave if pointer is a null pointer. Since calling this function does not make sense
7145
// if pointer == null, issue a GL error to notify user about it.
7146
GL.recordError(0x501 /* GL_INVALID_VALUE */);
7147
return;
7148
}
7149
HEAP32[((pointer)>>2)]=GLctx.getVertexAttribOffset(index, pname);
7150
}
7151
7152
7153
/** @suppress{checkTypes} */
7154
function emscriptenWebGLGetVertexAttrib(index, pname, params, type) {
7155
if (!params) {
7156
// GLES2 specification does not specify how to behave if params is a null pointer. Since calling this function does not make sense
7157
// if params == null, issue a GL error to notify user about it.
7158
GL.recordError(0x501 /* GL_INVALID_VALUE */);
7159
return;
7160
}
7161
var data = GLctx.getVertexAttrib(index, pname);
7162
if (pname == 0x889F/*VERTEX_ATTRIB_ARRAY_BUFFER_BINDING*/) {
7163
HEAP32[((params)>>2)]=data["name"];
7164
} else if (typeof data == 'number' || typeof data == 'boolean') {
7165
switch (type) {
7166
case 0: HEAP32[((params)>>2)]=data; break;
7167
case 2: HEAPF32[((params)>>2)]=data; break;
7168
case 5: HEAP32[((params)>>2)]=Math.fround(data); break;
7169
default: throw 'internal emscriptenWebGLGetVertexAttrib() error, bad type: ' + type;
7170
}
7171
} else {
7172
for (var i = 0; i < data.length; i++) {
7173
switch (type) {
7174
case 0: HEAP32[(((params)+(i*4))>>2)]=data[i]; break;
7175
case 2: HEAPF32[(((params)+(i*4))>>2)]=data[i]; break;
7176
case 5: HEAP32[(((params)+(i*4))>>2)]=Math.fround(data[i]); break;
7177
default: throw 'internal emscriptenWebGLGetVertexAttrib() error, bad type: ' + type;
7178
}
7179
}
7180
}
7181
}function _emscripten_glGetVertexAttribfv(index, pname, params) {
7182
// N.B. This function may only be called if the vertex attribute was specified using the function glVertexAttrib*f(),
7183
// otherwise the results are undefined. (GLES3 spec 6.1.12)
7184
emscriptenWebGLGetVertexAttrib(index, pname, params, 2);
7185
}
7186
7187
function _emscripten_glGetVertexAttribiv(index, pname, params) {
7188
// N.B. This function may only be called if the vertex attribute was specified using the function glVertexAttrib*f(),
7189
// otherwise the results are undefined. (GLES3 spec 6.1.12)
7190
emscriptenWebGLGetVertexAttrib(index, pname, params, 5);
7191
}
7192
7193
function _emscripten_glHint(x0, x1) { GLctx['hint'](x0, x1) }
7194
7195
function _emscripten_glIsBuffer(buffer) {
7196
var b = GL.buffers[buffer];
7197
if (!b) return 0;
7198
return GLctx.isBuffer(b);
7199
}
7200
7201
function _emscripten_glIsEnabled(x0) { return GLctx['isEnabled'](x0) }
7202
7203
function _emscripten_glIsFramebuffer(framebuffer) {
7204
var fb = GL.framebuffers[framebuffer];
7205
if (!fb) return 0;
7206
return GLctx.isFramebuffer(fb);
7207
}
7208
7209
function _emscripten_glIsProgram(program) {
7210
program = GL.programs[program];
7211
if (!program) return 0;
7212
return GLctx.isProgram(program);
7213
}
7214
7215
function _emscripten_glIsQueryEXT(id) {
7216
var query = GL.timerQueriesEXT[id];
7217
if (!query) return 0;
7218
return GLctx.disjointTimerQueryExt['isQueryEXT'](query);
7219
}
7220
7221
function _emscripten_glIsRenderbuffer(renderbuffer) {
7222
var rb = GL.renderbuffers[renderbuffer];
7223
if (!rb) return 0;
7224
return GLctx.isRenderbuffer(rb);
7225
}
7226
7227
function _emscripten_glIsShader(shader) {
7228
var s = GL.shaders[shader];
7229
if (!s) return 0;
7230
return GLctx.isShader(s);
7231
}
7232
7233
function _emscripten_glIsTexture(id) {
7234
var texture = GL.textures[id];
7235
if (!texture) return 0;
7236
return GLctx.isTexture(texture);
7237
}
7238
7239
function _emscripten_glIsVertexArrayOES(array) {
7240
7241
var vao = GL.vaos[array];
7242
if (!vao) return 0;
7243
return GLctx['isVertexArray'](vao);
7244
}
7245
7246
function _emscripten_glLineWidth(x0) { GLctx['lineWidth'](x0) }
7247
7248
function _emscripten_glLinkProgram(program) {
7249
GLctx.linkProgram(GL.programs[program]);
7250
GL.populateUniformTable(program);
7251
}
7252
7253
function _emscripten_glPixelStorei(pname, param) {
7254
if (pname == 0xCF5 /* GL_UNPACK_ALIGNMENT */) {
7255
GL.unpackAlignment = param;
7256
}
7257
GLctx.pixelStorei(pname, param);
7258
}
7259
7260
function _emscripten_glPolygonOffset(x0, x1) { GLctx['polygonOffset'](x0, x1) }
7261
7262
function _emscripten_glQueryCounterEXT(id, target) {
7263
GLctx.disjointTimerQueryExt['queryCounterEXT'](GL.timerQueriesEXT[id], target);
7264
}
7265
7266
7267
7268
function __computeUnpackAlignedImageSize(width, height, sizePerPixel, alignment) {
7269
function roundedToNextMultipleOf(x, y) {
7270
return (x + y - 1) & -y;
7271
}
7272
var plainRowSize = width * sizePerPixel;
7273
var alignedRowSize = roundedToNextMultipleOf(plainRowSize, alignment);
7274
return height * alignedRowSize;
7275
}
7276
7277
function __colorChannelsInGlTextureFormat(format) {
7278
// Micro-optimizations for size: map format to size by subtracting smallest enum value (0x1902) from all values first.
7279
// Also omit the most common size value (1) from the list, which is assumed by formats not on the list.
7280
var colorChannels = {
7281
// 0x1902 /* GL_DEPTH_COMPONENT */ - 0x1902: 1,
7282
// 0x1906 /* GL_ALPHA */ - 0x1902: 1,
7283
5: 3,
7284
6: 4,
7285
// 0x1909 /* GL_LUMINANCE */ - 0x1902: 1,
7286
8: 2,
7287
29502: 3,
7288
29504: 4,
7289
};
7290
return colorChannels[format - 0x1902]||1;
7291
}
7292
7293
function __heapObjectForWebGLType(type) {
7294
// Micro-optimization for size: Subtract lowest GL enum number (0x1400/* GL_BYTE */) from type to compare
7295
// smaller values for the heap, for shorter generated code size.
7296
// Also the type HEAPU16 is not tested for explicitly, but any unrecognized type will return out HEAPU16.
7297
// (since most types are HEAPU16)
7298
type -= 0x1400;
7299
7300
if (type == 1) return HEAPU8;
7301
7302
7303
if (type == 4) return HEAP32;
7304
7305
if (type == 6) return HEAPF32;
7306
7307
if (type == 5
7308
|| type == 28922
7309
)
7310
return HEAPU32;
7311
7312
return HEAPU16;
7313
}
7314
7315
function __heapAccessShiftForWebGLHeap(heap) {
7316
return 31 - Math.clz32(heap.BYTES_PER_ELEMENT);
7317
}function emscriptenWebGLGetTexPixelData(type, format, width, height, pixels, internalFormat) {
7318
var heap = __heapObjectForWebGLType(type);
7319
var shift = __heapAccessShiftForWebGLHeap(heap);
7320
var byteSize = 1<<shift;
7321
var sizePerPixel = __colorChannelsInGlTextureFormat(format) * byteSize;
7322
var bytes = __computeUnpackAlignedImageSize(width, height, sizePerPixel, GL.unpackAlignment);
7323
return heap.subarray(pixels >> shift, pixels + bytes >> shift);
7324
}function _emscripten_glReadPixels(x, y, width, height, format, type, pixels) {
7325
var pixelData = emscriptenWebGLGetTexPixelData(type, format, width, height, pixels, format);
7326
if (!pixelData) {
7327
GL.recordError(0x500/*GL_INVALID_ENUM*/);
7328
return;
7329
}
7330
GLctx.readPixels(x, y, width, height, format, type, pixelData);
7331
}
7332
7333
function _emscripten_glReleaseShaderCompiler() {
7334
// NOP (as allowed by GLES 2.0 spec)
7335
}
7336
7337
function _emscripten_glRenderbufferStorage(x0, x1, x2, x3) { GLctx['renderbufferStorage'](x0, x1, x2, x3) }
7338
7339
function _emscripten_glSampleCoverage(value, invert) {
7340
GLctx.sampleCoverage(value, !!invert);
7341
}
7342
7343
function _emscripten_glScissor(x0, x1, x2, x3) { GLctx['scissor'](x0, x1, x2, x3) }
7344
7345
function _emscripten_glShaderBinary() {
7346
GL.recordError(0x500/*GL_INVALID_ENUM*/);
7347
}
7348
7349
function _emscripten_glShaderSource(shader, count, string, length) {
7350
var source = GL.getSource(shader, count, string, length);
7351
7352
7353
GLctx.shaderSource(GL.shaders[shader], source);
7354
}
7355
7356
function _emscripten_glStencilFunc(x0, x1, x2) { GLctx['stencilFunc'](x0, x1, x2) }
7357
7358
function _emscripten_glStencilFuncSeparate(x0, x1, x2, x3) { GLctx['stencilFuncSeparate'](x0, x1, x2, x3) }
7359
7360
function _emscripten_glStencilMask(x0) { GLctx['stencilMask'](x0) }
7361
7362
function _emscripten_glStencilMaskSeparate(x0, x1) { GLctx['stencilMaskSeparate'](x0, x1) }
7363
7364
function _emscripten_glStencilOp(x0, x1, x2) { GLctx['stencilOp'](x0, x1, x2) }
7365
7366
function _emscripten_glStencilOpSeparate(x0, x1, x2, x3) { GLctx['stencilOpSeparate'](x0, x1, x2, x3) }
7367
7368
function _emscripten_glTexImage2D(target, level, internalFormat, width, height, border, format, type, pixels) {
7369
GLctx.texImage2D(target, level, internalFormat, width, height, border, format, type, pixels ? emscriptenWebGLGetTexPixelData(type, format, width, height, pixels, internalFormat) : null);
7370
}
7371
7372
function _emscripten_glTexParameterf(x0, x1, x2) { GLctx['texParameterf'](x0, x1, x2) }
7373
7374
function _emscripten_glTexParameterfv(target, pname, params) {
7375
var param = HEAPF32[((params)>>2)];
7376
GLctx.texParameterf(target, pname, param);
7377
}
7378
7379
function _emscripten_glTexParameteri(x0, x1, x2) { GLctx['texParameteri'](x0, x1, x2) }
7380
7381
function _emscripten_glTexParameteriv(target, pname, params) {
7382
var param = HEAP32[((params)>>2)];
7383
GLctx.texParameteri(target, pname, param);
7384
}
7385
7386
function _emscripten_glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels) {
7387
var pixelData = null;
7388
if (pixels) pixelData = emscriptenWebGLGetTexPixelData(type, format, width, height, pixels, 0);
7389
GLctx.texSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixelData);
7390
}
7391
7392
function _emscripten_glUniform1f(location, v0) {
7393
GLctx.uniform1f(GL.uniforms[location], v0);
7394
}
7395
7396
function _emscripten_glUniform1fv(location, count, value) {
7397
7398
7399
if (count <= GL.MINI_TEMP_BUFFER_SIZE) {
7400
// avoid allocation when uploading few enough uniforms
7401
var view = GL.miniTempBufferFloatViews[count-1];
7402
for (var i = 0; i < count; ++i) {
7403
view[i] = HEAPF32[(((value)+(4*i))>>2)];
7404
}
7405
} else
7406
{
7407
var view = HEAPF32.subarray((value)>>2,(value+count*4)>>2);
7408
}
7409
GLctx.uniform1fv(GL.uniforms[location], view);
7410
}
7411
7412
function _emscripten_glUniform1i(location, v0) {
7413
GLctx.uniform1i(GL.uniforms[location], v0);
7414
}
7415
7416
function _emscripten_glUniform1iv(location, count, value) {
7417
7418
7419
if (count <= GL.MINI_TEMP_BUFFER_SIZE) {
7420
// avoid allocation when uploading few enough uniforms
7421
var view = GL.miniTempBufferIntViews[count-1];
7422
for (var i = 0; i < count; ++i) {
7423
view[i] = HEAP32[(((value)+(4*i))>>2)];
7424
}
7425
} else
7426
{
7427
var view = HEAP32.subarray((value)>>2,(value+count*4)>>2);
7428
}
7429
GLctx.uniform1iv(GL.uniforms[location], view);
7430
}
7431
7432
function _emscripten_glUniform2f(location, v0, v1) {
7433
GLctx.uniform2f(GL.uniforms[location], v0, v1);
7434
}
7435
7436
function _emscripten_glUniform2fv(location, count, value) {
7437
7438
7439
if (2*count <= GL.MINI_TEMP_BUFFER_SIZE) {
7440
// avoid allocation when uploading few enough uniforms
7441
var view = GL.miniTempBufferFloatViews[2*count-1];
7442
for (var i = 0; i < 2*count; i += 2) {
7443
view[i] = HEAPF32[(((value)+(4*i))>>2)];
7444
view[i+1] = HEAPF32[(((value)+(4*i+4))>>2)];
7445
}
7446
} else
7447
{
7448
var view = HEAPF32.subarray((value)>>2,(value+count*8)>>2);
7449
}
7450
GLctx.uniform2fv(GL.uniforms[location], view);
7451
}
7452
7453
function _emscripten_glUniform2i(location, v0, v1) {
7454
GLctx.uniform2i(GL.uniforms[location], v0, v1);
7455
}
7456
7457
function _emscripten_glUniform2iv(location, count, value) {
7458
7459
7460
if (2*count <= GL.MINI_TEMP_BUFFER_SIZE) {
7461
// avoid allocation when uploading few enough uniforms
7462
var view = GL.miniTempBufferIntViews[2*count-1];
7463
for (var i = 0; i < 2*count; i += 2) {
7464
view[i] = HEAP32[(((value)+(4*i))>>2)];
7465
view[i+1] = HEAP32[(((value)+(4*i+4))>>2)];
7466
}
7467
} else
7468
{
7469
var view = HEAP32.subarray((value)>>2,(value+count*8)>>2);
7470
}
7471
GLctx.uniform2iv(GL.uniforms[location], view);
7472
}
7473
7474
function _emscripten_glUniform3f(location, v0, v1, v2) {
7475
GLctx.uniform3f(GL.uniforms[location], v0, v1, v2);
7476
}
7477
7478
function _emscripten_glUniform3fv(location, count, value) {
7479
7480
7481
if (3*count <= GL.MINI_TEMP_BUFFER_SIZE) {
7482
// avoid allocation when uploading few enough uniforms
7483
var view = GL.miniTempBufferFloatViews[3*count-1];
7484
for (var i = 0; i < 3*count; i += 3) {
7485
view[i] = HEAPF32[(((value)+(4*i))>>2)];
7486
view[i+1] = HEAPF32[(((value)+(4*i+4))>>2)];
7487
view[i+2] = HEAPF32[(((value)+(4*i+8))>>2)];
7488
}
7489
} else
7490
{
7491
var view = HEAPF32.subarray((value)>>2,(value+count*12)>>2);
7492
}
7493
GLctx.uniform3fv(GL.uniforms[location], view);
7494
}
7495
7496
function _emscripten_glUniform3i(location, v0, v1, v2) {
7497
GLctx.uniform3i(GL.uniforms[location], v0, v1, v2);
7498
}
7499
7500
function _emscripten_glUniform3iv(location, count, value) {
7501
7502
7503
if (3*count <= GL.MINI_TEMP_BUFFER_SIZE) {
7504
// avoid allocation when uploading few enough uniforms
7505
var view = GL.miniTempBufferIntViews[3*count-1];
7506
for (var i = 0; i < 3*count; i += 3) {
7507
view[i] = HEAP32[(((value)+(4*i))>>2)];
7508
view[i+1] = HEAP32[(((value)+(4*i+4))>>2)];
7509
view[i+2] = HEAP32[(((value)+(4*i+8))>>2)];
7510
}
7511
} else
7512
{
7513
var view = HEAP32.subarray((value)>>2,(value+count*12)>>2);
7514
}
7515
GLctx.uniform3iv(GL.uniforms[location], view);
7516
}
7517
7518
function _emscripten_glUniform4f(location, v0, v1, v2, v3) {
7519
GLctx.uniform4f(GL.uniforms[location], v0, v1, v2, v3);
7520
}
7521
7522
function _emscripten_glUniform4fv(location, count, value) {
7523
7524
7525
if (4*count <= GL.MINI_TEMP_BUFFER_SIZE) {
7526
// avoid allocation when uploading few enough uniforms
7527
var view = GL.miniTempBufferFloatViews[4*count-1];
7528
// hoist the heap out of the loop for size and for pthreads+growth.
7529
var heap = HEAPF32;
7530
value >>= 2;
7531
for (var i = 0; i < 4 * count; i += 4) {
7532
var dst = value + i;
7533
view[i] = heap[dst];
7534
view[i + 1] = heap[dst + 1];
7535
view[i + 2] = heap[dst + 2];
7536
view[i + 3] = heap[dst + 3];
7537
}
7538
} else
7539
{
7540
var view = HEAPF32.subarray((value)>>2,(value+count*16)>>2);
7541
}
7542
GLctx.uniform4fv(GL.uniforms[location], view);
7543
}
7544
7545
function _emscripten_glUniform4i(location, v0, v1, v2, v3) {
7546
GLctx.uniform4i(GL.uniforms[location], v0, v1, v2, v3);
7547
}
7548
7549
function _emscripten_glUniform4iv(location, count, value) {
7550
7551
7552
if (4*count <= GL.MINI_TEMP_BUFFER_SIZE) {
7553
// avoid allocation when uploading few enough uniforms
7554
var view = GL.miniTempBufferIntViews[4*count-1];
7555
for (var i = 0; i < 4*count; i += 4) {
7556
view[i] = HEAP32[(((value)+(4*i))>>2)];
7557
view[i+1] = HEAP32[(((value)+(4*i+4))>>2)];
7558
view[i+2] = HEAP32[(((value)+(4*i+8))>>2)];
7559
view[i+3] = HEAP32[(((value)+(4*i+12))>>2)];
7560
}
7561
} else
7562
{
7563
var view = HEAP32.subarray((value)>>2,(value+count*16)>>2);
7564
}
7565
GLctx.uniform4iv(GL.uniforms[location], view);
7566
}
7567
7568
function _emscripten_glUniformMatrix2fv(location, count, transpose, value) {
7569
7570
7571
if (4*count <= GL.MINI_TEMP_BUFFER_SIZE) {
7572
// avoid allocation when uploading few enough uniforms
7573
var view = GL.miniTempBufferFloatViews[4*count-1];
7574
for (var i = 0; i < 4*count; i += 4) {
7575
view[i] = HEAPF32[(((value)+(4*i))>>2)];
7576
view[i+1] = HEAPF32[(((value)+(4*i+4))>>2)];
7577
view[i+2] = HEAPF32[(((value)+(4*i+8))>>2)];
7578
view[i+3] = HEAPF32[(((value)+(4*i+12))>>2)];
7579
}
7580
} else
7581
{
7582
var view = HEAPF32.subarray((value)>>2,(value+count*16)>>2);
7583
}
7584
GLctx.uniformMatrix2fv(GL.uniforms[location], !!transpose, view);
7585
}
7586
7587
function _emscripten_glUniformMatrix3fv(location, count, transpose, value) {
7588
7589
7590
if (9*count <= GL.MINI_TEMP_BUFFER_SIZE) {
7591
// avoid allocation when uploading few enough uniforms
7592
var view = GL.miniTempBufferFloatViews[9*count-1];
7593
for (var i = 0; i < 9*count; i += 9) {
7594
view[i] = HEAPF32[(((value)+(4*i))>>2)];
7595
view[i+1] = HEAPF32[(((value)+(4*i+4))>>2)];
7596
view[i+2] = HEAPF32[(((value)+(4*i+8))>>2)];
7597
view[i+3] = HEAPF32[(((value)+(4*i+12))>>2)];
7598
view[i+4] = HEAPF32[(((value)+(4*i+16))>>2)];
7599
view[i+5] = HEAPF32[(((value)+(4*i+20))>>2)];
7600
view[i+6] = HEAPF32[(((value)+(4*i+24))>>2)];
7601
view[i+7] = HEAPF32[(((value)+(4*i+28))>>2)];
7602
view[i+8] = HEAPF32[(((value)+(4*i+32))>>2)];
7603
}
7604
} else
7605
{
7606
var view = HEAPF32.subarray((value)>>2,(value+count*36)>>2);
7607
}
7608
GLctx.uniformMatrix3fv(GL.uniforms[location], !!transpose, view);
7609
}
7610
7611
function _emscripten_glUniformMatrix4fv(location, count, transpose, value) {
7612
7613
7614
if (16*count <= GL.MINI_TEMP_BUFFER_SIZE) {
7615
// avoid allocation when uploading few enough uniforms
7616
var view = GL.miniTempBufferFloatViews[16*count-1];
7617
// hoist the heap out of the loop for size and for pthreads+growth.
7618
var heap = HEAPF32;
7619
value >>= 2;
7620
for (var i = 0; i < 16 * count; i += 16) {
7621
var dst = value + i;
7622
view[i] = heap[dst];
7623
view[i + 1] = heap[dst + 1];
7624
view[i + 2] = heap[dst + 2];
7625
view[i + 3] = heap[dst + 3];
7626
view[i + 4] = heap[dst + 4];
7627
view[i + 5] = heap[dst + 5];
7628
view[i + 6] = heap[dst + 6];
7629
view[i + 7] = heap[dst + 7];
7630
view[i + 8] = heap[dst + 8];
7631
view[i + 9] = heap[dst + 9];
7632
view[i + 10] = heap[dst + 10];
7633
view[i + 11] = heap[dst + 11];
7634
view[i + 12] = heap[dst + 12];
7635
view[i + 13] = heap[dst + 13];
7636
view[i + 14] = heap[dst + 14];
7637
view[i + 15] = heap[dst + 15];
7638
}
7639
} else
7640
{
7641
var view = HEAPF32.subarray((value)>>2,(value+count*64)>>2);
7642
}
7643
GLctx.uniformMatrix4fv(GL.uniforms[location], !!transpose, view);
7644
}
7645
7646
function _emscripten_glUseProgram(program) {
7647
GLctx.useProgram(GL.programs[program]);
7648
}
7649
7650
function _emscripten_glValidateProgram(program) {
7651
GLctx.validateProgram(GL.programs[program]);
7652
}
7653
7654
function _emscripten_glVertexAttrib1f(x0, x1) { GLctx['vertexAttrib1f'](x0, x1) }
7655
7656
function _emscripten_glVertexAttrib1fv(index, v) {
7657
7658
GLctx.vertexAttrib1f(index, HEAPF32[v>>2]);
7659
}
7660
7661
function _emscripten_glVertexAttrib2f(x0, x1, x2) { GLctx['vertexAttrib2f'](x0, x1, x2) }
7662
7663
function _emscripten_glVertexAttrib2fv(index, v) {
7664
7665
GLctx.vertexAttrib2f(index, HEAPF32[v>>2], HEAPF32[v+4>>2]);
7666
}
7667
7668
function _emscripten_glVertexAttrib3f(x0, x1, x2, x3) { GLctx['vertexAttrib3f'](x0, x1, x2, x3) }
7669
7670
function _emscripten_glVertexAttrib3fv(index, v) {
7671
7672
GLctx.vertexAttrib3f(index, HEAPF32[v>>2], HEAPF32[v+4>>2], HEAPF32[v+8>>2]);
7673
}
7674
7675
function _emscripten_glVertexAttrib4f(x0, x1, x2, x3, x4) { GLctx['vertexAttrib4f'](x0, x1, x2, x3, x4) }
7676
7677
function _emscripten_glVertexAttrib4fv(index, v) {
7678
7679
GLctx.vertexAttrib4f(index, HEAPF32[v>>2], HEAPF32[v+4>>2], HEAPF32[v+8>>2], HEAPF32[v+12>>2]);
7680
}
7681
7682
function _emscripten_glVertexAttribDivisorANGLE(index, divisor) {
7683
GLctx['vertexAttribDivisor'](index, divisor);
7684
}
7685
7686
function _emscripten_glVertexAttribPointer(index, size, type, normalized, stride, ptr) {
7687
GLctx.vertexAttribPointer(index, size, type, !!normalized, stride, ptr);
7688
}
7689
7690
function _emscripten_glViewport(x0, x1, x2, x3) { GLctx['viewport'](x0, x1, x2, x3) }
7691
7692
function _emscripten_has_asyncify() {
7693
return 0;
7694
}
7695
7696
function _emscripten_memcpy_big(dest, src, num) {
7697
HEAPU8.copyWithin(dest, src, src + num);
7698
}
7699
7700
7701
function __emscripten_do_request_fullscreen(target, strategy) {
7702
if (!JSEvents.fullscreenEnabled()) return -1;
7703
target = __findEventTarget(target);
7704
if (!target) return -4;
7705
7706
if (!target.requestFullscreen
7707
&& !target.webkitRequestFullscreen
7708
) {
7709
return -3;
7710
}
7711
7712
var canPerformRequests = JSEvents.canPerformEventHandlerRequests();
7713
7714
// Queue this function call if we're not currently in an event handler and the user saw it appropriate to do so.
7715
if (!canPerformRequests) {
7716
if (strategy.deferUntilInEventHandler) {
7717
JSEvents.deferCall(_JSEvents_requestFullscreen, 1 /* priority over pointer lock */, [target, strategy]);
7718
return 1;
7719
} else {
7720
return -2;
7721
}
7722
}
7723
7724
return _JSEvents_requestFullscreen(target, strategy);
7725
}function _emscripten_request_fullscreen_strategy(target, deferUntilInEventHandler, fullscreenStrategy) {
7726
var strategy = {
7727
scaleMode: HEAP32[((fullscreenStrategy)>>2)],
7728
canvasResolutionScaleMode: HEAP32[(((fullscreenStrategy)+(4))>>2)],
7729
filteringMode: HEAP32[(((fullscreenStrategy)+(8))>>2)],
7730
deferUntilInEventHandler: deferUntilInEventHandler,
7731
canvasResizedCallback: HEAP32[(((fullscreenStrategy)+(12))>>2)],
7732
canvasResizedCallbackUserData: HEAP32[(((fullscreenStrategy)+(16))>>2)]
7733
};
7734
__currentFullscreenStrategy = strategy;
7735
7736
return __emscripten_do_request_fullscreen(target, strategy);
7737
}
7738
7739
function _emscripten_request_pointerlock(target, deferUntilInEventHandler) {
7740
target = __findEventTarget(target);
7741
if (!target) return -4;
7742
if (!target.requestPointerLock
7743
&& !target.msRequestPointerLock
7744
) {
7745
return -1;
7746
}
7747
7748
var canPerformRequests = JSEvents.canPerformEventHandlerRequests();
7749
7750
// Queue this function call if we're not currently in an event handler and the user saw it appropriate to do so.
7751
if (!canPerformRequests) {
7752
if (deferUntilInEventHandler) {
7753
JSEvents.deferCall(__requestPointerLock, 2 /* priority below fullscreen */, [target]);
7754
return 1;
7755
} else {
7756
return -2;
7757
}
7758
}
7759
7760
return __requestPointerLock(target);
7761
}
7762
7763
7764
function _emscripten_get_heap_size() {
7765
return HEAPU8.length;
7766
}
7767
7768
function abortOnCannotGrowMemory(requestedSize) {
7769
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 ');
7770
}function _emscripten_resize_heap(requestedSize) {
7771
abortOnCannotGrowMemory(requestedSize);
7772
}
7773
7774
function _emscripten_sample_gamepad_data() {
7775
return (JSEvents.lastGamepadState = (navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : null)))
7776
? 0 : -1;
7777
}
7778
7779
7780
function __registerBeforeUnloadEventCallback(target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString) {
7781
var beforeUnloadEventHandlerFunc = function(ev) {
7782
var e = ev || event;
7783
7784
// Note: This is always called on the main browser thread, since it needs synchronously return a value!
7785
var confirmationMessage = dynCall_iiii(callbackfunc, eventTypeId, 0, userData);
7786
7787
if (confirmationMessage) {
7788
confirmationMessage = UTF8ToString(confirmationMessage);
7789
}
7790
if (confirmationMessage) {
7791
e.preventDefault();
7792
e.returnValue = confirmationMessage;
7793
return confirmationMessage;
7794
}
7795
};
7796
7797
var eventHandler = {
7798
target: __findEventTarget(target),
7799
eventTypeString: eventTypeString,
7800
callbackfunc: callbackfunc,
7801
handlerFunc: beforeUnloadEventHandlerFunc,
7802
useCapture: useCapture
7803
};
7804
JSEvents.registerOrRemoveHandler(eventHandler);
7805
}function _emscripten_set_beforeunload_callback_on_thread(userData, callbackfunc, targetThread) {
7806
if (typeof onbeforeunload === 'undefined') return -1;
7807
// beforeunload callback can only be registered on the main browser thread, because the page will go away immediately after returning from the handler,
7808
// and there is no time to start proxying it anywhere.
7809
if (targetThread !== 1) return -5;
7810
__registerBeforeUnloadEventCallback(2, userData, true, callbackfunc, 28, "beforeunload");
7811
return 0;
7812
}
7813
7814
7815
function __registerFocusEventCallback(target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) {
7816
if (!JSEvents.focusEvent) JSEvents.focusEvent = _malloc( 256 );
7817
7818
var focusEventHandlerFunc = function(ev) {
7819
var e = ev || event;
7820
7821
var nodeName = JSEvents.getNodeNameForTarget(e.target);
7822
var id = e.target.id ? e.target.id : '';
7823
7824
var focusEvent = JSEvents.focusEvent;
7825
stringToUTF8(nodeName, focusEvent + 0, 128);
7826
stringToUTF8(id, focusEvent + 128, 128);
7827
7828
if (dynCall_iiii(callbackfunc, eventTypeId, focusEvent, userData)) e.preventDefault();
7829
};
7830
7831
var eventHandler = {
7832
target: __findEventTarget(target),
7833
eventTypeString: eventTypeString,
7834
callbackfunc: callbackfunc,
7835
handlerFunc: focusEventHandlerFunc,
7836
useCapture: useCapture
7837
};
7838
JSEvents.registerOrRemoveHandler(eventHandler);
7839
}function _emscripten_set_blur_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) {
7840
__registerFocusEventCallback(target, userData, useCapture, callbackfunc, 12, "blur", targetThread);
7841
return 0;
7842
}
7843
7844
7845
function _emscripten_set_element_css_size(target, width, height) {
7846
target = __findEventTarget(target);
7847
if (!target) return -4;
7848
7849
target.style.width = width + "px";
7850
target.style.height = height + "px";
7851
7852
return 0;
7853
}
7854
7855
function _emscripten_set_focus_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) {
7856
__registerFocusEventCallback(target, userData, useCapture, callbackfunc, 13, "focus", targetThread);
7857
return 0;
7858
}
7859
7860
7861
7862
function __fillFullscreenChangeEventData(eventStruct) {
7863
var fullscreenElement = document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement || document.msFullscreenElement;
7864
var isFullscreen = !!fullscreenElement;
7865
/** @suppress{checkTypes} */
7866
HEAP32[((eventStruct)>>2)]=isFullscreen;
7867
HEAP32[(((eventStruct)+(4))>>2)]=JSEvents.fullscreenEnabled();
7868
// If transitioning to fullscreen, report info about the element that is now fullscreen.
7869
// If transitioning to windowed mode, report info about the element that just was fullscreen.
7870
var reportedElement = isFullscreen ? fullscreenElement : JSEvents.previousFullscreenElement;
7871
var nodeName = JSEvents.getNodeNameForTarget(reportedElement);
7872
var id = (reportedElement && reportedElement.id) ? reportedElement.id : '';
7873
stringToUTF8(nodeName, eventStruct + 8, 128);
7874
stringToUTF8(id, eventStruct + 136, 128);
7875
HEAP32[(((eventStruct)+(264))>>2)]=reportedElement ? reportedElement.clientWidth : 0;
7876
HEAP32[(((eventStruct)+(268))>>2)]=reportedElement ? reportedElement.clientHeight : 0;
7877
HEAP32[(((eventStruct)+(272))>>2)]=screen.width;
7878
HEAP32[(((eventStruct)+(276))>>2)]=screen.height;
7879
if (isFullscreen) {
7880
JSEvents.previousFullscreenElement = fullscreenElement;
7881
}
7882
}function __registerFullscreenChangeEventCallback(target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) {
7883
if (!JSEvents.fullscreenChangeEvent) JSEvents.fullscreenChangeEvent = _malloc( 280 );
7884
7885
var fullscreenChangeEventhandlerFunc = function(ev) {
7886
var e = ev || event;
7887
7888
var fullscreenChangeEvent = JSEvents.fullscreenChangeEvent;
7889
7890
__fillFullscreenChangeEventData(fullscreenChangeEvent);
7891
7892
if (dynCall_iiii(callbackfunc, eventTypeId, fullscreenChangeEvent, userData)) e.preventDefault();
7893
};
7894
7895
var eventHandler = {
7896
target: target,
7897
eventTypeString: eventTypeString,
7898
callbackfunc: callbackfunc,
7899
handlerFunc: fullscreenChangeEventhandlerFunc,
7900
useCapture: useCapture
7901
};
7902
JSEvents.registerOrRemoveHandler(eventHandler);
7903
}function _emscripten_set_fullscreenchange_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) {
7904
if (!JSEvents.fullscreenEnabled()) return -1;
7905
target = __findEventTarget(target);
7906
if (!target) return -4;
7907
__registerFullscreenChangeEventCallback(target, userData, useCapture, callbackfunc, 19, "fullscreenchange", targetThread);
7908
7909
7910
// Unprefixed Fullscreen API shipped in Chromium 71 (https://bugs.chromium.org/p/chromium/issues/detail?id=383813)
7911
// 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.
7912
__registerFullscreenChangeEventCallback(target, userData, useCapture, callbackfunc, 19, "webkitfullscreenchange", targetThread);
7913
7914
return 0;
7915
}
7916
7917
7918
function __registerGamepadEventCallback(target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) {
7919
if (!JSEvents.gamepadEvent) JSEvents.gamepadEvent = _malloc( 1432 );
7920
7921
var gamepadEventHandlerFunc = function(ev) {
7922
var e = ev || event;
7923
7924
var gamepadEvent = JSEvents.gamepadEvent;
7925
__fillGamepadEventData(gamepadEvent, e["gamepad"]);
7926
7927
if (dynCall_iiii(callbackfunc, eventTypeId, gamepadEvent, userData)) e.preventDefault();
7928
};
7929
7930
var eventHandler = {
7931
target: __findEventTarget(target),
7932
allowsDeferredCalls: true,
7933
eventTypeString: eventTypeString,
7934
callbackfunc: callbackfunc,
7935
handlerFunc: gamepadEventHandlerFunc,
7936
useCapture: useCapture
7937
};
7938
JSEvents.registerOrRemoveHandler(eventHandler);
7939
}function _emscripten_set_gamepadconnected_callback_on_thread(userData, useCapture, callbackfunc, targetThread) {
7940
if (!navigator.getGamepads && !navigator.webkitGetGamepads) return -1;
7941
__registerGamepadEventCallback(2, userData, useCapture, callbackfunc, 26, "gamepadconnected", targetThread);
7942
return 0;
7943
}
7944
7945
function _emscripten_set_gamepaddisconnected_callback_on_thread(userData, useCapture, callbackfunc, targetThread) {
7946
if (!navigator.getGamepads && !navigator.webkitGetGamepads) return -1;
7947
__registerGamepadEventCallback(2, userData, useCapture, callbackfunc, 27, "gamepaddisconnected", targetThread);
7948
return 0;
7949
}
7950
7951
7952
function __registerKeyEventCallback(target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) {
7953
if (!JSEvents.keyEvent) JSEvents.keyEvent = _malloc( 164 );
7954
7955
var keyEventHandlerFunc = function(ev) {
7956
var e = ev || event;
7957
7958
var keyEventData = JSEvents.keyEvent;
7959
stringToUTF8(e.key ? e.key : "", keyEventData + 0, 32);
7960
stringToUTF8(e.code ? e.code : "", keyEventData + 32, 32);
7961
HEAP32[(((keyEventData)+(64))>>2)]=e.location;
7962
HEAP32[(((keyEventData)+(68))>>2)]=e.ctrlKey;
7963
HEAP32[(((keyEventData)+(72))>>2)]=e.shiftKey;
7964
HEAP32[(((keyEventData)+(76))>>2)]=e.altKey;
7965
HEAP32[(((keyEventData)+(80))>>2)]=e.metaKey;
7966
HEAP32[(((keyEventData)+(84))>>2)]=e.repeat;
7967
stringToUTF8(e.locale ? e.locale : "", keyEventData + 88, 32);
7968
stringToUTF8(e.char ? e.char : "", keyEventData + 120, 32);
7969
HEAP32[(((keyEventData)+(152))>>2)]=e.charCode;
7970
HEAP32[(((keyEventData)+(156))>>2)]=e.keyCode;
7971
HEAP32[(((keyEventData)+(160))>>2)]=e.which;
7972
7973
if (dynCall_iiii(callbackfunc, eventTypeId, keyEventData, userData)) e.preventDefault();
7974
};
7975
7976
var eventHandler = {
7977
target: __findEventTarget(target),
7978
allowsDeferredCalls: true,
7979
eventTypeString: eventTypeString,
7980
callbackfunc: callbackfunc,
7981
handlerFunc: keyEventHandlerFunc,
7982
useCapture: useCapture
7983
};
7984
JSEvents.registerOrRemoveHandler(eventHandler);
7985
}function _emscripten_set_keydown_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) {
7986
__registerKeyEventCallback(target, userData, useCapture, callbackfunc, 2, "keydown", targetThread);
7987
return 0;
7988
}
7989
7990
function _emscripten_set_keypress_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) {
7991
__registerKeyEventCallback(target, userData, useCapture, callbackfunc, 1, "keypress", targetThread);
7992
return 0;
7993
}
7994
7995
function _emscripten_set_keyup_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) {
7996
__registerKeyEventCallback(target, userData, useCapture, callbackfunc, 3, "keyup", targetThread);
7997
return 0;
7998
}
7999
8000
8001
8002
8003
function __fillMouseEventData(eventStruct, e, target) {
8004
HEAP32[((eventStruct)>>2)]=e.screenX;
8005
HEAP32[(((eventStruct)+(4))>>2)]=e.screenY;
8006
HEAP32[(((eventStruct)+(8))>>2)]=e.clientX;
8007
HEAP32[(((eventStruct)+(12))>>2)]=e.clientY;
8008
HEAP32[(((eventStruct)+(16))>>2)]=e.ctrlKey;
8009
HEAP32[(((eventStruct)+(20))>>2)]=e.shiftKey;
8010
HEAP32[(((eventStruct)+(24))>>2)]=e.altKey;
8011
HEAP32[(((eventStruct)+(28))>>2)]=e.metaKey;
8012
HEAP16[(((eventStruct)+(32))>>1)]=e.button;
8013
HEAP16[(((eventStruct)+(34))>>1)]=e.buttons;
8014
var movementX = e["movementX"]
8015
|| (e.screenX-JSEvents.previousScreenX)
8016
;
8017
var movementY = e["movementY"]
8018
|| (e.screenY-JSEvents.previousScreenY)
8019
;
8020
8021
HEAP32[(((eventStruct)+(36))>>2)]=movementX;
8022
HEAP32[(((eventStruct)+(40))>>2)]=movementY;
8023
8024
var rect = __getBoundingClientRect(target);
8025
HEAP32[(((eventStruct)+(44))>>2)]=e.clientX - rect.left;
8026
HEAP32[(((eventStruct)+(48))>>2)]=e.clientY - rect.top;
8027
8028
// wheel and mousewheel events contain wrong screenX/screenY on chrome/opera
8029
// https://github.com/emscripten-core/emscripten/pull/4997
8030
// https://bugs.chromium.org/p/chromium/issues/detail?id=699956
8031
if (e.type !== 'wheel' && e.type !== 'mousewheel') {
8032
JSEvents.previousScreenX = e.screenX;
8033
JSEvents.previousScreenY = e.screenY;
8034
}
8035
}function __registerMouseEventCallback(target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) {
8036
if (!JSEvents.mouseEvent) JSEvents.mouseEvent = _malloc( 64 );
8037
target = __findEventTarget(target);
8038
8039
var mouseEventHandlerFunc = function(ev) {
8040
var e = ev || event;
8041
8042
// TODO: Make this access thread safe, or this could update live while app is reading it.
8043
__fillMouseEventData(JSEvents.mouseEvent, e, target);
8044
8045
if (dynCall_iiii(callbackfunc, eventTypeId, JSEvents.mouseEvent, userData)) e.preventDefault();
8046
};
8047
8048
var eventHandler = {
8049
target: target,
8050
allowsDeferredCalls: eventTypeString != 'mousemove' && eventTypeString != 'mouseenter' && eventTypeString != 'mouseleave', // Mouse move events do not allow fullscreen/pointer lock requests to be handled in them!
8051
eventTypeString: eventTypeString,
8052
callbackfunc: callbackfunc,
8053
handlerFunc: mouseEventHandlerFunc,
8054
useCapture: useCapture
8055
};
8056
JSEvents.registerOrRemoveHandler(eventHandler);
8057
}function _emscripten_set_mousedown_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) {
8058
__registerMouseEventCallback(target, userData, useCapture, callbackfunc, 5, "mousedown", targetThread);
8059
return 0;
8060
}
8061
8062
function _emscripten_set_mouseenter_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) {
8063
__registerMouseEventCallback(target, userData, useCapture, callbackfunc, 33, "mouseenter", targetThread);
8064
return 0;
8065
}
8066
8067
function _emscripten_set_mouseleave_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) {
8068
__registerMouseEventCallback(target, userData, useCapture, callbackfunc, 34, "mouseleave", targetThread);
8069
return 0;
8070
}
8071
8072
function _emscripten_set_mousemove_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) {
8073
__registerMouseEventCallback(target, userData, useCapture, callbackfunc, 8, "mousemove", targetThread);
8074
return 0;
8075
}
8076
8077
function _emscripten_set_mouseup_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) {
8078
__registerMouseEventCallback(target, userData, useCapture, callbackfunc, 6, "mouseup", targetThread);
8079
return 0;
8080
}
8081
8082
8083
8084
function __fillPointerlockChangeEventData(eventStruct) {
8085
var pointerLockElement = document.pointerLockElement || document.mozPointerLockElement || document.webkitPointerLockElement || document.msPointerLockElement;
8086
var isPointerlocked = !!pointerLockElement;
8087
/** @suppress {checkTypes} */
8088
HEAP32[((eventStruct)>>2)]=isPointerlocked;
8089
var nodeName = JSEvents.getNodeNameForTarget(pointerLockElement);
8090
var id = (pointerLockElement && pointerLockElement.id) ? pointerLockElement.id : '';
8091
stringToUTF8(nodeName, eventStruct + 4, 128);
8092
stringToUTF8(id, eventStruct + 132, 128);
8093
}function __registerPointerlockChangeEventCallback(target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) {
8094
if (!JSEvents.pointerlockChangeEvent) JSEvents.pointerlockChangeEvent = _malloc( 260 );
8095
8096
var pointerlockChangeEventHandlerFunc = function(ev) {
8097
var e = ev || event;
8098
8099
var pointerlockChangeEvent = JSEvents.pointerlockChangeEvent;
8100
__fillPointerlockChangeEventData(pointerlockChangeEvent);
8101
8102
if (dynCall_iiii(callbackfunc, eventTypeId, pointerlockChangeEvent, userData)) e.preventDefault();
8103
};
8104
8105
var eventHandler = {
8106
target: target,
8107
eventTypeString: eventTypeString,
8108
callbackfunc: callbackfunc,
8109
handlerFunc: pointerlockChangeEventHandlerFunc,
8110
useCapture: useCapture
8111
};
8112
JSEvents.registerOrRemoveHandler(eventHandler);
8113
}/** @suppress {missingProperties} */
8114
function _emscripten_set_pointerlockchange_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) {
8115
// TODO: Currently not supported in pthreads or in --proxy-to-worker mode. (In pthreads mode, document object is not defined)
8116
if (!document || !document.body || (!document.body.requestPointerLock && !document.body.mozRequestPointerLock && !document.body.webkitRequestPointerLock && !document.body.msRequestPointerLock)) {
8117
return -1;
8118
}
8119
8120
target = __findEventTarget(target);
8121
if (!target) return -4;
8122
__registerPointerlockChangeEventCallback(target, userData, useCapture, callbackfunc, 20, "pointerlockchange", targetThread);
8123
__registerPointerlockChangeEventCallback(target, userData, useCapture, callbackfunc, 20, "mozpointerlockchange", targetThread);
8124
__registerPointerlockChangeEventCallback(target, userData, useCapture, callbackfunc, 20, "webkitpointerlockchange", targetThread);
8125
__registerPointerlockChangeEventCallback(target, userData, useCapture, callbackfunc, 20, "mspointerlockchange", targetThread);
8126
return 0;
8127
}
8128
8129
8130
function __registerUiEventCallback(target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) {
8131
if (!JSEvents.uiEvent) JSEvents.uiEvent = _malloc( 36 );
8132
8133
target = __findEventTarget(target);
8134
8135
var uiEventHandlerFunc = function(ev) {
8136
var e = ev || event;
8137
if (e.target != target) {
8138
// Never take ui events such as scroll via a 'bubbled' route, but always from the direct element that
8139
// was targeted. Otherwise e.g. if app logs a message in response to a page scroll, the Emscripten log
8140
// message box could cause to scroll, generating a new (bubbled) scroll message, causing a new log print,
8141
// causing a new scroll, etc..
8142
return;
8143
}
8144
var uiEvent = JSEvents.uiEvent;
8145
var b = document.body; // Take document.body to a variable, Closure compiler does not outline access to it on its own.
8146
HEAP32[((uiEvent)>>2)]=e.detail;
8147
HEAP32[(((uiEvent)+(4))>>2)]=b.clientWidth;
8148
HEAP32[(((uiEvent)+(8))>>2)]=b.clientHeight;
8149
HEAP32[(((uiEvent)+(12))>>2)]=innerWidth;
8150
HEAP32[(((uiEvent)+(16))>>2)]=innerHeight;
8151
HEAP32[(((uiEvent)+(20))>>2)]=outerWidth;
8152
HEAP32[(((uiEvent)+(24))>>2)]=outerHeight;
8153
HEAP32[(((uiEvent)+(28))>>2)]=pageXOffset;
8154
HEAP32[(((uiEvent)+(32))>>2)]=pageYOffset;
8155
if (dynCall_iiii(callbackfunc, eventTypeId, uiEvent, userData)) e.preventDefault();
8156
};
8157
8158
var eventHandler = {
8159
target: target,
8160
eventTypeString: eventTypeString,
8161
callbackfunc: callbackfunc,
8162
handlerFunc: uiEventHandlerFunc,
8163
useCapture: useCapture
8164
};
8165
JSEvents.registerOrRemoveHandler(eventHandler);
8166
}function _emscripten_set_resize_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) {
8167
__registerUiEventCallback(target, userData, useCapture, callbackfunc, 10, "resize", targetThread);
8168
return 0;
8169
}
8170
8171
8172
function __registerTouchEventCallback(target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) {
8173
if (!JSEvents.touchEvent) JSEvents.touchEvent = _malloc( 1684 );
8174
8175
target = __findEventTarget(target);
8176
8177
var touchEventHandlerFunc = function(ev) {
8178
var e = ev || event;
8179
8180
var touches = {};
8181
for(var i = 0; i < e.touches.length; ++i) {
8182
var touch = e.touches[i];
8183
touch.changed = false;
8184
touches[touch.identifier] = touch;
8185
}
8186
for(var i = 0; i < e.changedTouches.length; ++i) {
8187
var touch = e.changedTouches[i];
8188
touches[touch.identifier] = touch;
8189
touch.changed = true;
8190
}
8191
for(var i = 0; i < e.targetTouches.length; ++i) {
8192
var touch = e.targetTouches[i];
8193
touches[touch.identifier].onTarget = true;
8194
}
8195
8196
var touchEvent = JSEvents.touchEvent;
8197
var ptr = touchEvent;
8198
HEAP32[(((ptr)+(4))>>2)]=e.ctrlKey;
8199
HEAP32[(((ptr)+(8))>>2)]=e.shiftKey;
8200
HEAP32[(((ptr)+(12))>>2)]=e.altKey;
8201
HEAP32[(((ptr)+(16))>>2)]=e.metaKey;
8202
ptr += 20; // Advance to the start of the touch array.
8203
var targetRect = __getBoundingClientRect(target);
8204
var numTouches = 0;
8205
for(var i in touches) {
8206
var t = touches[i];
8207
HEAP32[((ptr)>>2)]=t.identifier;
8208
HEAP32[(((ptr)+(4))>>2)]=t.screenX;
8209
HEAP32[(((ptr)+(8))>>2)]=t.screenY;
8210
HEAP32[(((ptr)+(12))>>2)]=t.clientX;
8211
HEAP32[(((ptr)+(16))>>2)]=t.clientY;
8212
HEAP32[(((ptr)+(20))>>2)]=t.pageX;
8213
HEAP32[(((ptr)+(24))>>2)]=t.pageY;
8214
HEAP32[(((ptr)+(28))>>2)]=t.changed;
8215
HEAP32[(((ptr)+(32))>>2)]=t.onTarget;
8216
HEAP32[(((ptr)+(36))>>2)]=t.clientX - targetRect.left;
8217
HEAP32[(((ptr)+(40))>>2)]=t.clientY - targetRect.top;
8218
8219
ptr += 52;
8220
8221
if (++numTouches >= 32) {
8222
break;
8223
}
8224
}
8225
HEAP32[((touchEvent)>>2)]=numTouches;
8226
8227
if (dynCall_iiii(callbackfunc, eventTypeId, touchEvent, userData)) e.preventDefault();
8228
};
8229
8230
var eventHandler = {
8231
target: target,
8232
allowsDeferredCalls: eventTypeString == 'touchstart' || eventTypeString == 'touchend',
8233
eventTypeString: eventTypeString,
8234
callbackfunc: callbackfunc,
8235
handlerFunc: touchEventHandlerFunc,
8236
useCapture: useCapture
8237
};
8238
JSEvents.registerOrRemoveHandler(eventHandler);
8239
}function _emscripten_set_touchcancel_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) {
8240
__registerTouchEventCallback(target, userData, useCapture, callbackfunc, 25, "touchcancel", targetThread);
8241
return 0;
8242
}
8243
8244
function _emscripten_set_touchend_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) {
8245
__registerTouchEventCallback(target, userData, useCapture, callbackfunc, 23, "touchend", targetThread);
8246
return 0;
8247
}
8248
8249
function _emscripten_set_touchmove_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) {
8250
__registerTouchEventCallback(target, userData, useCapture, callbackfunc, 24, "touchmove", targetThread);
8251
return 0;
8252
}
8253
8254
function _emscripten_set_touchstart_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) {
8255
__registerTouchEventCallback(target, userData, useCapture, callbackfunc, 22, "touchstart", targetThread);
8256
return 0;
8257
}
8258
8259
8260
8261
function __fillVisibilityChangeEventData(eventStruct) {
8262
var visibilityStates = [ "hidden", "visible", "prerender", "unloaded" ];
8263
var visibilityState = visibilityStates.indexOf(document.visibilityState);
8264
8265
// Assigning a boolean to HEAP32 with expected type coercion.
8266
/** @suppress {checkTypes} */
8267
HEAP32[((eventStruct)>>2)]=document.hidden;
8268
HEAP32[(((eventStruct)+(4))>>2)]=visibilityState;
8269
}function __registerVisibilityChangeEventCallback(target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) {
8270
if (!JSEvents.visibilityChangeEvent) JSEvents.visibilityChangeEvent = _malloc( 8 );
8271
8272
var visibilityChangeEventHandlerFunc = function(ev) {
8273
var e = ev || event;
8274
8275
var visibilityChangeEvent = JSEvents.visibilityChangeEvent;
8276
8277
__fillVisibilityChangeEventData(visibilityChangeEvent);
8278
8279
if (dynCall_iiii(callbackfunc, eventTypeId, visibilityChangeEvent, userData)) e.preventDefault();
8280
};
8281
8282
var eventHandler = {
8283
target: target,
8284
eventTypeString: eventTypeString,
8285
callbackfunc: callbackfunc,
8286
handlerFunc: visibilityChangeEventHandlerFunc,
8287
useCapture: useCapture
8288
};
8289
JSEvents.registerOrRemoveHandler(eventHandler);
8290
}function _emscripten_set_visibilitychange_callback_on_thread(userData, useCapture, callbackfunc, targetThread) {
8291
if (!__specialEventTargets[1]) {
8292
return -4;
8293
}
8294
__registerVisibilityChangeEventCallback(__specialEventTargets[1], userData, useCapture, callbackfunc, 21, "visibilitychange", targetThread);
8295
return 0;
8296
}
8297
8298
8299
function __registerWheelEventCallback(target, userData, useCapture, callbackfunc, eventTypeId, eventTypeString, targetThread) {
8300
if (!JSEvents.wheelEvent) JSEvents.wheelEvent = _malloc( 96 );
8301
8302
// The DOM Level 3 events spec event 'wheel'
8303
var wheelHandlerFunc = function(ev) {
8304
var e = ev || event;
8305
var wheelEvent = JSEvents.wheelEvent;
8306
__fillMouseEventData(wheelEvent, e, target);
8307
HEAPF64[(((wheelEvent)+(64))>>3)]=e["deltaX"];
8308
HEAPF64[(((wheelEvent)+(72))>>3)]=e["deltaY"];
8309
HEAPF64[(((wheelEvent)+(80))>>3)]=e["deltaZ"];
8310
HEAP32[(((wheelEvent)+(88))>>2)]=e["deltaMode"];
8311
if (dynCall_iiii(callbackfunc, eventTypeId, wheelEvent, userData)) e.preventDefault();
8312
};
8313
// The 'mousewheel' event as implemented in Safari 6.0.5
8314
var mouseWheelHandlerFunc = function(ev) {
8315
var e = ev || event;
8316
__fillMouseEventData(JSEvents.wheelEvent, e, target);
8317
HEAPF64[(((JSEvents.wheelEvent)+(64))>>3)]=e["wheelDeltaX"] || 0;
8318
/* 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. */
8319
var wheelDeltaY = -(e["wheelDeltaY"] || e["wheelDelta"])
8320
HEAPF64[(((JSEvents.wheelEvent)+(72))>>3)]=wheelDeltaY;
8321
HEAPF64[(((JSEvents.wheelEvent)+(80))>>3)]=0 /* Not available */;
8322
HEAP32[(((JSEvents.wheelEvent)+(88))>>2)]=0 /* DOM_DELTA_PIXEL */;
8323
var shouldCancel = dynCall_iiii(callbackfunc, eventTypeId, JSEvents.wheelEvent, userData);
8324
if (shouldCancel) {
8325
e.preventDefault();
8326
}
8327
};
8328
8329
var eventHandler = {
8330
target: target,
8331
allowsDeferredCalls: true,
8332
eventTypeString: eventTypeString,
8333
callbackfunc: callbackfunc,
8334
handlerFunc: (eventTypeString == 'wheel') ? wheelHandlerFunc : mouseWheelHandlerFunc,
8335
useCapture: useCapture
8336
};
8337
JSEvents.registerOrRemoveHandler(eventHandler);
8338
}function _emscripten_set_wheel_callback_on_thread(target, userData, useCapture, callbackfunc, targetThread) {
8339
target = __findEventTarget(target);
8340
if (typeof target.onwheel !== 'undefined') {
8341
__registerWheelEventCallback(target, userData, useCapture, callbackfunc, 9, "wheel", targetThread);
8342
return 0;
8343
} else if (typeof target.onmousewheel !== 'undefined') {
8344
__registerWheelEventCallback(target, userData, useCapture, callbackfunc, 9, "mousewheel", targetThread);
8345
return 0;
8346
} else {
8347
return -1;
8348
}
8349
}
8350
8351
function _emscripten_sleep() {
8352
throw 'Please compile your program with async support in order to use asynchronous operations like emscripten_sleep';
8353
}
8354
8355
8356
8357
var ENV={};
8358
8359
function __getExecutableName() {
8360
return thisProgram || './this.program';
8361
}function _emscripten_get_environ() {
8362
if (!_emscripten_get_environ.strings) {
8363
// Default values.
8364
var env = {
8365
'USER': 'web_user',
8366
'LOGNAME': 'web_user',
8367
'PATH': '/',
8368
'PWD': '/',
8369
'HOME': '/home/web_user',
8370
// Browser language detection #8751
8371
'LANG': ((typeof navigator === 'object' && navigator.languages && navigator.languages[0]) || 'C').replace('-', '_') + '.UTF-8',
8372
'_': __getExecutableName()
8373
};
8374
// Apply the user-provided values, if any.
8375
for (var x in ENV) {
8376
env[x] = ENV[x];
8377
}
8378
var strings = [];
8379
for (var x in env) {
8380
strings.push(x + '=' + env[x]);
8381
}
8382
_emscripten_get_environ.strings = strings;
8383
}
8384
return _emscripten_get_environ.strings;
8385
}function _environ_get(__environ, environ_buf) {
8386
var strings = _emscripten_get_environ();
8387
var bufSize = 0;
8388
strings.forEach(function(string, i) {
8389
var ptr = environ_buf + bufSize;
8390
HEAP32[(((__environ)+(i * 4))>>2)]=ptr;
8391
writeAsciiToMemory(string, ptr);
8392
bufSize += string.length + 1;
8393
});
8394
return 0;
8395
}
8396
8397
function _environ_sizes_get(penviron_count, penviron_buf_size) {
8398
var strings = _emscripten_get_environ();
8399
HEAP32[((penviron_count)>>2)]=strings.length;
8400
var bufSize = 0;
8401
strings.forEach(function(string) {
8402
bufSize += string.length + 1;
8403
});
8404
HEAP32[((penviron_buf_size)>>2)]=bufSize;
8405
return 0;
8406
}
8407
8408
function _exit(status) {
8409
// void _exit(int status);
8410
// http://pubs.opengroup.org/onlinepubs/000095399/functions/exit.html
8411
exit(status);
8412
}
8413
8414
function _fd_close(fd) {try {
8415
8416
var stream = SYSCALLS.getStreamFromFD(fd);
8417
FS.close(stream);
8418
return 0;
8419
} catch (e) {
8420
if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
8421
return e.errno;
8422
}
8423
}
8424
8425
function _fd_read(fd, iov, iovcnt, pnum) {try {
8426
8427
var stream = SYSCALLS.getStreamFromFD(fd);
8428
var num = SYSCALLS.doReadv(stream, iov, iovcnt);
8429
HEAP32[((pnum)>>2)]=num
8430
return 0;
8431
} catch (e) {
8432
if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
8433
return e.errno;
8434
}
8435
}
8436
8437
function _fd_seek(fd, offset_low, offset_high, whence, newOffset) {try {
8438
8439
var stream = SYSCALLS.getStreamFromFD(fd);
8440
var HIGH_OFFSET = 0x100000000; // 2^32
8441
// use an unsigned operator on low and shift high by 32-bits
8442
var offset = offset_high * HIGH_OFFSET + (offset_low >>> 0);
8443
8444
var DOUBLE_LIMIT = 0x20000000000000; // 2^53
8445
// we also check for equality since DOUBLE_LIMIT + 1 == DOUBLE_LIMIT
8446
if (offset <= -DOUBLE_LIMIT || offset >= DOUBLE_LIMIT) {
8447
return -61;
8448
}
8449
8450
FS.llseek(stream, offset, whence);
8451
(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]);
8452
if (stream.getdents && offset === 0 && whence === 0) stream.getdents = null; // reset readdir state
8453
return 0;
8454
} catch (e) {
8455
if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
8456
return e.errno;
8457
}
8458
}
8459
8460
function _fd_write(fd, iov, iovcnt, pnum) {try {
8461
8462
var stream = SYSCALLS.getStreamFromFD(fd);
8463
var num = SYSCALLS.doWritev(stream, iov, iovcnt);
8464
HEAP32[((pnum)>>2)]=num
8465
return 0;
8466
} catch (e) {
8467
if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
8468
return e.errno;
8469
}
8470
}
8471
8472
function _gettimeofday(ptr) {
8473
var now = Date.now();
8474
HEAP32[((ptr)>>2)]=(now/1000)|0; // seconds
8475
HEAP32[(((ptr)+(4))>>2)]=((now % 1000)*1000)|0; // microseconds
8476
return 0;
8477
}
8478
8479
function _glActiveTexture(x0) { GLctx['activeTexture'](x0) }
8480
8481
function _glAttachShader(program, shader) {
8482
GLctx.attachShader(GL.programs[program],
8483
GL.shaders[shader]);
8484
}
8485
8486
function _glBindBuffer(target, buffer) {
8487
8488
GLctx.bindBuffer(target, GL.buffers[buffer]);
8489
}
8490
8491
function _glBindTexture(target, texture) {
8492
GLctx.bindTexture(target, GL.textures[texture]);
8493
}
8494
8495
function _glBlendFunc(x0, x1) { GLctx['blendFunc'](x0, x1) }
8496
8497
function _glBufferData(target, size, data, usage) {
8498
// 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
8499
// randomly mixing both uses in calling code, to avoid any potential JS engine JIT issues.
8500
GLctx.bufferData(target, data ? HEAPU8.subarray(data, data+size) : size, usage);
8501
}
8502
8503
function _glClear(x0) { GLctx['clear'](x0) }
8504
8505
function _glClearColor(x0, x1, x2, x3) { GLctx['clearColor'](x0, x1, x2, x3) }
8506
8507
function _glCompileShader(shader) {
8508
GLctx.compileShader(GL.shaders[shader]);
8509
}
8510
8511
function _glCreateProgram() {
8512
var id = GL.getNewId(GL.programs);
8513
var program = GLctx.createProgram();
8514
program.name = id;
8515
GL.programs[id] = program;
8516
return id;
8517
}
8518
8519
function _glCreateShader(shaderType) {
8520
var id = GL.getNewId(GL.shaders);
8521
GL.shaders[id] = GLctx.createShader(shaderType);
8522
return id;
8523
}
8524
8525
function _glDepthFunc(x0) { GLctx['depthFunc'](x0) }
8526
8527
function _glDepthMask(flag) {
8528
GLctx.depthMask(!!flag);
8529
}
8530
8531
function _glDisable(x0) { GLctx['disable'](x0) }
8532
8533
function _glDisableVertexAttribArray(index) {
8534
GLctx.disableVertexAttribArray(index);
8535
}
8536
8537
function _glDrawArrays(mode, first, count) {
8538
8539
GLctx.drawArrays(mode, first, count);
8540
8541
}
8542
8543
function _glEnable(x0) { GLctx['enable'](x0) }
8544
8545
function _glEnableVertexAttribArray(index) {
8546
GLctx.enableVertexAttribArray(index);
8547
}
8548
8549
function _glGenBuffers(n, buffers) {
8550
__glGenObject(n, buffers, 'createBuffer', GL.buffers
8551
);
8552
}
8553
8554
function _glGenTextures(n, textures) {
8555
__glGenObject(n, textures, 'createTexture', GL.textures
8556
);
8557
}
8558
8559
function _glGetAttribLocation(program, name) {
8560
return GLctx.getAttribLocation(GL.programs[program], UTF8ToString(name));
8561
}
8562
8563
function _glGetShaderInfoLog(shader, maxLength, length, infoLog) {
8564
var log = GLctx.getShaderInfoLog(GL.shaders[shader]);
8565
if (log === null) log = '(unknown error)';
8566
var numBytesWrittenExclNull = (maxLength > 0 && infoLog) ? stringToUTF8(log, infoLog, maxLength) : 0;
8567
if (length) HEAP32[((length)>>2)]=numBytesWrittenExclNull;
8568
}
8569
8570
function _glGetShaderiv(shader, pname, p) {
8571
if (!p) {
8572
// GLES2 specification does not specify how to behave if p is a null pointer. Since calling this function does not make sense
8573
// if p == null, issue a GL error to notify user about it.
8574
GL.recordError(0x501 /* GL_INVALID_VALUE */);
8575
return;
8576
}
8577
if (pname == 0x8B84) { // GL_INFO_LOG_LENGTH
8578
var log = GLctx.getShaderInfoLog(GL.shaders[shader]);
8579
if (log === null) log = '(unknown error)';
8580
HEAP32[((p)>>2)]=log.length + 1;
8581
} else if (pname == 0x8B88) { // GL_SHADER_SOURCE_LENGTH
8582
var source = GLctx.getShaderSource(GL.shaders[shader]);
8583
var sourceLength = (source === null || source.length == 0) ? 0 : source.length + 1;
8584
HEAP32[((p)>>2)]=sourceLength;
8585
} else {
8586
HEAP32[((p)>>2)]=GLctx.getShaderParameter(GL.shaders[shader], pname);
8587
}
8588
}
8589
8590
function _glGetUniformLocation(program, name) {
8591
name = UTF8ToString(name);
8592
8593
var arrayIndex = 0;
8594
// If user passed an array accessor "[index]", parse the array index off the accessor.
8595
if (name[name.length - 1] == ']') {
8596
var leftBrace = name.lastIndexOf('[');
8597
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]"
8598
name = name.slice(0, leftBrace);
8599
}
8600
8601
var uniformInfo = GL.programInfos[program] && GL.programInfos[program].uniforms[name]; // returns pair [ dimension_of_uniform_array, uniform_location ]
8602
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.
8603
return uniformInfo[1] + arrayIndex;
8604
} else {
8605
return -1;
8606
}
8607
}
8608
8609
function _glLinkProgram(program) {
8610
GLctx.linkProgram(GL.programs[program]);
8611
GL.populateUniformTable(program);
8612
}
8613
8614
function _glPolygonOffset(x0, x1) { GLctx['polygonOffset'](x0, x1) }
8615
8616
function _glScissor(x0, x1, x2, x3) { GLctx['scissor'](x0, x1, x2, x3) }
8617
8618
function _glShaderSource(shader, count, string, length) {
8619
var source = GL.getSource(shader, count, string, length);
8620
8621
8622
GLctx.shaderSource(GL.shaders[shader], source);
8623
}
8624
8625
function _glTexImage2D(target, level, internalFormat, width, height, border, format, type, pixels) {
8626
GLctx.texImage2D(target, level, internalFormat, width, height, border, format, type, pixels ? emscriptenWebGLGetTexPixelData(type, format, width, height, pixels, internalFormat) : null);
8627
}
8628
8629
function _glTexParameteri(x0, x1, x2) { GLctx['texParameteri'](x0, x1, x2) }
8630
8631
function _glUniform1i(location, v0) {
8632
GLctx.uniform1i(GL.uniforms[location], v0);
8633
}
8634
8635
function _glUseProgram(program) {
8636
GLctx.useProgram(GL.programs[program]);
8637
}
8638
8639
function _glVertexAttribPointer(index, size, type, normalized, stride, ptr) {
8640
GLctx.vertexAttribPointer(index, size, type, !!normalized, stride, ptr);
8641
}
8642
8643
function _glViewport(x0, x1, x2, x3) { GLctx['viewport'](x0, x1, x2, x3) }
8644
8645
8646
function _usleep(useconds) {
8647
// int usleep(useconds_t useconds);
8648
// http://pubs.opengroup.org/onlinepubs/000095399/functions/usleep.html
8649
// We're single-threaded, so use a busy loop. Super-ugly.
8650
var start = _emscripten_get_now();
8651
while (_emscripten_get_now() - start < useconds / 1000) {
8652
// Do nothing.
8653
}
8654
}function _nanosleep(rqtp, rmtp) {
8655
// int nanosleep(const struct timespec *rqtp, struct timespec *rmtp);
8656
if (rqtp === 0) {
8657
___setErrNo(28);
8658
return -1;
8659
}
8660
var seconds = HEAP32[((rqtp)>>2)];
8661
var nanoseconds = HEAP32[(((rqtp)+(4))>>2)];
8662
if (nanoseconds < 0 || nanoseconds > 999999999 || seconds < 0) {
8663
___setErrNo(28);
8664
return -1;
8665
}
8666
if (rmtp !== 0) {
8667
HEAP32[((rmtp)>>2)]=0;
8668
HEAP32[(((rmtp)+(4))>>2)]=0;
8669
}
8670
return _usleep((seconds * 1e6) + (nanoseconds / 1000));
8671
}
8672
8673
function _setTempRet0($i) {
8674
setTempRet0(($i) | 0);
8675
}
8676
8677
function _sigaction(signum, act, oldact) {
8678
//int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact);
8679
err('Calling stub instead of sigaction()');
8680
return 0;
8681
}
8682
8683
8684
var __sigalrm_handler=0;function _signal(sig, func) {
8685
if (sig == 14 /*SIGALRM*/) {
8686
__sigalrm_handler = func;
8687
} else {
8688
err('Calling stub instead of signal()');
8689
}
8690
return 0;
8691
}
8692
8693
function readAsmConstArgs(sigPtr, buf) {
8694
if (!readAsmConstArgs.array) {
8695
readAsmConstArgs.array = [];
8696
}
8697
var args = readAsmConstArgs.array;
8698
args.length = 0;
8699
var ch;
8700
while (ch = HEAPU8[sigPtr++]) {
8701
if (ch === 100/*'d'*/ || ch === 102/*'f'*/) {
8702
buf = (buf + 7) & ~7;
8703
args.push(HEAPF64[(buf >> 3)]);
8704
buf += 8;
8705
} else
8706
if (ch === 105 /*'i'*/)
8707
{
8708
buf = (buf + 3) & ~3;
8709
args.push(HEAP32[(buf >> 2)]);
8710
buf += 4;
8711
}
8712
else abort("unexpected char in asm const signature " + ch);
8713
}
8714
return args;
8715
}
8716
var FSNode = /** @constructor */ function(parent, name, mode, rdev) {
8717
if (!parent) {
8718
parent = this; // root node sets parent to itself
8719
}
8720
this.parent = parent;
8721
this.mount = parent.mount;
8722
this.mounted = null;
8723
this.id = FS.nextInode++;
8724
this.name = name;
8725
this.mode = mode;
8726
this.node_ops = {};
8727
this.stream_ops = {};
8728
this.rdev = rdev;
8729
};
8730
var readMode = 292/*292*/ | 73/*73*/;
8731
var writeMode = 146/*146*/;
8732
Object.defineProperties(FSNode.prototype, {
8733
read: {
8734
get: /** @this{FSNode} */function() {
8735
return (this.mode & readMode) === readMode;
8736
},
8737
set: /** @this{FSNode} */function(val) {
8738
val ? this.mode |= readMode : this.mode &= ~readMode;
8739
}
8740
},
8741
write: {
8742
get: /** @this{FSNode} */function() {
8743
return (this.mode & writeMode) === writeMode;
8744
},
8745
set: /** @this{FSNode} */function(val) {
8746
val ? this.mode |= writeMode : this.mode &= ~writeMode;
8747
}
8748
},
8749
isFolder: {
8750
get: /** @this{FSNode} */function() {
8751
return FS.isDir(this.mode);
8752
}
8753
},
8754
isDevice: {
8755
get: /** @this{FSNode} */function() {
8756
return FS.isChrdev(this.mode);
8757
}
8758
}
8759
});
8760
FS.FSNode = FSNode;
8761
FS.staticInit();;
8762
Module["requestFullscreen"] = function Module_requestFullscreen(lockPointer, resizeCanvas) { Browser.requestFullscreen(lockPointer, resizeCanvas) };
8763
Module["requestFullScreen"] = function Module_requestFullScreen() { Browser.requestFullScreen() };
8764
Module["requestAnimationFrame"] = function Module_requestAnimationFrame(func) { Browser.requestAnimationFrame(func) };
8765
Module["setCanvasSize"] = function Module_setCanvasSize(width, height, noUpdates) { Browser.setCanvasSize(width, height, noUpdates) };
8766
Module["pauseMainLoop"] = function Module_pauseMainLoop() { Browser.mainLoop.pause() };
8767
Module["resumeMainLoop"] = function Module_resumeMainLoop() { Browser.mainLoop.resume() };
8768
Module["getUserMedia"] = function Module_getUserMedia() { Browser.getUserMedia() }
8769
Module["createContext"] = function Module_createContext(canvas, useWebGL, setInModule, webGLContextAttributes) { return Browser.createContext(canvas, useWebGL, setInModule, webGLContextAttributes) };
8770
var GLctx; GL.init();
8771
for (var i = 0; i < 32; i++) __tempFixedLengthArray.push(new Array(i));;
8772
var ASSERTIONS = true;
8773
8774
// Copyright 2017 The Emscripten Authors. All rights reserved.
8775
// Emscripten is available under two separate licenses, the MIT license and the
8776
// University of Illinois/NCSA Open Source License. Both these licenses can be
8777
// found in the LICENSE file.
8778
8779
/** @type {function(string, boolean=, number=)} */
8780
function intArrayFromString(stringy, dontAddNull, length) {
8781
var len = length > 0 ? length : lengthBytesUTF8(stringy)+1;
8782
var u8array = new Array(len);
8783
var numBytesWritten = stringToUTF8Array(stringy, u8array, 0, u8array.length);
8784
if (dontAddNull) u8array.length = numBytesWritten;
8785
return u8array;
8786
}
8787
8788
function intArrayToString(array) {
8789
var ret = [];
8790
for (var i = 0; i < array.length; i++) {
8791
var chr = array[i];
8792
if (chr > 0xFF) {
8793
if (ASSERTIONS) {
8794
assert(false, 'Character code ' + chr + ' (' + String.fromCharCode(chr) + ') at offset ' + i + ' not in 0x00-0xFF.');
8795
}
8796
chr &= 0xFF;
8797
}
8798
ret.push(String.fromCharCode(chr));
8799
}
8800
return ret.join('');
8801
}
8802
8803
8804
var asmGlobalArg = {};
8805
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 };
8806
var asm = createWasm();
8807
Module["asm"] = asm;
8808
/** @type {function(...*):?} */
8809
var ___wasm_call_ctors = Module["___wasm_call_ctors"] = function() {
8810
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8811
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8812
return Module["asm"]["__wasm_call_ctors"].apply(null, arguments)
8813
};
8814
8815
/** @type {function(...*):?} */
8816
var _memcpy = Module["_memcpy"] = function() {
8817
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8818
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8819
return Module["asm"]["memcpy"].apply(null, arguments)
8820
};
8821
8822
/** @type {function(...*):?} */
8823
var _memset = Module["_memset"] = function() {
8824
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8825
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8826
return Module["asm"]["memset"].apply(null, arguments)
8827
};
8828
8829
/** @type {function(...*):?} */
8830
var _malloc = Module["_malloc"] = function() {
8831
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8832
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8833
return Module["asm"]["malloc"].apply(null, arguments)
8834
};
8835
8836
/** @type {function(...*):?} */
8837
var _free = Module["_free"] = function() {
8838
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8839
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8840
return Module["asm"]["free"].apply(null, arguments)
8841
};
8842
8843
/** @type {function(...*):?} */
8844
var _main = Module["_main"] = function() {
8845
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8846
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8847
return Module["asm"]["main"].apply(null, arguments)
8848
};
8849
8850
/** @type {function(...*):?} */
8851
var _strstr = Module["_strstr"] = function() {
8852
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8853
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8854
return Module["asm"]["strstr"].apply(null, arguments)
8855
};
8856
8857
/** @type {function(...*):?} */
8858
var ___errno_location = Module["___errno_location"] = function() {
8859
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8860
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8861
return Module["asm"]["__errno_location"].apply(null, arguments)
8862
};
8863
8864
/** @type {function(...*):?} */
8865
var _fflush = Module["_fflush"] = function() {
8866
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8867
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8868
return Module["asm"]["fflush"].apply(null, arguments)
8869
};
8870
8871
/** @type {function(...*):?} */
8872
var _emscripten_GetProcAddress = Module["_emscripten_GetProcAddress"] = function() {
8873
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8874
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8875
return Module["asm"]["emscripten_GetProcAddress"].apply(null, arguments)
8876
};
8877
8878
/** @type {function(...*):?} */
8879
var ___set_stack_limit = Module["___set_stack_limit"] = function() {
8880
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8881
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8882
return Module["asm"]["__set_stack_limit"].apply(null, arguments)
8883
};
8884
8885
/** @type {function(...*):?} */
8886
var stackSave = Module["stackSave"] = function() {
8887
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8888
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8889
return Module["asm"]["stackSave"].apply(null, arguments)
8890
};
8891
8892
/** @type {function(...*):?} */
8893
var stackAlloc = Module["stackAlloc"] = function() {
8894
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8895
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8896
return Module["asm"]["stackAlloc"].apply(null, arguments)
8897
};
8898
8899
/** @type {function(...*):?} */
8900
var stackRestore = Module["stackRestore"] = function() {
8901
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8902
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8903
return Module["asm"]["stackRestore"].apply(null, arguments)
8904
};
8905
8906
/** @type {function(...*):?} */
8907
var __growWasmMemory = Module["__growWasmMemory"] = function() {
8908
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8909
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8910
return Module["asm"]["__growWasmMemory"].apply(null, arguments)
8911
};
8912
8913
/** @type {function(...*):?} */
8914
var dynCall_i = Module["dynCall_i"] = function() {
8915
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8916
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8917
return Module["asm"]["dynCall_i"].apply(null, arguments)
8918
};
8919
8920
/** @type {function(...*):?} */
8921
var dynCall_v = Module["dynCall_v"] = function() {
8922
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8923
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8924
return Module["asm"]["dynCall_v"].apply(null, arguments)
8925
};
8926
8927
/** @type {function(...*):?} */
8928
var dynCall_iiii = Module["dynCall_iiii"] = function() {
8929
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8930
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8931
return Module["asm"]["dynCall_iiii"].apply(null, arguments)
8932
};
8933
8934
/** @type {function(...*):?} */
8935
var dynCall_vi = Module["dynCall_vi"] = function() {
8936
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8937
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8938
return Module["asm"]["dynCall_vi"].apply(null, arguments)
8939
};
8940
8941
/** @type {function(...*):?} */
8942
var dynCall_iii = Module["dynCall_iii"] = function() {
8943
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8944
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8945
return Module["asm"]["dynCall_iii"].apply(null, arguments)
8946
};
8947
8948
/** @type {function(...*):?} */
8949
var dynCall_vd = Module["dynCall_vd"] = function() {
8950
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8951
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8952
return Module["asm"]["dynCall_vd"].apply(null, arguments)
8953
};
8954
8955
/** @type {function(...*):?} */
8956
var dynCall_ii = Module["dynCall_ii"] = function() {
8957
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8958
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8959
return Module["asm"]["dynCall_ii"].apply(null, arguments)
8960
};
8961
8962
/** @type {function(...*):?} */
8963
var dynCall_viii = Module["dynCall_viii"] = function() {
8964
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8965
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8966
return Module["asm"]["dynCall_viii"].apply(null, arguments)
8967
};
8968
8969
/** @type {function(...*):?} */
8970
var dynCall_vii = Module["dynCall_vii"] = function() {
8971
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8972
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8973
return Module["asm"]["dynCall_vii"].apply(null, arguments)
8974
};
8975
8976
/** @type {function(...*):?} */
8977
var dynCall_viiii = Module["dynCall_viiii"] = function() {
8978
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8979
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8980
return Module["asm"]["dynCall_viiii"].apply(null, arguments)
8981
};
8982
8983
/** @type {function(...*):?} */
8984
var dynCall_d = Module["dynCall_d"] = function() {
8985
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8986
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8987
return Module["asm"]["dynCall_d"].apply(null, arguments)
8988
};
8989
8990
/** @type {function(...*):?} */
8991
var dynCall_iiiii = Module["dynCall_iiiii"] = function() {
8992
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
8993
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
8994
return Module["asm"]["dynCall_iiiii"].apply(null, arguments)
8995
};
8996
8997
/** @type {function(...*):?} */
8998
var dynCall_iiiiii = Module["dynCall_iiiiii"] = function() {
8999
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
9000
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
9001
return Module["asm"]["dynCall_iiiiii"].apply(null, arguments)
9002
};
9003
9004
/** @type {function(...*):?} */
9005
var dynCall_jiji = Module["dynCall_jiji"] = function() {
9006
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
9007
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
9008
return Module["asm"]["dynCall_jiji"].apply(null, arguments)
9009
};
9010
9011
/** @type {function(...*):?} */
9012
var dynCall_ji = Module["dynCall_ji"] = function() {
9013
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
9014
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
9015
return Module["asm"]["dynCall_ji"].apply(null, arguments)
9016
};
9017
9018
/** @type {function(...*):?} */
9019
var dynCall_iiiiidii = Module["dynCall_iiiiidii"] = function() {
9020
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
9021
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
9022
return Module["asm"]["dynCall_iiiiidii"].apply(null, arguments)
9023
};
9024
9025
/** @type {function(...*):?} */
9026
var dynCall_iiiiiiiiii = Module["dynCall_iiiiiiiiii"] = function() {
9027
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
9028
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
9029
return Module["asm"]["dynCall_iiiiiiiiii"].apply(null, arguments)
9030
};
9031
9032
/** @type {function(...*):?} */
9033
var dynCall_iiiiiiiii = Module["dynCall_iiiiiiiii"] = function() {
9034
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
9035
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
9036
return Module["asm"]["dynCall_iiiiiiiii"].apply(null, arguments)
9037
};
9038
9039
/** @type {function(...*):?} */
9040
var dynCall_viiiiiii = Module["dynCall_viiiiiii"] = function() {
9041
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
9042
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
9043
return Module["asm"]["dynCall_viiiiiii"].apply(null, arguments)
9044
};
9045
9046
/** @type {function(...*):?} */
9047
var dynCall_viiiiiiiiiii = Module["dynCall_viiiiiiiiiii"] = function() {
9048
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
9049
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
9050
return Module["asm"]["dynCall_viiiiiiiiiii"].apply(null, arguments)
9051
};
9052
9053
/** @type {function(...*):?} */
9054
var dynCall_iiiiiiii = Module["dynCall_iiiiiiii"] = function() {
9055
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
9056
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
9057
return Module["asm"]["dynCall_iiiiiiii"].apply(null, arguments)
9058
};
9059
9060
/** @type {function(...*):?} */
9061
var dynCall_iidiiii = Module["dynCall_iidiiii"] = function() {
9062
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
9063
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
9064
return Module["asm"]["dynCall_iidiiii"].apply(null, arguments)
9065
};
9066
9067
/** @type {function(...*):?} */
9068
var dynCall_viiiii = Module["dynCall_viiiii"] = function() {
9069
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
9070
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
9071
return Module["asm"]["dynCall_viiiii"].apply(null, arguments)
9072
};
9073
9074
/** @type {function(...*):?} */
9075
var dynCall_vffff = Module["dynCall_vffff"] = function() {
9076
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
9077
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
9078
return Module["asm"]["dynCall_vffff"].apply(null, arguments)
9079
};
9080
9081
/** @type {function(...*):?} */
9082
var dynCall_vf = Module["dynCall_vf"] = function() {
9083
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
9084
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
9085
return Module["asm"]["dynCall_vf"].apply(null, arguments)
9086
};
9087
9088
/** @type {function(...*):?} */
9089
var dynCall_viiiiiiii = Module["dynCall_viiiiiiii"] = function() {
9090
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
9091
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
9092
return Module["asm"]["dynCall_viiiiiiii"].apply(null, arguments)
9093
};
9094
9095
/** @type {function(...*):?} */
9096
var dynCall_viiiiiiiii = Module["dynCall_viiiiiiiii"] = function() {
9097
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
9098
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
9099
return Module["asm"]["dynCall_viiiiiiiii"].apply(null, arguments)
9100
};
9101
9102
/** @type {function(...*):?} */
9103
var dynCall_vff = Module["dynCall_vff"] = function() {
9104
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
9105
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
9106
return Module["asm"]["dynCall_vff"].apply(null, arguments)
9107
};
9108
9109
/** @type {function(...*):?} */
9110
var dynCall_vfi = Module["dynCall_vfi"] = function() {
9111
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
9112
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
9113
return Module["asm"]["dynCall_vfi"].apply(null, arguments)
9114
};
9115
9116
/** @type {function(...*):?} */
9117
var dynCall_viif = Module["dynCall_viif"] = function() {
9118
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
9119
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
9120
return Module["asm"]["dynCall_viif"].apply(null, arguments)
9121
};
9122
9123
/** @type {function(...*):?} */
9124
var dynCall_vif = Module["dynCall_vif"] = function() {
9125
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
9126
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
9127
return Module["asm"]["dynCall_vif"].apply(null, arguments)
9128
};
9129
9130
/** @type {function(...*):?} */
9131
var dynCall_viff = Module["dynCall_viff"] = function() {
9132
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
9133
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
9134
return Module["asm"]["dynCall_viff"].apply(null, arguments)
9135
};
9136
9137
/** @type {function(...*):?} */
9138
var dynCall_vifff = Module["dynCall_vifff"] = function() {
9139
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
9140
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
9141
return Module["asm"]["dynCall_vifff"].apply(null, arguments)
9142
};
9143
9144
/** @type {function(...*):?} */
9145
var dynCall_viffff = Module["dynCall_viffff"] = function() {
9146
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
9147
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
9148
return Module["asm"]["dynCall_viffff"].apply(null, arguments)
9149
};
9150
9151
/** @type {function(...*):?} */
9152
var dynCall_viiiiii = Module["dynCall_viiiiii"] = function() {
9153
assert(runtimeInitialized, 'you need to wait for the runtime to be ready (e.g. wait for main() to be called)');
9154
assert(!runtimeExited, 'the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
9155
return Module["asm"]["dynCall_viiiiii"].apply(null, arguments)
9156
};
9157
9158
9159
9160
9161
// === Auto-generated postamble setup entry stuff ===
9162
9163
Module['asm'] = asm;
9164
9165
if (!Object.getOwnPropertyDescriptor(Module, "intArrayFromString")) Module["intArrayFromString"] = function() { abort("'intArrayFromString' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9166
if (!Object.getOwnPropertyDescriptor(Module, "intArrayToString")) Module["intArrayToString"] = function() { abort("'intArrayToString' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9167
if (!Object.getOwnPropertyDescriptor(Module, "ccall")) Module["ccall"] = function() { abort("'ccall' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9168
if (!Object.getOwnPropertyDescriptor(Module, "cwrap")) Module["cwrap"] = function() { abort("'cwrap' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9169
if (!Object.getOwnPropertyDescriptor(Module, "setValue")) Module["setValue"] = function() { abort("'setValue' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9170
if (!Object.getOwnPropertyDescriptor(Module, "getValue")) Module["getValue"] = function() { abort("'getValue' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9171
if (!Object.getOwnPropertyDescriptor(Module, "allocate")) Module["allocate"] = function() { abort("'allocate' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9172
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") };
9173
if (!Object.getOwnPropertyDescriptor(Module, "UTF8ArrayToString")) Module["UTF8ArrayToString"] = function() { abort("'UTF8ArrayToString' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9174
if (!Object.getOwnPropertyDescriptor(Module, "UTF8ToString")) Module["UTF8ToString"] = function() { abort("'UTF8ToString' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9175
if (!Object.getOwnPropertyDescriptor(Module, "stringToUTF8Array")) Module["stringToUTF8Array"] = function() { abort("'stringToUTF8Array' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9176
if (!Object.getOwnPropertyDescriptor(Module, "stringToUTF8")) Module["stringToUTF8"] = function() { abort("'stringToUTF8' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9177
if (!Object.getOwnPropertyDescriptor(Module, "lengthBytesUTF8")) Module["lengthBytesUTF8"] = function() { abort("'lengthBytesUTF8' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9178
if (!Object.getOwnPropertyDescriptor(Module, "stackTrace")) Module["stackTrace"] = function() { abort("'stackTrace' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9179
if (!Object.getOwnPropertyDescriptor(Module, "addOnPreRun")) Module["addOnPreRun"] = function() { abort("'addOnPreRun' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9180
if (!Object.getOwnPropertyDescriptor(Module, "addOnInit")) Module["addOnInit"] = function() { abort("'addOnInit' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9181
if (!Object.getOwnPropertyDescriptor(Module, "addOnPreMain")) Module["addOnPreMain"] = function() { abort("'addOnPreMain' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9182
if (!Object.getOwnPropertyDescriptor(Module, "addOnExit")) Module["addOnExit"] = function() { abort("'addOnExit' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9183
if (!Object.getOwnPropertyDescriptor(Module, "addOnPostRun")) Module["addOnPostRun"] = function() { abort("'addOnPostRun' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9184
if (!Object.getOwnPropertyDescriptor(Module, "writeStringToMemory")) Module["writeStringToMemory"] = function() { abort("'writeStringToMemory' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9185
if (!Object.getOwnPropertyDescriptor(Module, "writeArrayToMemory")) Module["writeArrayToMemory"] = function() { abort("'writeArrayToMemory' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9186
if (!Object.getOwnPropertyDescriptor(Module, "writeAsciiToMemory")) Module["writeAsciiToMemory"] = function() { abort("'writeAsciiToMemory' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9187
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") };
9188
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") };
9189
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") };
9190
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") };
9191
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") };
9192
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") };
9193
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") };
9194
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") };
9195
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") };
9196
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") };
9197
if (!Object.getOwnPropertyDescriptor(Module, "dynamicAlloc")) Module["dynamicAlloc"] = function() { abort("'dynamicAlloc' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9198
if (!Object.getOwnPropertyDescriptor(Module, "loadDynamicLibrary")) Module["loadDynamicLibrary"] = function() { abort("'loadDynamicLibrary' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9199
if (!Object.getOwnPropertyDescriptor(Module, "loadWebAssemblyModule")) Module["loadWebAssemblyModule"] = function() { abort("'loadWebAssemblyModule' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9200
if (!Object.getOwnPropertyDescriptor(Module, "getLEB")) Module["getLEB"] = function() { abort("'getLEB' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9201
if (!Object.getOwnPropertyDescriptor(Module, "getFunctionTables")) Module["getFunctionTables"] = function() { abort("'getFunctionTables' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9202
if (!Object.getOwnPropertyDescriptor(Module, "alignFunctionTables")) Module["alignFunctionTables"] = function() { abort("'alignFunctionTables' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9203
if (!Object.getOwnPropertyDescriptor(Module, "registerFunctions")) Module["registerFunctions"] = function() { abort("'registerFunctions' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9204
if (!Object.getOwnPropertyDescriptor(Module, "addFunction")) Module["addFunction"] = function() { abort("'addFunction' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9205
if (!Object.getOwnPropertyDescriptor(Module, "removeFunction")) Module["removeFunction"] = function() { abort("'removeFunction' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9206
if (!Object.getOwnPropertyDescriptor(Module, "getFuncWrapper")) Module["getFuncWrapper"] = function() { abort("'getFuncWrapper' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9207
if (!Object.getOwnPropertyDescriptor(Module, "prettyPrint")) Module["prettyPrint"] = function() { abort("'prettyPrint' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9208
if (!Object.getOwnPropertyDescriptor(Module, "makeBigInt")) Module["makeBigInt"] = function() { abort("'makeBigInt' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9209
if (!Object.getOwnPropertyDescriptor(Module, "dynCall")) Module["dynCall"] = function() { abort("'dynCall' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9210
if (!Object.getOwnPropertyDescriptor(Module, "getCompilerSetting")) Module["getCompilerSetting"] = function() { abort("'getCompilerSetting' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9211
if (!Object.getOwnPropertyDescriptor(Module, "print")) Module["print"] = function() { abort("'print' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9212
if (!Object.getOwnPropertyDescriptor(Module, "printErr")) Module["printErr"] = function() { abort("'printErr' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9213
if (!Object.getOwnPropertyDescriptor(Module, "getTempRet0")) Module["getTempRet0"] = function() { abort("'getTempRet0' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9214
if (!Object.getOwnPropertyDescriptor(Module, "setTempRet0")) Module["setTempRet0"] = function() { abort("'setTempRet0' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9215
Module["callMain"] = callMain;
9216
if (!Object.getOwnPropertyDescriptor(Module, "abort")) Module["abort"] = function() { abort("'abort' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9217
if (!Object.getOwnPropertyDescriptor(Module, "stringToNewUTF8")) Module["stringToNewUTF8"] = function() { abort("'stringToNewUTF8' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9218
if (!Object.getOwnPropertyDescriptor(Module, "abortOnCannotGrowMemory")) Module["abortOnCannotGrowMemory"] = function() { abort("'abortOnCannotGrowMemory' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9219
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)") };
9220
if (!Object.getOwnPropertyDescriptor(Module, "ENV")) Module["ENV"] = function() { abort("'ENV' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9221
if (!Object.getOwnPropertyDescriptor(Module, "setjmpId")) Module["setjmpId"] = function() { abort("'setjmpId' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9222
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)") };
9223
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)") };
9224
if (!Object.getOwnPropertyDescriptor(Module, "DNS")) Module["DNS"] = function() { abort("'DNS' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9225
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)") };
9226
if (!Object.getOwnPropertyDescriptor(Module, "Protocols")) Module["Protocols"] = function() { abort("'Protocols' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9227
if (!Object.getOwnPropertyDescriptor(Module, "Sockets")) Module["Sockets"] = function() { abort("'Sockets' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9228
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)") };
9229
if (!Object.getOwnPropertyDescriptor(Module, "readAsmConstArgs")) Module["readAsmConstArgs"] = function() { abort("'readAsmConstArgs' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9230
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)") };
9231
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)") };
9232
if (!Object.getOwnPropertyDescriptor(Module, "PATH")) Module["PATH"] = function() { abort("'PATH' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9233
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)") };
9234
if (!Object.getOwnPropertyDescriptor(Module, "SYSCALLS")) Module["SYSCALLS"] = function() { abort("'SYSCALLS' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9235
if (!Object.getOwnPropertyDescriptor(Module, "syscallMmap2")) Module["syscallMmap2"] = function() { abort("'syscallMmap2' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9236
if (!Object.getOwnPropertyDescriptor(Module, "syscallMunmap")) Module["syscallMunmap"] = function() { abort("'syscallMunmap' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9237
if (!Object.getOwnPropertyDescriptor(Module, "JSEvents")) Module["JSEvents"] = function() { abort("'JSEvents' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9238
if (!Object.getOwnPropertyDescriptor(Module, "demangle")) Module["demangle"] = function() { abort("'demangle' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9239
if (!Object.getOwnPropertyDescriptor(Module, "demangleAll")) Module["demangleAll"] = function() { abort("'demangleAll' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9240
if (!Object.getOwnPropertyDescriptor(Module, "jsStackTrace")) Module["jsStackTrace"] = function() { abort("'jsStackTrace' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9241
if (!Object.getOwnPropertyDescriptor(Module, "stackTrace")) Module["stackTrace"] = function() { abort("'stackTrace' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9242
if (!Object.getOwnPropertyDescriptor(Module, "writeI53ToI64")) Module["writeI53ToI64"] = function() { abort("'writeI53ToI64' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9243
if (!Object.getOwnPropertyDescriptor(Module, "writeI53ToI64Clamped")) Module["writeI53ToI64Clamped"] = function() { abort("'writeI53ToI64Clamped' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9244
if (!Object.getOwnPropertyDescriptor(Module, "writeI53ToI64Signaling")) Module["writeI53ToI64Signaling"] = function() { abort("'writeI53ToI64Signaling' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9245
if (!Object.getOwnPropertyDescriptor(Module, "writeI53ToU64Clamped")) Module["writeI53ToU64Clamped"] = function() { abort("'writeI53ToU64Clamped' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9246
if (!Object.getOwnPropertyDescriptor(Module, "writeI53ToU64Signaling")) Module["writeI53ToU64Signaling"] = function() { abort("'writeI53ToU64Signaling' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9247
if (!Object.getOwnPropertyDescriptor(Module, "readI53FromI64")) Module["readI53FromI64"] = function() { abort("'readI53FromI64' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9248
if (!Object.getOwnPropertyDescriptor(Module, "readI53FromU64")) Module["readI53FromU64"] = function() { abort("'readI53FromU64' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9249
if (!Object.getOwnPropertyDescriptor(Module, "convertI32PairToI53")) Module["convertI32PairToI53"] = function() { abort("'convertI32PairToI53' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9250
if (!Object.getOwnPropertyDescriptor(Module, "convertU32PairToI53")) Module["convertU32PairToI53"] = function() { abort("'convertU32PairToI53' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9251
if (!Object.getOwnPropertyDescriptor(Module, "Browser")) Module["Browser"] = function() { abort("'Browser' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9252
if (!Object.getOwnPropertyDescriptor(Module, "FS")) Module["FS"] = function() { abort("'FS' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9253
if (!Object.getOwnPropertyDescriptor(Module, "MEMFS")) Module["MEMFS"] = function() { abort("'MEMFS' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9254
if (!Object.getOwnPropertyDescriptor(Module, "TTY")) Module["TTY"] = function() { abort("'TTY' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9255
if (!Object.getOwnPropertyDescriptor(Module, "PIPEFS")) Module["PIPEFS"] = function() { abort("'PIPEFS' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9256
if (!Object.getOwnPropertyDescriptor(Module, "SOCKFS")) Module["SOCKFS"] = function() { abort("'SOCKFS' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9257
if (!Object.getOwnPropertyDescriptor(Module, "GL")) Module["GL"] = function() { abort("'GL' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9258
if (!Object.getOwnPropertyDescriptor(Module, "emscriptenWebGLGet")) Module["emscriptenWebGLGet"] = function() { abort("'emscriptenWebGLGet' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9259
if (!Object.getOwnPropertyDescriptor(Module, "emscriptenWebGLGetTexPixelData")) Module["emscriptenWebGLGetTexPixelData"] = function() { abort("'emscriptenWebGLGetTexPixelData' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9260
if (!Object.getOwnPropertyDescriptor(Module, "emscriptenWebGLGetUniform")) Module["emscriptenWebGLGetUniform"] = function() { abort("'emscriptenWebGLGetUniform' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9261
if (!Object.getOwnPropertyDescriptor(Module, "emscriptenWebGLGetVertexAttrib")) Module["emscriptenWebGLGetVertexAttrib"] = function() { abort("'emscriptenWebGLGetVertexAttrib' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9262
if (!Object.getOwnPropertyDescriptor(Module, "AL")) Module["AL"] = function() { abort("'AL' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9263
if (!Object.getOwnPropertyDescriptor(Module, "SDL")) Module["SDL"] = function() { abort("'SDL' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9264
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)") };
9265
if (!Object.getOwnPropertyDescriptor(Module, "GLUT")) Module["GLUT"] = function() { abort("'GLUT' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9266
if (!Object.getOwnPropertyDescriptor(Module, "EGL")) Module["EGL"] = function() { abort("'EGL' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9267
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)") };
9268
if (!Object.getOwnPropertyDescriptor(Module, "GLFW")) Module["GLFW"] = function() { abort("'GLFW' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9269
if (!Object.getOwnPropertyDescriptor(Module, "GLEW")) Module["GLEW"] = function() { abort("'GLEW' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9270
if (!Object.getOwnPropertyDescriptor(Module, "IDBStore")) Module["IDBStore"] = function() { abort("'IDBStore' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9271
if (!Object.getOwnPropertyDescriptor(Module, "runAndAbortIfError")) Module["runAndAbortIfError"] = function() { abort("'runAndAbortIfError' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9272
if (!Object.getOwnPropertyDescriptor(Module, "warnOnce")) Module["warnOnce"] = function() { abort("'warnOnce' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9273
if (!Object.getOwnPropertyDescriptor(Module, "stackSave")) Module["stackSave"] = function() { abort("'stackSave' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9274
if (!Object.getOwnPropertyDescriptor(Module, "stackRestore")) Module["stackRestore"] = function() { abort("'stackRestore' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9275
if (!Object.getOwnPropertyDescriptor(Module, "stackAlloc")) Module["stackAlloc"] = function() { abort("'stackAlloc' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9276
if (!Object.getOwnPropertyDescriptor(Module, "AsciiToString")) Module["AsciiToString"] = function() { abort("'AsciiToString' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9277
if (!Object.getOwnPropertyDescriptor(Module, "stringToAscii")) Module["stringToAscii"] = function() { abort("'stringToAscii' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9278
if (!Object.getOwnPropertyDescriptor(Module, "UTF16ToString")) Module["UTF16ToString"] = function() { abort("'UTF16ToString' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9279
if (!Object.getOwnPropertyDescriptor(Module, "stringToUTF16")) Module["stringToUTF16"] = function() { abort("'stringToUTF16' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9280
if (!Object.getOwnPropertyDescriptor(Module, "lengthBytesUTF16")) Module["lengthBytesUTF16"] = function() { abort("'lengthBytesUTF16' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9281
if (!Object.getOwnPropertyDescriptor(Module, "UTF32ToString")) Module["UTF32ToString"] = function() { abort("'UTF32ToString' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9282
if (!Object.getOwnPropertyDescriptor(Module, "stringToUTF32")) Module["stringToUTF32"] = function() { abort("'stringToUTF32' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9283
if (!Object.getOwnPropertyDescriptor(Module, "lengthBytesUTF32")) Module["lengthBytesUTF32"] = function() { abort("'lengthBytesUTF32' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9284
if (!Object.getOwnPropertyDescriptor(Module, "allocateUTF8")) Module["allocateUTF8"] = function() { abort("'allocateUTF8' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9285
if (!Object.getOwnPropertyDescriptor(Module, "allocateUTF8OnStack")) Module["allocateUTF8OnStack"] = function() { abort("'allocateUTF8OnStack' was not exported. add it to EXTRA_EXPORTED_RUNTIME_METHODS (see the FAQ)") };
9286
Module["writeStackCookie"] = writeStackCookie;
9287
Module["checkStackCookie"] = checkStackCookie;
9288
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)") } });
9289
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)") } });
9290
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)") } });
9291
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)") } });
9292
9293
9294
9295
var calledRun;
9296
9297
9298
/**
9299
* @constructor
9300
* @this {ExitStatus}
9301
*/
9302
function ExitStatus(status) {
9303
this.name = "ExitStatus";
9304
this.message = "Program terminated with exit(" + status + ")";
9305
this.status = status;
9306
}
9307
9308
var calledMain = false;
9309
9310
9311
dependenciesFulfilled = function runCaller() {
9312
// If run has never been called, and we should call run (INVOKE_RUN is true, and Module.noInitialRun is not false)
9313
if (!calledRun) run();
9314
if (!calledRun) dependenciesFulfilled = runCaller; // try this again later, after new deps are fulfilled
9315
};
9316
9317
function callMain(args) {
9318
assert(runDependencies == 0, 'cannot call main when async dependencies remain! (listen on Module["onRuntimeInitialized"])');
9319
assert(__ATPRERUN__.length == 0, 'cannot call main when preRun functions remain to be called');
9320
9321
var entryFunction = Module['_main'];
9322
9323
9324
args = args || [];
9325
9326
var argc = args.length+1;
9327
var argv = stackAlloc((argc + 1) * 4);
9328
HEAP32[argv >> 2] = allocateUTF8OnStack(thisProgram);
9329
for (var i = 1; i < argc; i++) {
9330
HEAP32[(argv >> 2) + i] = allocateUTF8OnStack(args[i - 1]);
9331
}
9332
HEAP32[(argv >> 2) + argc] = 0;
9333
9334
9335
try {
9336
9337
Module['___set_stack_limit'](STACK_MAX);
9338
9339
var ret = entryFunction(argc, argv);
9340
9341
9342
// In PROXY_TO_PTHREAD builds, we should never exit the runtime below, as execution is asynchronously handed
9343
// off to a pthread.
9344
// if we're not running an evented main loop, it's time to exit
9345
exit(ret, /* implicit = */ true);
9346
}
9347
catch(e) {
9348
if (e instanceof ExitStatus) {
9349
// exit() throws this once it's done to make sure execution
9350
// has been stopped completely
9351
return;
9352
} else if (e == 'unwind') {
9353
// running an evented main loop, don't immediately exit
9354
noExitRuntime = true;
9355
return;
9356
} else {
9357
var toLog = e;
9358
if (e && typeof e === 'object' && e.stack) {
9359
toLog = [e, e.stack];
9360
}
9361
err('exception thrown: ' + toLog);
9362
quit_(1, e);
9363
}
9364
} finally {
9365
calledMain = true;
9366
}
9367
}
9368
9369
9370
9371
9372
/** @type {function(Array=)} */
9373
function run(args) {
9374
args = args || arguments_;
9375
9376
if (runDependencies > 0) {
9377
return;
9378
}
9379
9380
writeStackCookie();
9381
9382
preRun();
9383
9384
if (runDependencies > 0) return; // a preRun added a dependency, run will be called later
9385
9386
function doRun() {
9387
// run may have just been called through dependencies being fulfilled just in this very frame,
9388
// or while the async setStatus time below was happening
9389
if (calledRun) return;
9390
calledRun = true;
9391
Module['calledRun'] = true;
9392
9393
if (ABORT) return;
9394
9395
initRuntime();
9396
9397
preMain();
9398
9399
if (Module['onRuntimeInitialized']) Module['onRuntimeInitialized']();
9400
9401
if (shouldRunNow) callMain(args);
9402
9403
postRun();
9404
}
9405
9406
if (Module['setStatus']) {
9407
Module['setStatus']('Running...');
9408
setTimeout(function() {
9409
setTimeout(function() {
9410
Module['setStatus']('');
9411
}, 1);
9412
doRun();
9413
}, 1);
9414
} else
9415
{
9416
doRun();
9417
}
9418
checkStackCookie();
9419
}
9420
Module['run'] = run;
9421
9422
function checkUnflushedContent() {
9423
// Compiler settings do not allow exiting the runtime, so flushing
9424
// the streams is not possible. but in ASSERTIONS mode we check
9425
// if there was something to flush, and if so tell the user they
9426
// should request that the runtime be exitable.
9427
// Normally we would not even include flush() at all, but in ASSERTIONS
9428
// builds we do so just for this check, and here we see if there is any
9429
// content to flush, that is, we check if there would have been
9430
// something a non-ASSERTIONS build would have not seen.
9431
// How we flush the streams depends on whether we are in SYSCALLS_REQUIRE_FILESYSTEM=0
9432
// mode (which has its own special function for this; otherwise, all
9433
// the code is inside libc)
9434
var print = out;
9435
var printErr = err;
9436
var has = false;
9437
out = err = function(x) {
9438
has = true;
9439
}
9440
try { // it doesn't matter if it fails
9441
var flush = Module['_fflush'];
9442
if (flush) flush(0);
9443
// also flush in the JS FS layer
9444
['stdout', 'stderr'].forEach(function(name) {
9445
var info = FS.analyzePath('/dev/' + name);
9446
if (!info) return;
9447
var stream = info.object;
9448
var rdev = stream.rdev;
9449
var tty = TTY.ttys[rdev];
9450
if (tty && tty.output && tty.output.length) {
9451
has = true;
9452
}
9453
});
9454
} catch(e) {}
9455
out = print;
9456
err = printErr;
9457
if (has) {
9458
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.');
9459
}
9460
}
9461
9462
/** @param {boolean|number=} implicit */
9463
function exit(status, implicit) {
9464
checkUnflushedContent();
9465
9466
// if this is just main exit-ing implicitly, and the status is 0, then we
9467
// don't need to do anything here and can just leave. if the status is
9468
// non-zero, though, then we need to report it.
9469
// (we may have warned about this earlier, if a situation justifies doing so)
9470
if (implicit && noExitRuntime && status === 0) {
9471
return;
9472
}
9473
9474
if (noExitRuntime) {
9475
// if exit() was called, we may warn the user if the runtime isn't actually being shut down
9476
if (!implicit) {
9477
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)');
9478
}
9479
} else {
9480
9481
ABORT = true;
9482
EXITSTATUS = status;
9483
9484
exitRuntime();
9485
9486
if (Module['onExit']) Module['onExit'](status);
9487
}
9488
9489
quit_(status, new ExitStatus(status));
9490
}
9491
9492
if (Module['preInit']) {
9493
if (typeof Module['preInit'] == 'function') Module['preInit'] = [Module['preInit']];
9494
while (Module['preInit'].length > 0) {
9495
Module['preInit'].pop()();
9496
}
9497
}
9498
9499
// shouldRunNow refers to calling main(), not run().
9500
var shouldRunNow = true;
9501
9502
if (Module['noInitialRun']) shouldRunNow = false;
9503
9504
9505
noExitRuntime = true;
9506
9507
run();
9508
9509
9510
9511
9512
9513
// {{MODULE_ADDITIONS}}
9514
9515
9516
9517
9518