Guest User

InfoMedia.js

a guest
Feb 24th, 2013
338
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Note: Some Emscripten settings will significantly limit the speed of the generated code.
  2. // Note: Some Emscripten settings may limit the speed of the generated code.
  3. try {
  4.   this['Module'] = Module;
  5. } catch(e) {
  6.   this['Module'] = Module = {};
  7. }
  8.  
  9. // The environment setup code below is customized to use Module.
  10. // *** Environment setup code ***
  11. var ENVIRONMENT_IS_NODE = typeof process === 'object' && typeof require === 'function';
  12. var ENVIRONMENT_IS_WEB = typeof window === 'object';
  13. var ENVIRONMENT_IS_WORKER = typeof importScripts === 'function';
  14. var ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER;
  15.  
  16. if (ENVIRONMENT_IS_NODE) {
  17.   // Expose functionality in the same simple way that the shells work
  18.   // Note that we pollute the global namespace here, otherwise we break in node
  19.   Module['print'] = function(x) {
  20.     process['stdout'].write(x + '\n');
  21.   };
  22.   Module['printErr'] = function(x) {
  23.     process['stderr'].write(x + '\n');
  24.   };
  25.  
  26.   var nodeFS = require('fs');
  27.   var nodePath = require('path');
  28.  
  29.   Module['read'] = function(filename) {
  30.     filename = nodePath['normalize'](filename);
  31.     var ret = nodeFS['readFileSync'](filename).toString();
  32.     // The path is absolute if the normalized version is the same as the resolved.
  33.     if (!ret && filename != nodePath['resolve'](filename)) {
  34.       filename = path.join(__dirname, '..', 'src', filename);
  35.       ret = nodeFS['readFileSync'](filename).toString();
  36.     }
  37.     return ret;
  38.   };
  39.  
  40.   Module['load'] = function(f) {
  41.     globalEval(read(f));
  42.   };
  43.  
  44.   if (!Module['arguments']) {
  45.     Module['arguments'] = process['argv'].slice(2);
  46.   }
  47. }
  48.  
  49. if (ENVIRONMENT_IS_SHELL) {
  50.   Module['print'] = print;
  51.   if (typeof printErr != 'undefined') Module['printErr'] = printErr; // not present in v8 or older sm
  52.  
  53.   // Polyfill over SpiderMonkey/V8 differences
  54.   if (typeof read != 'undefined') {
  55.     Module['read'] = read;
  56.   } else {
  57.     Module['read'] = function(f) { snarf(f) };
  58.   }
  59.  
  60.   if (!Module['arguments']) {
  61.     if (typeof scriptArgs != 'undefined') {
  62.       Module['arguments'] = scriptArgs;
  63.     } else if (typeof arguments != 'undefined') {
  64.       Module['arguments'] = arguments;
  65.     }
  66.   }
  67. }
  68.  
  69. if (ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_WORKER) {
  70.   if (!Module['print']) {
  71.     Module['print'] = function(x) {
  72.       console.log(x);
  73.     };
  74.   }
  75.  
  76.   if (!Module['printErr']) {
  77.     Module['printErr'] = function(x) {
  78.       console.log(x);
  79.     };
  80.   }
  81. }
  82.  
  83. if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) {
  84.   Module['read'] = function(url) {
  85.     var xhr = new XMLHttpRequest();
  86.     xhr.open('GET', url, false);
  87.     xhr.send(null);
  88.     return xhr.responseText;
  89.   };
  90.  
  91.   if (!Module['arguments']) {
  92.     if (typeof arguments != 'undefined') {
  93.       Module['arguments'] = arguments;
  94.     }
  95.   }
  96. }
  97.  
  98. if (ENVIRONMENT_IS_WORKER) {
  99.   // We can do very little here...
  100.   var TRY_USE_DUMP = false;
  101.   if (!Module['print']) {
  102.     Module['print'] = (TRY_USE_DUMP && (typeof(dump) !== "undefined") ? (function(x) {
  103.       dump(x);
  104.     }) : (function(x) {
  105.       // self.postMessage(x); // enable this if you want stdout to be sent as messages
  106.     }));
  107.   }
  108.  
  109.   Module['load'] = importScripts;
  110. }
  111.  
  112. if (!ENVIRONMENT_IS_WORKER && !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_SHELL) {
  113.   // Unreachable because SHELL is dependant on the others
  114.   throw 'Unknown runtime environment. Where are we?';
  115. }
  116.  
  117. function globalEval(x) {
  118.   eval.call(null, x);
  119. }
  120. if (!Module['load'] == 'undefined' && Module['read']) {
  121.   Module['load'] = function(f) {
  122.     globalEval(Module['read'](f));
  123.   };
  124. }
  125. if (!Module['print']) {
  126.   Module['print'] = function(){};
  127. }
  128. if (!Module['printErr']) {
  129.   Module['printErr'] = Module['print'];
  130. }
  131. if (!Module['arguments']) {
  132.   Module['arguments'] = [];
  133. }
  134. // *** Environment setup code ***
  135.  
  136. // Closure helpers
  137. Module.print = Module['print'];
  138. Module.printErr = Module['printErr'];
  139.  
  140. // Callbacks
  141. if (!Module['preRun']) Module['preRun'] = [];
  142. if (!Module['postRun']) Module['postRun'] = [];
  143.  
  144.  
  145. // === Auto-generated preamble library stuff ===
  146.  
  147. //========================================
  148. // Runtime code shared with compiler
  149. //========================================
  150.  
  151. var Runtime = {
  152.   stackSave: function () {
  153.     return STACKTOP;
  154.   },
  155.   stackRestore: function (stackTop) {
  156.     STACKTOP = stackTop;
  157.   },
  158.   forceAlign: function (target, quantum) {
  159.     quantum = quantum || 4;
  160.     if (quantum == 1) return target;
  161.     if (isNumber(target) && isNumber(quantum)) {
  162.       return Math.ceil(target/quantum)*quantum;
  163.     } else if (isNumber(quantum) && isPowerOfTwo(quantum)) {
  164.       var logg = log2(quantum);
  165.       return '((((' +target + ')+' + (quantum-1) + ')>>' + logg + ')<<' + logg + ')';
  166.     }
  167.     return 'Math.ceil((' + target + ')/' + quantum + ')*' + quantum;
  168.   },
  169.   isNumberType: function (type) {
  170.     return type in Runtime.INT_TYPES || type in Runtime.FLOAT_TYPES;
  171.   },
  172.   isPointerType: function isPointerType(type) {
  173.   return type[type.length-1] == '*';
  174. },
  175.   isStructType: function isStructType(type) {
  176.   if (isPointerType(type)) return false;
  177.   if (/^\[\d+\ x\ (.*)\]/.test(type)) return true; // [15 x ?] blocks. Like structs
  178.   if (/<?{ ?[^}]* ?}>?/.test(type)) return true; // { i32, i8 } etc. - anonymous struct types
  179.   // See comment in isStructPointerType()
  180.   return type[0] == '%';
  181. },
  182.   INT_TYPES: {"i1":0,"i8":0,"i16":0,"i32":0,"i64":0},
  183.   FLOAT_TYPES: {"float":0,"double":0},
  184.   BITSHIFT64_SHL: 0,
  185.   BITSHIFT64_ASHR: 1,
  186.   BITSHIFT64_LSHR: 2,
  187.   bitshift64: function (low, high, op, bits) {
  188.     var ret;
  189.     var ander = Math.pow(2, bits)-1;
  190.     if (bits < 32) {
  191.       switch (op) {
  192.         case Runtime.BITSHIFT64_SHL:
  193.           ret = [low << bits, (high << bits) | ((low&(ander << (32 - bits))) >>> (32 - bits))];
  194.           break;
  195.         case Runtime.BITSHIFT64_ASHR:
  196.           ret = [(((low >>> bits ) | ((high&ander) << (32 - bits))) >> 0) >>> 0, (high >> bits) >>> 0];
  197.           break;
  198.         case Runtime.BITSHIFT64_LSHR:
  199.           ret = [((low >>> bits) | ((high&ander) << (32 - bits))) >>> 0, high >>> bits];
  200.           break;
  201.       }
  202.     } else if (bits == 32) {
  203.       switch (op) {
  204.         case Runtime.BITSHIFT64_SHL:
  205.           ret = [0, low];
  206.           break;
  207.         case Runtime.BITSHIFT64_ASHR:
  208.           ret = [high, (high|0) < 0 ? ander : 0];
  209.           break;
  210.         case Runtime.BITSHIFT64_LSHR:
  211.           ret = [high, 0];
  212.           break;
  213.       }
  214.     } else { // bits > 32
  215.       switch (op) {
  216.         case Runtime.BITSHIFT64_SHL:
  217.           ret = [0, low << (bits - 32)];
  218.           break;
  219.         case Runtime.BITSHIFT64_ASHR:
  220.           ret = [(high >> (bits - 32)) >>> 0, (high|0) < 0 ? ander : 0];
  221.           break;
  222.         case Runtime.BITSHIFT64_LSHR:
  223.           ret = [high >>>  (bits - 32) , 0];
  224.           break;
  225.       }
  226.     }
  227.     assert(ret);
  228.     HEAP32[tempDoublePtr>>2] = ret[0]; // cannot use utility functions since we are in runtime itself
  229.     HEAP32[tempDoublePtr+4>>2] = ret[1];
  230.   },
  231.   or64: function (x, y) {
  232.     var l = (x | 0) | (y | 0);
  233.     var h = (Math.round(x / 4294967296) | Math.round(y / 4294967296)) * 4294967296;
  234.     return l + h;
  235.   },
  236.   and64: function (x, y) {
  237.     var l = (x | 0) & (y | 0);
  238.     var h = (Math.round(x / 4294967296) & Math.round(y / 4294967296)) * 4294967296;
  239.     return l + h;
  240.   },
  241.   xor64: function (x, y) {
  242.     var l = (x | 0) ^ (y | 0);
  243.     var h = (Math.round(x / 4294967296) ^ Math.round(y / 4294967296)) * 4294967296;
  244.     return l + h;
  245.   },
  246.   getNativeTypeSize: function (type, quantumSize) {
  247.     if (Runtime.QUANTUM_SIZE == 1) return 1;
  248.     var size = {
  249.       '%i1': 1,
  250.       '%i8': 1,
  251.       '%i16': 2,
  252.       '%i32': 4,
  253.       '%i64': 8,
  254.       "%float": 4,
  255.       "%double": 8
  256.     }['%'+type]; // add '%' since float and double confuse Closure compiler as keys, and also spidermonkey as a compiler will remove 's from '_i8' etc
  257.     if (!size) {
  258.       if (type.charAt(type.length-1) == '*') {
  259.         size = Runtime.QUANTUM_SIZE; // A pointer
  260.       } else if (type[0] == 'i') {
  261.         var bits = parseInt(type.substr(1));
  262.         assert(bits % 8 == 0);
  263.         size = bits/8;
  264.       }
  265.     }
  266.     return size;
  267.   },
  268.   getNativeFieldSize: function (type) {
  269.     return Math.max(Runtime.getNativeTypeSize(type), Runtime.QUANTUM_SIZE);
  270.   },
  271.   dedup: function dedup(items, ident) {
  272.   var seen = {};
  273.   if (ident) {
  274.     return items.filter(function(item) {
  275.       if (seen[item[ident]]) return false;
  276.       seen[item[ident]] = true;
  277.       return true;
  278.     });
  279.   } else {
  280.     return items.filter(function(item) {
  281.       if (seen[item]) return false;
  282.       seen[item] = true;
  283.       return true;
  284.     });
  285.   }
  286. },
  287.   set: function set() {
  288.   var args = typeof arguments[0] === 'object' ? arguments[0] : arguments;
  289.   var ret = {};
  290.   for (var i = 0; i < args.length; i++) {
  291.     ret[args[i]] = 0;
  292.   }
  293.   return ret;
  294. },
  295.   calculateStructAlignment: function calculateStructAlignment(type) {
  296.     type.flatSize = 0;
  297.     type.alignSize = 0;
  298.     var diffs = [];
  299.     var prev = -1;
  300.     type.flatIndexes = type.fields.map(function(field) {
  301.       var size, alignSize;
  302.       if (Runtime.isNumberType(field) || Runtime.isPointerType(field)) {
  303.         size = Runtime.getNativeTypeSize(field); // pack char; char; in structs, also char[X]s.
  304.         alignSize = size;
  305.       } else if (Runtime.isStructType(field)) {
  306.         size = Types.types[field].flatSize;
  307.         alignSize = Types.types[field].alignSize;
  308.       } else {
  309.         throw 'Unclear type in struct: ' + field + ', in ' + type.name_ + ' :: ' + dump(Types.types[type.name_]);
  310.       }
  311.       alignSize = type.packed ? 1 : Math.min(alignSize, Runtime.QUANTUM_SIZE);
  312.       type.alignSize = Math.max(type.alignSize, alignSize);
  313.       var curr = Runtime.alignMemory(type.flatSize, alignSize); // if necessary, place this on aligned memory
  314.       type.flatSize = curr + size;
  315.       if (prev >= 0) {
  316.         diffs.push(curr-prev);
  317.       }
  318.       prev = curr;
  319.       return curr;
  320.     });
  321.     type.flatSize = Runtime.alignMemory(type.flatSize, type.alignSize);
  322.     if (diffs.length == 0) {
  323.       type.flatFactor = type.flatSize;
  324.     } else if (Runtime.dedup(diffs).length == 1) {
  325.       type.flatFactor = diffs[0];
  326.     }
  327.     type.needsFlattening = (type.flatFactor != 1);
  328.     return type.flatIndexes;
  329.   },
  330.   generateStructInfo: function (struct, typeName, offset) {
  331.     var type, alignment;
  332.     if (typeName) {
  333.       offset = offset || 0;
  334.       type = (typeof Types === 'undefined' ? Runtime.typeInfo : Types.types)[typeName];
  335.       if (!type) return null;
  336.       if (type.fields.length != struct.length) {
  337.         printErr('Number of named fields must match the type for ' + typeName + ': possibly duplicate struct names. Cannot return structInfo');
  338.         return null;
  339.       }
  340.       alignment = type.flatIndexes;
  341.     } else {
  342.       var type = { fields: struct.map(function(item) { return item[0] }) };
  343.       alignment = Runtime.calculateStructAlignment(type);
  344.     }
  345.     var ret = {
  346.       __size__: type.flatSize
  347.     };
  348.     if (typeName) {
  349.       struct.forEach(function(item, i) {
  350.         if (typeof item === 'string') {
  351.           ret[item] = alignment[i] + offset;
  352.         } else {
  353.           // embedded struct
  354.           var key;
  355.           for (var k in item) key = k;
  356.           ret[key] = Runtime.generateStructInfo(item[key], type.fields[i], alignment[i]);
  357.         }
  358.       });
  359.     } else {
  360.       struct.forEach(function(item, i) {
  361.         ret[item[1]] = alignment[i];
  362.       });
  363.     }
  364.     return ret;
  365.   },
  366.   dynCall: function (sig, ptr, args) {
  367.     if (args && args.length) {
  368.       assert(args.length == sig.length-1);
  369.       return FUNCTION_TABLE[ptr].apply(null, args);
  370.     } else {
  371.       assert(sig.length == 1);
  372.       return FUNCTION_TABLE[ptr]();
  373.     }
  374.   },
  375.   addFunction: function (func, sig) {
  376.     assert(sig);
  377.     var table = FUNCTION_TABLE; // TODO: support asm
  378.     var ret = table.length;
  379.     table.push(func);
  380.     table.push(0);
  381.     return ret;
  382.   },
  383.   warnOnce: function (text) {
  384.     if (!Runtime.warnOnce.shown) Runtime.warnOnce.shown = {};
  385.     if (!Runtime.warnOnce.shown[text]) {
  386.       Runtime.warnOnce.shown[text] = 1;
  387.       Module.printErr(text);
  388.     }
  389.   },
  390.   funcWrappers: {},
  391.   getFuncWrapper: function (func, sig) {
  392.     assert(sig);
  393.     if (!Runtime.funcWrappers[func]) {
  394.       Runtime.funcWrappers[func] = function() {
  395.         Runtime.dynCall(sig, func, arguments);
  396.       };
  397.     }
  398.     return Runtime.funcWrappers[func];
  399.   },
  400.   UTF8Processor: function () {
  401.     var buffer = [];
  402.     var needed = 0;
  403.     this.processCChar = function (code) {
  404.       code = code & 0xff;
  405.       if (needed) {
  406.         buffer.push(code);
  407.         needed--;
  408.       }
  409.       if (buffer.length == 0) {
  410.         if (code < 128) return String.fromCharCode(code);
  411.         buffer.push(code);
  412.         if (code > 191 && code < 224) {
  413.           needed = 1;
  414.         } else {
  415.           needed = 2;
  416.         }
  417.         return '';
  418.       }
  419.       if (needed > 0) return '';
  420.       var c1 = buffer[0];
  421.       var c2 = buffer[1];
  422.       var c3 = buffer[2];
  423.       var ret;
  424.       if (c1 > 191 && c1 < 224) {
  425.         ret = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
  426.       } else {
  427.         ret = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
  428.       }
  429.       buffer.length = 0;
  430.       return ret;
  431.     }
  432.     this.processJSString = function(string) {
  433.       string = unescape(encodeURIComponent(string));
  434.       var ret = [];
  435.       for (var i = 0; i < string.length; i++) {
  436.         ret.push(string.charCodeAt(i));
  437.       }
  438.       return ret;
  439.     }
  440.   },
  441.   stackAlloc: function stackAlloc(size) { var ret = STACKTOP;STACKTOP = (STACKTOP + size)|0;STACKTOP = ((((STACKTOP)+3)>>2)<<2);assert(STACKTOP|0 < STACK_MAX|0); return ret; },
  442.   staticAlloc: function staticAlloc(size) { var ret = STATICTOP;STATICTOP = (STATICTOP + size)|0;STATICTOP = ((((STATICTOP)+3)>>2)<<2); if (STATICTOP >= TOTAL_MEMORY) enlargeMemory();; return ret; },
  443.   alignMemory: function alignMemory(size,quantum) { var ret = size = Math.ceil((size)/(quantum ? quantum : 4))*(quantum ? quantum : 4); return ret; },
  444.   makeBigInt: function makeBigInt(low,high,unsigned) { var ret = (unsigned ? (((low)>>>0)+(((high)>>>0)*4294967296)) : (((low)>>>0)+(((high)|0)*4294967296))); return ret; },
  445.   QUANTUM_SIZE: 4,
  446.   __dummy__: 0
  447. }
  448.  
  449.  
  450.  
  451.  
  452. var CorrectionsMonitor = {
  453.   MAX_ALLOWED: 0, // XXX
  454.   corrections: 0,
  455.   sigs: {},
  456.  
  457.   note: function(type, succeed, sig) {
  458.     if (!succeed) {
  459.       this.corrections++;
  460.       if (this.corrections >= this.MAX_ALLOWED) abort('\n\nToo many corrections!');
  461.     }
  462.   },
  463.  
  464.   print: function() {
  465.   }
  466. };
  467.  
  468.  
  469.  
  470.  
  471.  
  472. //========================================
  473. // Runtime essentials
  474. //========================================
  475.  
  476. var __THREW__ = 0; // Used in checking for thrown exceptions.
  477. var setjmpId = 1; // Used in setjmp/longjmp
  478. var setjmpLabels = {};
  479.  
  480. var ABORT = false;
  481.  
  482. var undef = 0;
  483. // tempInt is used for 32-bit signed values or smaller. tempBigInt is used
  484. // for 32-bit unsigned values or more than 32 bits. TODO: audit all uses of tempInt
  485. var tempValue, tempInt, tempBigInt, tempInt2, tempBigInt2, tempPair, tempBigIntI, tempBigIntR, tempBigIntS, tempBigIntP, tempBigIntD;
  486. var tempI64, tempI64b;
  487. var tempRet0, tempRet1, tempRet2, tempRet3, tempRet4, tempRet5, tempRet6, tempRet7, tempRet8, tempRet9;
  488.  
  489. function abort(text) {
  490.   Module.print(text + ':\n' + (new Error).stack);
  491.   ABORT = true;
  492.   throw "Assertion: " + text;
  493. }
  494.  
  495. function assert(condition, text) {
  496.   if (!condition) {
  497.     abort('Assertion failed: ' + text);
  498.   }
  499. }
  500.  
  501. var globalScope = this;
  502.  
  503. // C calling interface. A convenient way to call C functions (in C files, or
  504. // defined with extern "C").
  505. //
  506. // Note: LLVM optimizations can inline and remove functions, after which you will not be
  507. //       able to call them. Closure can also do so. To avoid that, add your function to
  508. //       the exports using something like
  509. //
  510. //         -s EXPORTED_FUNCTIONS='["_main", "_myfunc"]'
  511. //
  512. // @param ident      The name of the C function (note that C++ functions will be name-mangled - use extern "C")
  513. // @param returnType The return type of the function, one of the JS types 'number', 'string' or 'array' (use 'number' for any C pointer, and
  514. //                   'array' for JavaScript arrays and typed arrays).
  515. // @param argTypes   An array of the types of arguments for the function (if there are no arguments, this can be ommitted). Types are as in returnType,
  516. //                   except that 'array' is not possible (there is no way for us to know the length of the array)
  517. // @param args       An array of the arguments to the function, as native JS values (as in returnType)
  518. //                   Note that string arguments will be stored on the stack (the JS string will become a C string on the stack).
  519. // @return           The return value, as a native JS value (as in returnType)
  520. function ccall(ident, returnType, argTypes, args) {
  521.   return ccallFunc(getCFunc(ident), returnType, argTypes, args);
  522. }
  523. Module["ccall"] = ccall;
  524.  
  525. // Returns the C function with a specified identifier (for C++, you need to do manual name mangling)
  526. function getCFunc(ident) {
  527.   try {
  528.     var func = eval('_' + ident);
  529.   } catch(e) {
  530.     try {
  531.       func = globalScope['Module']['_' + ident]; // closure exported function
  532.     } catch(e) {}
  533.   }
  534.   assert(func, 'Cannot call unknown function ' + ident + ' (perhaps LLVM optimizations or closure removed it?)');
  535.   return func;
  536. }
  537.  
  538. // Internal function that does a C call using a function, not an identifier
  539. function ccallFunc(func, returnType, argTypes, args) {
  540.   var stack = 0;
  541.   function toC(value, type) {
  542.     if (type == 'string') {
  543.       if (value === null || value === undefined || value === 0) return 0; // null string
  544.       if (!stack) stack = Runtime.stackSave();
  545.       var ret = Runtime.stackAlloc(value.length+1);
  546.       writeStringToMemory(value, ret);
  547.       return ret;
  548.     } else if (type == 'array') {
  549.       if (!stack) stack = Runtime.stackSave();
  550.       var ret = Runtime.stackAlloc(value.length);
  551.       writeArrayToMemory(value, ret);
  552.       return ret;
  553.     }
  554.     return value;
  555.   }
  556.   function fromC(value, type) {
  557.     if (type == 'string') {
  558.       return Pointer_stringify(value);
  559.     }
  560.     assert(type != 'array');
  561.     return value;
  562.   }
  563.   var i = 0;
  564.   var cArgs = args ? args.map(function(arg) {
  565.     return toC(arg, argTypes[i++]);
  566.   }) : [];
  567.   var ret = fromC(func.apply(null, cArgs), returnType);
  568.   if (stack) Runtime.stackRestore(stack);
  569.   return ret;
  570. }
  571.  
  572. // Returns a native JS wrapper for a C function. This is similar to ccall, but
  573. // returns a function you can call repeatedly in a normal way. For example:
  574. //
  575. //   var my_function = cwrap('my_c_function', 'number', ['number', 'number']);
  576. //   alert(my_function(5, 22));
  577. //   alert(my_function(99, 12));
  578. //
  579. function cwrap(ident, returnType, argTypes) {
  580.   var func = getCFunc(ident);
  581.   return function() {
  582.     return ccallFunc(func, returnType, argTypes, Array.prototype.slice.call(arguments));
  583.   }
  584. }
  585. Module["cwrap"] = cwrap;
  586.  
  587. // Sets a value in memory in a dynamic way at run-time. Uses the
  588. // type data. This is the same as makeSetValue, except that
  589. // makeSetValue is done at compile-time and generates the needed
  590. // code then, whereas this function picks the right code at
  591. // run-time.
  592. // Note that setValue and getValue only do *aligned* writes and reads!
  593. // Note that ccall uses JS types as for defining types, while setValue and
  594. // getValue need LLVM types ('i8', 'i32') - this is a lower-level operation
  595. function setValue(ptr, value, type, noSafe) {
  596.   type = type || 'i8';
  597.   if (type.charAt(type.length-1) === '*') type = 'i32'; // pointers are 32-bit
  598.     switch(type) {
  599.       case 'i1': HEAP8[(ptr)]=value; break;
  600.       case 'i8': HEAP8[(ptr)]=value; break;
  601.       case 'i16': HEAP16[((ptr)>>1)]=value; break;
  602.       case 'i32': HEAP32[((ptr)>>2)]=value; break;
  603.       case 'i64': (tempI64 = [value>>>0,Math.min(Math.floor((value)/4294967296), 4294967295)>>>0],HEAP32[((ptr)>>2)]=tempI64[0],HEAP32[(((ptr)+(4))>>2)]=tempI64[1]); break;
  604.       case 'float': HEAPF32[((ptr)>>2)]=value; break;
  605.       case 'double': (HEAPF64[(tempDoublePtr)>>3]=value,HEAP32[((ptr)>>2)]=HEAP32[((tempDoublePtr)>>2)],HEAP32[(((ptr)+(4))>>2)]=HEAP32[(((tempDoublePtr)+(4))>>2)]); break;
  606.       default: abort('invalid type for setValue: ' + type);
  607.     }
  608. }
  609. Module['setValue'] = setValue;
  610.  
  611. // Parallel to setValue.
  612. function getValue(ptr, type, noSafe) {
  613.   type = type || 'i8';
  614.   if (type.charAt(type.length-1) === '*') type = 'i32'; // pointers are 32-bit
  615.     switch(type) {
  616.       case 'i1': return HEAP8[(ptr)];
  617.       case 'i8': return HEAP8[(ptr)];
  618.       case 'i16': return HEAP16[((ptr)>>1)];
  619.       case 'i32': return HEAP32[((ptr)>>2)];
  620.       case 'i64': return HEAP32[((ptr)>>2)];
  621.       case 'float': return HEAPF32[((ptr)>>2)];
  622.       case 'double': return (HEAP32[((tempDoublePtr)>>2)]=HEAP32[((ptr)>>2)],HEAP32[(((tempDoublePtr)+(4))>>2)]=HEAP32[(((ptr)+(4))>>2)],HEAPF64[(tempDoublePtr)>>3]);
  623.       default: abort('invalid type for setValue: ' + type);
  624.     }
  625.   return null;
  626. }
  627. Module['getValue'] = getValue;
  628.  
  629. var ALLOC_NORMAL = 0; // Tries to use _malloc()
  630. var ALLOC_STACK = 1; // Lives for the duration of the current function call
  631. var ALLOC_STATIC = 2; // Cannot be freed
  632. var ALLOC_NONE = 3; // Do not allocate
  633. Module['ALLOC_NORMAL'] = ALLOC_NORMAL;
  634. Module['ALLOC_STACK'] = ALLOC_STACK;
  635. Module['ALLOC_STATIC'] = ALLOC_STATIC;
  636. Module['ALLOC_NONE'] = ALLOC_NONE;
  637.  
  638. // Simple unoptimized memset - necessary during startup
  639. var _memset = function(ptr, value, num) {
  640.   var stop = ptr + num;
  641.   while (ptr < stop) {
  642.     HEAP8[(ptr++)]=value;
  643.   }
  644. }
  645.  
  646. // allocate(): This is for internal use. You can use it yourself as well, but the interface
  647. //             is a little tricky (see docs right below). The reason is that it is optimized
  648. //             for multiple syntaxes to save space in generated code. So you should
  649. //             normally not use allocate(), and instead allocate memory using _malloc(),
  650. //             initialize it with setValue(), and so forth.
  651. // @slab: An array of data, or a number. If a number, then the size of the block to allocate,
  652. //        in *bytes* (note that this is sometimes confusing: the next parameter does not
  653. //        affect this!)
  654. // @types: Either an array of types, one for each byte (or 0 if no type at that position),
  655. //         or a single type which is used for the entire block. This only matters if there
  656. //         is initial data - if @slab is a number, then this does not matter at all and is
  657. //         ignored.
  658. // @allocator: How to allocate memory, see ALLOC_*
  659. function allocate(slab, types, allocator, ptr) {
  660.   var zeroinit, size;
  661.   if (typeof slab === 'number') {
  662.     zeroinit = true;
  663.     size = slab;
  664.   } else {
  665.     zeroinit = false;
  666.     size = slab.length;
  667.   }
  668.  
  669.   var singleType = typeof types === 'string' ? types : null;
  670.  
  671.   var ret;
  672.   if (allocator == ALLOC_NONE) {
  673.     ret = ptr;
  674.   } else {
  675.     ret = [_malloc, Runtime.stackAlloc, Runtime.staticAlloc][allocator === undefined ? ALLOC_STATIC : allocator](Math.max(size, singleType ? 1 : types.length));
  676.   }
  677.  
  678.   if (zeroinit) {
  679.     _memset(ret, 0, size);
  680.     return ret;
  681.   }
  682.  
  683.   if (singleType === 'i8') {
  684.     HEAPU8.set(new Uint8Array(slab), ret);
  685.     return ret;
  686.   }
  687.  
  688.   var i = 0, type;
  689.   while (i < size) {
  690.     var curr = slab[i];
  691.  
  692.     if (typeof curr === 'function') {
  693.       curr = Runtime.getFunctionIndex(curr);
  694.     }
  695.  
  696.     type = singleType || types[i];
  697.     if (type === 0) {
  698.       i++;
  699.       continue;
  700.     }
  701.     assert(type, 'Must know what type to store in allocate!');
  702.  
  703.     if (type == 'i64') type = 'i32'; // special case: we have one i32 here, and one i32 later
  704.  
  705.     setValue(ret+i, curr, type);
  706.     i += Runtime.getNativeTypeSize(type);
  707.   }
  708.  
  709.   return ret;
  710. }
  711. Module['allocate'] = allocate;
  712.  
  713. function Pointer_stringify(ptr, /* optional */ length) {
  714.   var utf8 = new Runtime.UTF8Processor();
  715.   var nullTerminated = typeof(length) == "undefined";
  716.   var ret = "";
  717.   var i = 0;
  718.   var t;
  719.   while (1) {
  720.   assert(i < TOTAL_MEMORY);
  721.     t = HEAPU8[((ptr)+(i))];
  722.     if (nullTerminated && t == 0) break;
  723.     ret += utf8.processCChar(t);
  724.     i += 1;
  725.     if (!nullTerminated && i == length) break;
  726.   }
  727.   return ret;
  728. }
  729. Module['Pointer_stringify'] = Pointer_stringify;
  730.  
  731. function Array_stringify(array) {
  732.   var ret = "";
  733.   for (var i = 0; i < array.length; i++) {
  734.     ret += String.fromCharCode(array[i]);
  735.   }
  736.   return ret;
  737. }
  738. Module['Array_stringify'] = Array_stringify;
  739.  
  740. // Memory management
  741.  
  742. var PAGE_SIZE = 4096;
  743. function alignMemoryPage(x) {
  744.   return ((x+4095)>>12)<<12;
  745. }
  746.  
  747. var HEAP;
  748. var HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAPF64;
  749.  
  750. var STACK_ROOT, STACKTOP, STACK_MAX;
  751. var STATICTOP;
  752. function enlargeMemory() {
  753.   abort('Cannot enlarge memory arrays. Either (1) compile with -s TOTAL_MEMORY=X with X higher than the current value, (2) compile with ALLOW_MEMORY_GROWTH which adjusts the size at runtime but prevents some optimizations, or (3) set Module.TOTAL_MEMORY before the program runs.');
  754. }
  755.  
  756. var TOTAL_STACK = Module['TOTAL_STACK'] || 5242880;
  757. var TOTAL_MEMORY = Module['TOTAL_MEMORY'] || 16777216;
  758. var FAST_MEMORY = Module['FAST_MEMORY'] || 2097152;
  759.  
  760. // Initialize the runtime's memory
  761. // check for full engine support (use string 'subarray' to avoid closure compiler confusion)
  762.   assert(!!Int32Array && !!Float64Array && !!(new Int32Array(1)['subarray']) && !!(new Int32Array(1)['set']),
  763.          'Cannot fallback to non-typed array case: Code is too specialized');
  764.  
  765.   var buffer = new ArrayBuffer(TOTAL_MEMORY);
  766.   HEAP8 = new Int8Array(buffer);
  767.   HEAP16 = new Int16Array(buffer);
  768.   HEAP32 = new Int32Array(buffer);
  769.   HEAPU8 = new Uint8Array(buffer);
  770.   HEAPU16 = new Uint16Array(buffer);
  771.   HEAPU32 = new Uint32Array(buffer);
  772.   HEAPF32 = new Float32Array(buffer);
  773.   HEAPF64 = new Float64Array(buffer);
  774.  
  775.   // Endianness check (note: assumes compiler arch was little-endian)
  776.   HEAP32[0] = 255;
  777.   assert(HEAPU8[0] === 255 && HEAPU8[3] === 0, 'Typed arrays 2 must be run on a little-endian system');
  778.  
  779. Module['HEAP'] = HEAP;
  780. Module['HEAP8'] = HEAP8;
  781. Module['HEAP16'] = HEAP16;
  782. Module['HEAP32'] = HEAP32;
  783. Module['HEAPU8'] = HEAPU8;
  784. Module['HEAPU16'] = HEAPU16;
  785. Module['HEAPU32'] = HEAPU32;
  786. Module['HEAPF32'] = HEAPF32;
  787. Module['HEAPF64'] = HEAPF64;
  788.  
  789. STACK_ROOT = STACKTOP = Runtime.alignMemory(1);
  790. STACK_MAX = TOTAL_STACK; // we lose a little stack here, but TOTAL_STACK is nice and round so use that as the max
  791.  
  792. var tempDoublePtr = Runtime.alignMemory(allocate(12, 'i8', ALLOC_STACK), 8);
  793. assert(tempDoublePtr % 8 == 0);
  794. function copyTempFloat(ptr) { // functions, because inlining this code is increases code size too much
  795.   HEAP8[tempDoublePtr] = HEAP8[ptr];
  796.   HEAP8[tempDoublePtr+1] = HEAP8[ptr+1];
  797.   HEAP8[tempDoublePtr+2] = HEAP8[ptr+2];
  798.   HEAP8[tempDoublePtr+3] = HEAP8[ptr+3];
  799. }
  800. function copyTempDouble(ptr) {
  801.   HEAP8[tempDoublePtr] = HEAP8[ptr];
  802.   HEAP8[tempDoublePtr+1] = HEAP8[ptr+1];
  803.   HEAP8[tempDoublePtr+2] = HEAP8[ptr+2];
  804.   HEAP8[tempDoublePtr+3] = HEAP8[ptr+3];
  805.   HEAP8[tempDoublePtr+4] = HEAP8[ptr+4];
  806.   HEAP8[tempDoublePtr+5] = HEAP8[ptr+5];
  807.   HEAP8[tempDoublePtr+6] = HEAP8[ptr+6];
  808.   HEAP8[tempDoublePtr+7] = HEAP8[ptr+7];
  809. }
  810.  
  811. STATICTOP = STACK_MAX;
  812. assert(STATICTOP < TOTAL_MEMORY); // Stack must fit in TOTAL_MEMORY; allocations from here on may enlarge TOTAL_MEMORY
  813.  
  814. var nullString = allocate(intArrayFromString('(null)'), 'i8', ALLOC_STACK);
  815.  
  816. function callRuntimeCallbacks(callbacks) {
  817.   while(callbacks.length > 0) {
  818.     var callback = callbacks.shift();
  819.     var func = callback.func;
  820.     if (typeof func === 'number') {
  821.       if (callback.arg === undefined) {
  822.         Runtime.dynCall('v', func);
  823.       } else {
  824.         Runtime.dynCall('vi', func, [callback.arg]);
  825.       }
  826.     } else {
  827.       func(callback.arg === undefined ? null : callback.arg);
  828.     }
  829.   }
  830. }
  831.  
  832. var __ATINIT__ = []; // functions called during startup
  833. var __ATMAIN__ = []; // functions called when main() is to be run
  834. var __ATEXIT__ = []; // functions called during shutdown
  835.  
  836. function initRuntime() {
  837.   callRuntimeCallbacks(__ATINIT__);
  838. }
  839. function preMain() {
  840.   callRuntimeCallbacks(__ATMAIN__);
  841. }
  842. function exitRuntime() {
  843.   callRuntimeCallbacks(__ATEXIT__);
  844.  
  845.   // Print summary of correction activity
  846.   CorrectionsMonitor.print();
  847. }
  848.  
  849. // Tools
  850.  
  851. // This processes a JS string into a C-line array of numbers, 0-terminated.
  852. // For LLVM-originating strings, see parser.js:parseLLVMString function
  853. function intArrayFromString(stringy, dontAddNull, length /* optional */) {
  854.   var ret = (new Runtime.UTF8Processor()).processJSString(stringy);
  855.   if (length) {
  856.     ret.length = length;
  857.   }
  858.   if (!dontAddNull) {
  859.     ret.push(0);
  860.   }
  861.   return ret;
  862. }
  863. Module['intArrayFromString'] = intArrayFromString;
  864.  
  865. function intArrayToString(array) {
  866.   var ret = [];
  867.   for (var i = 0; i < array.length; i++) {
  868.     var chr = array[i];
  869.     if (chr > 0xFF) {
  870.         assert(false, 'Character code ' + chr + ' (' + String.fromCharCode(chr) + ')  at offset ' + i + ' not in 0x00-0xFF.');
  871.       chr &= 0xFF;
  872.     }
  873.     ret.push(String.fromCharCode(chr));
  874.   }
  875.   return ret.join('');
  876. }
  877. Module['intArrayToString'] = intArrayToString;
  878.  
  879. // Write a Javascript array to somewhere in the heap
  880. function writeStringToMemory(string, buffer, dontAddNull) {
  881.   var array = intArrayFromString(string, dontAddNull);
  882.   var i = 0;
  883.   while (i < array.length) {
  884.     var chr = array[i];
  885.     HEAP8[((buffer)+(i))]=chr
  886.     i = i + 1;
  887.   }
  888. }
  889. Module['writeStringToMemory'] = writeStringToMemory;
  890.  
  891. function writeArrayToMemory(array, buffer) {
  892.   for (var i = 0; i < array.length; i++) {
  893.     HEAP8[((buffer)+(i))]=array[i];
  894.   }
  895. }
  896. Module['writeArrayToMemory'] = writeArrayToMemory;
  897.  
  898. function unSign(value, bits, ignore, sig) {
  899.   if (value >= 0) {
  900.     return value;
  901.   }
  902.   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
  903.                     : Math.pow(2, bits)         + value;
  904.   // TODO: clean up previous line
  905. }
  906. function reSign(value, bits, ignore, sig) {
  907.   if (value <= 0) {
  908.     return value;
  909.   }
  910.   var half = bits <= 32 ? Math.abs(1 << (bits-1)) // abs is needed if bits == 32
  911.                         : Math.pow(2, bits-1);
  912.   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
  913.                                                        // but, in general there is no perfect solution here. With 64-bit ints, we get rounding and errors
  914.                                                        // TODO: In i64 mode 1, resign the two parts separately and safely
  915.     value = -2*half + value; // Cannot bitshift half, as it may be at the limit of the bits JS uses in bitshifts
  916.   }
  917.   return value;
  918. }
  919.  
  920. // A counter of dependencies for calling run(). If we need to
  921. // do asynchronous work before running, increment this and
  922. // decrement it. Incrementing must happen in a place like
  923. // PRE_RUN_ADDITIONS (used by emcc to add file preloading).
  924. // Note that you can add dependencies in preRun, even though
  925. // it happens right before run - run will be postponed until
  926. // the dependencies are met.
  927. var runDependencies = 0;
  928. var runDependencyTracking = {};
  929. var calledRun = false;
  930. var runDependencyWatcher = null;
  931. function addRunDependency(id) {
  932.   runDependencies++;
  933.   if (Module['monitorRunDependencies']) {
  934.     Module['monitorRunDependencies'](runDependencies);
  935.   }
  936.   if (id) {
  937.     assert(!runDependencyTracking[id]);
  938.     runDependencyTracking[id] = 1;
  939.     if (runDependencyWatcher === null && typeof setInterval !== 'undefined') {
  940.       // Check for missing dependencies every few seconds
  941.       runDependencyWatcher = setInterval(function() {
  942.         var shown = false;
  943.         for (var dep in runDependencyTracking) {
  944.           if (!shown) {
  945.             shown = true;
  946.             Module.printErr('still waiting on run dependencies:');
  947.           }
  948.           Module.printErr('dependency: ' + dep);
  949.         }
  950.         if (shown) {
  951.           Module.printErr('(end of list)');
  952.         }
  953.       }, 6000);
  954.     }
  955.   } else {
  956.     Module.printErr('warning: run dependency added without ID');
  957.   }
  958. }
  959. Module['addRunDependency'] = addRunDependency;
  960. function removeRunDependency(id) {
  961.   runDependencies--;
  962.   if (Module['monitorRunDependencies']) {
  963.     Module['monitorRunDependencies'](runDependencies);
  964.   }
  965.   if (id) {
  966.     assert(runDependencyTracking[id]);
  967.     delete runDependencyTracking[id];
  968.   } else {
  969.     Module.printErr('warning: run dependency removed without ID');
  970.   }
  971.   if (runDependencies == 0) {
  972.     if (runDependencyWatcher !== null) {
  973.       clearInterval(runDependencyWatcher);
  974.       runDependencyWatcher = null;
  975.     }
  976.     // If run has never been called, and we should call run (INVOKE_RUN is true, and Module.noInitialRun is not false)
  977.     if (!calledRun && shouldRunNow) run();
  978.   }
  979. }
  980. Module['removeRunDependency'] = removeRunDependency;
  981.  
  982. Module["preloadedImages"] = {}; // maps url to image data
  983. Module["preloadedAudios"] = {}; // maps url to audio data
  984.  
  985. // === Body ===
  986.  
  987.  
  988.  
  989.  
  990.  
  991.   var _sqrt=Math.sqrt;
  992.  
  993.   function _memcpy(dest, src, num) {
  994.       dest = dest|0; src = src|0; num = num|0;
  995.       var ret = 0;
  996.       ret = dest|0;
  997.       if ((dest&3) == (src&3)) {
  998.         while (dest & 3) {
  999.           if ((num|0) == 0) return ret|0;
  1000.           HEAP8[(dest)]=HEAP8[(src)];
  1001.           dest = (dest+1)|0;
  1002.           src = (src+1)|0;
  1003.           num = (num-1)|0;
  1004.         }
  1005.         while ((num|0) >= 4) {
  1006.           HEAP32[((dest)>>2)]=HEAP32[((src)>>2)];
  1007.           dest = (dest+4)|0;
  1008.           src = (src+4)|0;
  1009.           num = (num-4)|0;
  1010.         }
  1011.       }
  1012.       while ((num|0) > 0) {
  1013.         HEAP8[(dest)]=HEAP8[(src)];
  1014.         dest = (dest+1)|0;
  1015.         src = (src+1)|0;
  1016.         num = (num-1)|0;
  1017.       }
  1018.       return ret|0;
  1019.     }
  1020.  
  1021.   function _memset(ptr, value, num) {
  1022.       ptr = ptr|0; value = value|0; num = num|0;
  1023.       var stop = 0, value4 = 0, stop4 = 0, unaligned = 0;
  1024.       stop = (ptr + num)|0;
  1025.       if (num|0 >= 20) {
  1026.         // This is unaligned, but quite large, so work hard to get to aligned settings
  1027.         unaligned = ptr & 3;
  1028.         value4 = value | (value << 8) | (value << 16) | (value << 24);
  1029.         stop4 = stop & ~3;
  1030.         if (unaligned) {
  1031.           unaligned = (ptr + 4 - unaligned)|0;
  1032.           while ((ptr|0) < (unaligned|0)) { // no need to check for stop, since we have large num
  1033.             HEAP8[(ptr)]=value;
  1034.             ptr = (ptr+1)|0;
  1035.           }
  1036.         }
  1037.         while ((ptr|0) < (stop4|0)) {
  1038.           HEAP32[((ptr)>>2)]=value4;
  1039.           ptr = (ptr+4)|0;
  1040.         }
  1041.       }
  1042.       while ((ptr|0) < (stop|0)) {
  1043.         HEAP8[(ptr)]=value;
  1044.         ptr = (ptr+1)|0;
  1045.       }
  1046.     }
  1047.  
  1048.   function _malloc(bytes) {
  1049.       /* Over-allocate to make sure it is byte-aligned by 8.
  1050.        * This will leak memory, but this is only the dummy
  1051.        * implementation (replaced by dlmalloc normally) so
  1052.        * not an issue.
  1053.        */
  1054.       var ptr = Runtime.staticAlloc(bytes + 8);
  1055.       return (ptr+8) & 0xFFFFFFF8;
  1056.     }
  1057.  
  1058.   function _free(){}
  1059.  
  1060.   var Browser={mainLoop:{scheduler:null,shouldPause:false,paused:false,queue:[],pause:function () {
  1061.           Browser.mainLoop.shouldPause = true;
  1062.         },resume:function () {
  1063.           if (Browser.mainLoop.paused) {
  1064.             Browser.mainLoop.paused = false;
  1065.             Browser.mainLoop.scheduler();
  1066.           }
  1067.           Browser.mainLoop.shouldPause = false;
  1068.         },updateStatus:function () {
  1069.           if (Module['setStatus']) {
  1070.             var message = Module['statusMessage'] || 'Please wait...';
  1071.             var remaining = Browser.mainLoop.remainingBlockers;
  1072.             var expected = Browser.mainLoop.expectedBlockers;
  1073.             if (remaining) {
  1074.               if (remaining < expected) {
  1075.                 Module['setStatus'](message + ' (' + (expected - remaining) + '/' + expected + ')');
  1076.               } else {
  1077.                 Module['setStatus'](message);
  1078.               }
  1079.             } else {
  1080.               Module['setStatus']('');
  1081.             }
  1082.           }
  1083.         }},pointerLock:false,moduleContextCreatedCallbacks:[],workers:[],ensureObjects:function () {
  1084.         if (Browser.ensured) return;
  1085.         Browser.ensured = true;
  1086.         try {
  1087.           new Blob();
  1088.           Browser.hasBlobConstructor = true;
  1089.         } catch(e) {
  1090.           Browser.hasBlobConstructor = false;
  1091.           console.log("warning: no blob constructor, cannot create blobs with mimetypes");
  1092.         }
  1093.         Browser.BlobBuilder = typeof MozBlobBuilder != "undefined" ? MozBlobBuilder : (typeof WebKitBlobBuilder != "undefined" ? WebKitBlobBuilder : (!Browser.hasBlobConstructor ? console.log("warning: no BlobBuilder") : null));
  1094.         Browser.URLObject = typeof window != "undefined" ? (window.URL ? window.URL : window.webkitURL) : console.log("warning: cannot create object URLs");
  1095.  
  1096.         // Support for plugins that can process preloaded files. You can add more of these to
  1097.         // your app by creating and appending to Module.preloadPlugins.
  1098.         //
  1099.         // Each plugin is asked if it can handle a file based on the file's name. If it can,
  1100.         // it is given the file's raw data. When it is done, it calls a callback with the file's
  1101.         // (possibly modified) data. For example, a plugin might decompress a file, or it
  1102.         // might create some side data structure for use later (like an Image element, etc.).
  1103.  
  1104.         function getMimetype(name) {
  1105.           return {
  1106.             'jpg': 'image/jpeg',
  1107.             'png': 'image/png',
  1108.             'bmp': 'image/bmp',
  1109.             'ogg': 'audio/ogg',
  1110.             'wav': 'audio/wav',
  1111.             'mp3': 'audio/mpeg'
  1112.           }[name.substr(-3)];
  1113.           return ret;
  1114.         }
  1115.  
  1116.         if (!Module["preloadPlugins"]) Module["preloadPlugins"] = [];
  1117.  
  1118.         var imagePlugin = {};
  1119.         imagePlugin['canHandle'] = function(name) {
  1120.           return name.substr(-4) in { '.jpg': 1, '.png': 1, '.bmp': 1 };
  1121.         };
  1122.         imagePlugin['handle'] = function(byteArray, name, onload, onerror) {
  1123.           var b = null;
  1124.           if (Browser.hasBlobConstructor) {
  1125.             try {
  1126.               b = new Blob([byteArray], { type: getMimetype(name) });
  1127.             } catch(e) {
  1128.               Runtime.warnOnce('Blob constructor present but fails: ' + e + '; falling back to blob builder');
  1129.             }
  1130.           }
  1131.           if (!b) {
  1132.             var bb = new Browser.BlobBuilder();
  1133.             bb.append((new Uint8Array(byteArray)).buffer); // we need to pass a buffer, and must copy the array to get the right data range
  1134.             b = bb.getBlob();
  1135.           }
  1136.           var url = Browser.URLObject.createObjectURL(b);
  1137.           assert(typeof url == 'string', 'createObjectURL must return a url as a string');
  1138.           var img = new Image();
  1139.           img.onload = function() {
  1140.             assert(img.complete, 'Image ' + name + ' could not be decoded');
  1141.             var canvas = document.createElement('canvas');
  1142.             canvas.width = img.width;
  1143.             canvas.height = img.height;
  1144.             var ctx = canvas.getContext('2d');
  1145.             ctx.drawImage(img, 0, 0);
  1146.             Module["preloadedImages"][name] = canvas;
  1147.             Browser.URLObject.revokeObjectURL(url);
  1148.             if (onload) onload(byteArray);
  1149.           };
  1150.           img.onerror = function(event) {
  1151.             console.log('Image ' + url + ' could not be decoded');
  1152.             if (onerror) onerror();
  1153.           };
  1154.           img.src = url;
  1155.         };
  1156.         Module['preloadPlugins'].push(imagePlugin);
  1157.  
  1158.         var audioPlugin = {};
  1159.         audioPlugin['canHandle'] = function(name) {
  1160.           return name.substr(-4) in { '.ogg': 1, '.wav': 1, '.mp3': 1 };
  1161.         };
  1162.         audioPlugin['handle'] = function(byteArray, name, onload, onerror) {
  1163.           var done = false;
  1164.           function finish(audio) {
  1165.             if (done) return;
  1166.             done = true;
  1167.             Module["preloadedAudios"][name] = audio;
  1168.             if (onload) onload(byteArray);
  1169.           }
  1170.           function fail() {
  1171.             if (done) return;
  1172.             done = true;
  1173.             Module["preloadedAudios"][name] = new Audio(); // empty shim
  1174.             if (onerror) onerror();
  1175.           }
  1176.           if (Browser.hasBlobConstructor) {
  1177.             try {
  1178.               var b = new Blob([byteArray], { type: getMimetype(name) });
  1179.             } catch(e) {
  1180.               return fail();
  1181.             }
  1182.             var url = Browser.URLObject.createObjectURL(b); // XXX we never revoke this!
  1183.             assert(typeof url == 'string', 'createObjectURL must return a url as a string');
  1184.             var audio = new Audio();
  1185.             audio.addEventListener('canplaythrough', function() { finish(audio) }, false); // use addEventListener due to chromium bug 124926
  1186.             audio.onerror = function(event) {
  1187.               if (done) return;
  1188.               console.log('warning: browser could not fully decode audio ' + name + ', trying slower base64 approach');
  1189.               function encode64(data) {
  1190.                 var BASE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  1191.                 var PAD = '=';
  1192.                 var ret = '';
  1193.                 var leftchar = 0;
  1194.                 var leftbits = 0;
  1195.                 for (var i = 0; i < data.length; i++) {
  1196.                   leftchar = (leftchar << 8) | data[i];
  1197.                   leftbits += 8;
  1198.                   while (leftbits >= 6) {
  1199.                     var curr = (leftchar >> (leftbits-6)) & 0x3f;
  1200.                     leftbits -= 6;
  1201.                     ret += BASE[curr];
  1202.                   }
  1203.                 }
  1204.                 if (leftbits == 2) {
  1205.                   ret += BASE[(leftchar&3) << 4];
  1206.                   ret += PAD + PAD;
  1207.                 } else if (leftbits == 4) {
  1208.                   ret += BASE[(leftchar&0xf) << 2];
  1209.                   ret += PAD;
  1210.                 }
  1211.                 return ret;
  1212.               }
  1213.               audio.src = 'data:audio/x-' + name.substr(-3) + ';base64,' + encode64(byteArray);
  1214.               finish(audio); // we don't wait for confirmation this worked - but it's worth trying
  1215.             };
  1216.             audio.src = url;
  1217.             // workaround for chrome bug 124926 - we do not always get oncanplaythrough or onerror
  1218.             setTimeout(function() {
  1219.               finish(audio); // try to use it even though it is not necessarily ready to play
  1220.             }, 10000);
  1221.           } else {
  1222.             return fail();
  1223.           }
  1224.         };
  1225.         Module['preloadPlugins'].push(audioPlugin);
  1226.       },createContext:function (canvas, useWebGL, setInModule) {
  1227.         try {
  1228.           var ctx = canvas.getContext(useWebGL ? 'experimental-webgl' : '2d');
  1229.           if (!ctx) throw ':(';
  1230.         } catch (e) {
  1231.           Module.print('Could not create canvas - ' + e);
  1232.           return null;
  1233.         }
  1234.         if (useWebGL) {
  1235.           // Set the background of the WebGL canvas to black
  1236.           canvas.style.backgroundColor = "black";
  1237.  
  1238.           // Warn on context loss
  1239.           canvas.addEventListener('webglcontextlost', function(event) {
  1240.             alert('WebGL context lost. You will need to reload the page.');
  1241.           }, false);
  1242.         }
  1243.         if (setInModule) {
  1244.           Module.ctx = ctx;
  1245.           Module.useWebGL = useWebGL;
  1246.           Browser.moduleContextCreatedCallbacks.forEach(function(callback) { callback() });
  1247.         }
  1248.         return ctx;
  1249.       },requestFullScreen:function () {
  1250.         var canvas = Module['canvas'];
  1251.         function fullScreenChange() {
  1252.           var isFullScreen = false;
  1253.           if ((document['webkitFullScreenElement'] || document['webkitFullscreenElement'] ||
  1254.                document['mozFullScreenElement'] || document['mozFullscreenElement'] ||
  1255.                document['fullScreenElement'] || document['fullscreenElement']) === canvas) {
  1256.             canvas.requestPointerLock = canvas['requestPointerLock'] ||
  1257.                                         canvas['mozRequestPointerLock'] ||
  1258.                                         canvas['webkitRequestPointerLock'];
  1259.             canvas.requestPointerLock();
  1260.             isFullScreen = true;
  1261.           }
  1262.           if (Module['onFullScreen']) Module['onFullScreen'](isFullScreen);
  1263.         }
  1264.  
  1265.         document.addEventListener('fullscreenchange', fullScreenChange, false);
  1266.         document.addEventListener('mozfullscreenchange', fullScreenChange, false);
  1267.         document.addEventListener('webkitfullscreenchange', fullScreenChange, false);
  1268.  
  1269.         function pointerLockChange() {
  1270.           Browser.pointerLock = document['pointerLockElement'] === canvas ||
  1271.                                 document['mozPointerLockElement'] === canvas ||
  1272.                                 document['webkitPointerLockElement'] === canvas;
  1273.         }
  1274.  
  1275.         document.addEventListener('pointerlockchange', pointerLockChange, false);
  1276.         document.addEventListener('mozpointerlockchange', pointerLockChange, false);
  1277.         document.addEventListener('webkitpointerlockchange', pointerLockChange, false);
  1278.  
  1279.         canvas.requestFullScreen = canvas['requestFullScreen'] ||
  1280.                                    canvas['mozRequestFullScreen'] ||
  1281.                                    (canvas['webkitRequestFullScreen'] ? function() { canvas['webkitRequestFullScreen'](Element['ALLOW_KEYBOARD_INPUT']) } : null);
  1282.         canvas.requestFullScreen();
  1283.       },requestAnimationFrame:function (func) {
  1284.         if (!window.requestAnimationFrame) {
  1285.           window.requestAnimationFrame = window['requestAnimationFrame'] ||
  1286.                                          window['mozRequestAnimationFrame'] ||
  1287.                                          window['webkitRequestAnimationFrame'] ||
  1288.                                          window['msRequestAnimationFrame'] ||
  1289.                                          window['oRequestAnimationFrame'] ||
  1290.                                          window['setTimeout'];
  1291.         }
  1292.         window.requestAnimationFrame(func);
  1293.       },getMovementX:function (event) {
  1294.         return event['movementX'] ||
  1295.                event['mozMovementX'] ||
  1296.                event['webkitMovementX'] ||
  1297.                0;
  1298.       },getMovementY:function (event) {
  1299.         return event['movementY'] ||
  1300.                event['mozMovementY'] ||
  1301.                event['webkitMovementY'] ||
  1302.                0;
  1303.       },xhrLoad:function (url, onload, onerror) {
  1304.         var xhr = new XMLHttpRequest();
  1305.         xhr.open('GET', url, true);
  1306.         xhr.responseType = 'arraybuffer';
  1307.         xhr.onload = function() {
  1308.           if (xhr.status == 200) {
  1309.             onload(xhr.response);
  1310.           } else {
  1311.             onerror();
  1312.           }
  1313.         };
  1314.         xhr.onerror = onerror;
  1315.         xhr.send(null);
  1316.       },asyncLoad:function (url, onload, onerror, noRunDep) {
  1317.         Browser.xhrLoad(url, function(arrayBuffer) {
  1318.           assert(arrayBuffer, 'Loading data file "' + url + '" failed (no arrayBuffer).');
  1319.           onload(new Uint8Array(arrayBuffer));
  1320.           if (!noRunDep) removeRunDependency('al ' + url);
  1321.         }, function(event) {
  1322.           if (onerror) {
  1323.             onerror();
  1324.           } else {
  1325.             throw 'Loading data file "' + url + '" failed.';
  1326.           }
  1327.         });
  1328.         if (!noRunDep) addRunDependency('al ' + url);
  1329.       },resizeListeners:[],updateResizeListeners:function () {
  1330.         var canvas = Module['canvas'];
  1331.         Browser.resizeListeners.forEach(function(listener) {
  1332.           listener(canvas.width, canvas.height);
  1333.         });
  1334.       },setCanvasSize:function (width, height, noUpdates) {
  1335.         var canvas = Module['canvas'];
  1336.         canvas.width = width;
  1337.         canvas.height = height;
  1338.         if (!noUpdates) Browser.updateResizeListeners();
  1339.       }};
  1340. Module["requestFullScreen"] = function() { Browser.requestFullScreen() };
  1341.   Module["requestAnimationFrame"] = function(func) { Browser.requestAnimationFrame(func) };
  1342.   Module["pauseMainLoop"] = function() { Browser.mainLoop.pause() };
  1343.   Module["resumeMainLoop"] = function() { Browser.mainLoop.resume() };
  1344.  
  1345.  
  1346.  
  1347. var FUNCTION_TABLE = [0, 0];
  1348.  
  1349. function _int_sqrt($x) {
  1350.   var label = 0;
  1351.  
  1352.  
  1353.   var $1;
  1354.   $1=$x;
  1355.   var $2=$1;
  1356.   var $3=(($2)|0);
  1357.   var $4=Math.sqrt($3);
  1358.   var $5=(($4)&-1);
  1359.  
  1360.   return $5;
  1361. }
  1362. Module["_int_sqrt"] = _int_sqrt;
  1363.  
  1364. // Warning: printing of i64 values may be slightly rounded! No deep i64 math used, so precise i64 code not included
  1365. var i64Math = null;
  1366.  
  1367. // === Auto-generated postamble setup entry stuff ===
  1368.  
  1369. Module.callMain = function callMain(args) {
  1370.   var argc = args.length+1;
  1371.   function pad() {
  1372.     for (var i = 0; i < 4-1; i++) {
  1373.       argv.push(0);
  1374.     }
  1375.   }
  1376.   var argv = [allocate(intArrayFromString("/bin/this.program"), 'i8', ALLOC_STATIC) ];
  1377.   pad();
  1378.   for (var i = 0; i < argc-1; i = i + 1) {
  1379.     argv.push(allocate(intArrayFromString(args[i]), 'i8', ALLOC_STATIC));
  1380.     pad();
  1381.   }
  1382.   argv.push(0);
  1383.   argv = allocate(argv, 'i32', ALLOC_STATIC);
  1384.  
  1385.  
  1386.   var ret;
  1387.  
  1388.   ret = Module['_main'](argc, argv, 0);
  1389.  
  1390.  
  1391.   return ret;
  1392. }
  1393.  
  1394.  
  1395.  
  1396.  
  1397. function run(args) {
  1398.   args = args || Module['arguments'];
  1399.  
  1400.   if (runDependencies > 0) {
  1401.     Module.printErr('run() called, but dependencies remain, so not running');
  1402.     return 0;
  1403.   }
  1404.  
  1405.   if (Module['preRun']) {
  1406.     if (typeof Module['preRun'] == 'function') Module['preRun'] = [Module['preRun']];
  1407.     var toRun = Module['preRun'];
  1408.     Module['preRun'] = [];
  1409.     for (var i = toRun.length-1; i >= 0; i--) {
  1410.       toRun[i]();
  1411.     }
  1412.     if (runDependencies > 0) {
  1413.       // a preRun added a dependency, run will be called later
  1414.       return 0;
  1415.     }
  1416.   }
  1417.  
  1418.   function doRun() {
  1419.     var ret = 0;
  1420.     calledRun = true;
  1421.     if (Module['_main']) {
  1422.       preMain();
  1423.       ret = Module.callMain(args);
  1424.       if (!Module['noExitRuntime']) {
  1425.         exitRuntime();
  1426.       }
  1427.     }
  1428.     if (Module['postRun']) {
  1429.       if (typeof Module['postRun'] == 'function') Module['postRun'] = [Module['postRun']];
  1430.       while (Module['postRun'].length > 0) {
  1431.         Module['postRun'].pop()();
  1432.       }
  1433.     }
  1434.     return ret;
  1435.   }
  1436.  
  1437.   if (Module['setStatus']) {
  1438.     Module['setStatus']('Running...');
  1439.     setTimeout(function() {
  1440.       setTimeout(function() {
  1441.         Module['setStatus']('');
  1442.       }, 1);
  1443.       doRun();
  1444.     }, 1);
  1445.     return 0;
  1446.   } else {
  1447.     return doRun();
  1448.   }
  1449. }
  1450. Module['run'] = Module.run = run;
  1451.  
  1452. // {{PRE_RUN_ADDITIONS}}
  1453.  
  1454. if (Module['preInit']) {
  1455.   if (typeof Module['preInit'] == 'function') Module['preInit'] = [Module['preInit']];
  1456.   while (Module['preInit'].length > 0) {
  1457.     Module['preInit'].pop()();
  1458.   }
  1459. }
  1460.  
  1461. initRuntime();
  1462.  
  1463. var shouldRunNow = true;
  1464. if (Module['noInitialRun']) {
  1465.   shouldRunNow = false;
  1466. }
  1467.  
  1468. if (shouldRunNow) {
  1469.   var ret = run();
  1470. }
  1471.  
  1472. // {{POST_RUN_ADDITIONS}}
  1473.  
  1474.  
  1475.  
  1476.  
  1477.  
  1478.  
  1479.   // {{MODULE_ADDITIONS}}
  1480.  
  1481.  
  1482. // EMSCRIPTEN_GENERATED_FUNCTIONS: ["_int_sqrt"]
Add Comment
Please, Sign In to add comment