summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorZoRo <dos21h@gmail.com>2020-11-17 20:06:44 +0000
committerZoRo <dos21h@gmail.com>2020-11-17 20:06:44 +0000
commit677a52fe2323769619cd2fd15012a210f7d680e2 (patch)
tree104a8ee526be3cd4cc3c68bc28c9c8a4851fabe9
parenta5d473dfc0ca64a6aceba0cea3db663134f73d37 (diff)
downloadwasm_fractal-677a52fe2323769619cd2fd15012a210f7d680e2.tar.gz
wasm_fractal-677a52fe2323769619cd2fd15012a210f7d680e2.zip
Working version of fractal
-rw-r--r--Makefile4
-rw-r--r--fractal.c140
-rw-r--r--index.html26
-rw-r--r--index.js1
-rw-r--r--index.wasmbin0 -> 570874 bytes
5 files changed, 158 insertions, 13 deletions
diff --git a/Makefile b/Makefile
index 9e99e53..31ecc79 100644
--- a/Makefile
+++ b/Makefile
@@ -9,9 +9,9 @@ EM_LDFALGS=-s USE_SDL=2 -s USE_SDL_IMAGE=2 -s SDL2_IMAGE_FORMATS='["png"]' -s US
make:
$(CC) -c koh.c
$(CC) -c fractal.c
- $(CC) -c fractal2.c
+ #$(CC) -c fractal2.c
$(CC) koh.o fractal.o -o fractal $(LDFLAGS)
- $(CC) koh.o fractal2.o -o fractal2 $(LDFLAGS)
+ #$(CC) koh.o fractal2.o -o fractal2 $(LDFLAGS)
emcc:
$(EMCC) fractal.c koh.c -s WASM=1 -O3 -o index.js $(EM_LDFALGS) -s EXTRA_EXPORTED_RUNTIME_METHODS='["ccall", "cwrap"]'
diff --git a/fractal.c b/fractal.c
index 783ad87..dcb54b5 100644
--- a/fractal.c
+++ b/fractal.c
@@ -135,7 +135,7 @@ void generate_koh(int gener, double size, int posx, int posy, double k)
int i;
koh_node kn = {-1,-1,-1,-1};
- printf("%f %f\n",size,k);
+ //printf("%f %f\n",size,k);
double t_size = size*k;
if (gener<0)
@@ -150,7 +150,7 @@ void generate_koh(int gener, double size, int posx, int posy, double k)
kn.y = posy;
- printf("Gener %d posx %d posy %d size %f=>%f\n",gener,posx,posy,size,t_size);
+ //printf("Gener %d posx %d posy %d size %f=>%f\n",gener,posx,posy,size,t_size);
queue_add(kn);
generate_koh(gener-1, t_size, posx-t_size/2, posy-t_size/2, k);
@@ -195,18 +195,47 @@ void Triangle( int x, int y, int w, int h)
}
// Shader sources
+#if 1
const GLchar* vertexSource =
+ "#version 100 \n"
"attribute vec4 position; \n"
+ "attribute vec4 colour; \n"
+ "varying vec4 interpolated_colour;\n"
"void main() \n"
"{ \n"
- " gl_Position = vec4(position.xyz, 1.0); \n"
+ " interpolated_colour = colour;\n"
+ " gl_Position = position; \n"
+ " \n"
"} \n";
+#else
+const GLchar* vertexSource =
+"layout(location = 0) in vec3 vertexPosition;\n"
+"layout(location = 1) in vec3 vertexColor;\n"
+"out vec3 fragmentColor;\n"
+"uniform mat4 MVP;\n"
+"void main(){ \n"
+" gl_Position = vec4(vertexPosition,1);\n"
+" fragmentColor = vertexColor;\n"
+"}\n";
+#endif
+
+#if 1
const GLchar* fragmentSource =
+ "#version 100 \n"
"precision mediump float;\n"
+ "varying vec4 interpolated_colour;\n"
"void main() \n"
"{ \n"
- " gl_FragColor = vec4 (1.0, 1.0, 1.0, 1.0 );\n"
+ " gl_FragColor = interpolated_colour;\n"
"} \n";
+#else
+const GLchar* fragmentSource =
+"in vec3 fragmentColor;\n"
+"out vec3 color;\n"
+"void main(){\n"
+" color = vec3(0.0,0.0,0.0);\n"
+"}\n";
+#endif
GLuint vertexShader;
GLuint fragmentShader;
@@ -225,21 +254,63 @@ void RectPX( int x, int y,int w, int h )
x1, y1, 0.0f };
GLuint vertexPosObject;
- printf("x1 %f y1 %f x2 %f y2 %f\n",x1,y1,x2,y2);
+ //printf("x1 %f y1 %f x2 %f y2 %f\n",x1,y1,x2,y2);
+
+ glGenBuffers(1, &vertexPosObject);
+ glBindBuffer(GL_ARRAY_BUFFER, vertexPosObject);
+ glBufferData(GL_ARRAY_BUFFER, sizeof(vVertices), vVertices, GL_STATIC_DRAW);
+
+ glEnableVertexAttribArray(0);
+ glBindBuffer(GL_ARRAY_BUFFER, vertexPosObject);
+ glVertexAttribPointer(0 /* ? */, 3, GL_FLOAT, GL_FALSE, 0, 0);
+
+ glDrawArrays ( GL_TRIANGLE_FAN, 0, 4 );
+
+}
+
+void RectPXcolor( int x, int y,int w, int h, rgba32_t c )
+{
+ GLfloat x1 = (1.0f*x-SCREEN_WIDTH2)/SCREEN_WIDTH2;
+ GLfloat y1 = (1.0f*y-SCREEN_HEIGHT2)/SCREEN_HEIGHT2;
+ GLfloat x2 = (1.0f*(x+w)-SCREEN_WIDTH2)/SCREEN_WIDTH2;
+ GLfloat y2 = (1.0f*(y+h)-SCREEN_HEIGHT2)/SCREEN_HEIGHT2;
+ GLfloat vVertices[] = { x1, y2, 0.0f,
+ x2, y2, 0.0f,
+ x2, y1, 0.0f,
+ x1, y1, 0.0f };
+ GLfloat cVertices[] = { c.r, c.g, c.b,
+ c.r, c.g, c.b,
+ c.r, c.g, c.b,
+ c.r, c.g, c.b};
+ GLuint vertexPosObject;
+ GLuint colorBuffer;
glGenBuffers(1, &vertexPosObject);
glBindBuffer(GL_ARRAY_BUFFER, vertexPosObject);
glBufferData(GL_ARRAY_BUFFER, sizeof(vVertices), vVertices, GL_STATIC_DRAW);
- //glClear ( GL_COLOR_BUFFER_BIT );
+
+ printf("!!!x1 %f y1 %f x2 %f y2 %f\n",x1,y1,x2,y2);
+ glGenBuffers(1, &colorBuffer);
+ glBindBuffer(GL_ARRAY_BUFFER, colorBuffer);
+ glBufferData(GL_ARRAY_BUFFER, sizeof(cVertices), cVertices, GL_STATIC_DRAW);
+
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vertexPosObject);
glVertexAttribPointer(0 /* ? */, 3, GL_FLOAT, GL_FALSE, 0, 0);
+
+
+ glEnableVertexAttribArray(1);
+ glBindBuffer(GL_ARRAY_BUFFER, colorBuffer);
+ glVertexAttribPointer(1 /* ? */, 3, GL_FLOAT, GL_FALSE, 0, 0);
+
+ //glDisableVertexAttribArray(0);
+ //glDisableVertexAttribArray(1);
glDrawArrays ( GL_TRIANGLE_FAN, 0, 4 );
}
-rgba32_t start_col = {1.0,1.0,1.0,0.0};
+rgba32_t start_col = {0.0,1.0,0.0,0.0};
#if __EMSCRIPTEN__
void main_tick() {
@@ -247,6 +318,7 @@ void main_tick() {
int main_tick() {
#endif
int i,j;
+ int update_fractal=0;
SDL_Event event;
SDL_StartTextInput();
while (SDL_PollEvent(&event))
@@ -259,16 +331,37 @@ int main_tick() {
quit = 1;
break;
}
+ case SDL_KEYDOWN:
+ {
+ switch (event.key.keysym.sym)
+ {
+ case SDLK_DOWN:
+ update_fractal = 1;
+ break;
+ case SDLK_UP:
+ update_fractal = 1;
+ break;
+ case SDLK_LEFT:
+ update_fractal = 1;
+ break;
+ case SDLK_RIGHT:
+ update_fractal = 1;
+ break;
+ }
+ }
}
}
- glClear( GL_COLOR_BUFFER_BIT );
+ //glClear( GL_COLOR_BUFFER_BIT );
+ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+ glUseProgram(shaderProgram);
for (i=0;i<=MAX_GENERATION;i++)
{
//rgba32_t c = color_gen_shade(start_col, i, MAX_GENERATION);
rgba32_t c = color_gen_mainlv(start_col, i, MAX_GENERATION);
//static int once=0
+ //glColor(1.0f,0.0,0.0,0.0);
for (j=0;j<queue_index;j++)
{
@@ -277,7 +370,8 @@ int main_tick() {
{
koh_node kn = queue_get(j);
printf("j:%d %d %d %d\n",j,kn.x, kn.y, kn.size);
- RectPX(kn.x, kn.y, kn.size, kn.size);
+ //RectPX(kn.x, kn.y, kn.size, kn.size);
+ RectPXcolor(kn.x, kn.y, kn.size, kn.size, c);
}
}
}
@@ -310,6 +404,8 @@ int main()
int i,j;
SDL_Event event;
GLenum error = GL_NO_ERROR;
+ GLint Result = GL_FALSE;
+ int InfoLogLength;
printf("Max queue size %d\n", QUEUE_SIZE);
SDL_Init(SDL_INIT_VIDEO);
@@ -334,7 +430,7 @@ int main()
{
printf( "Error initializing OpenGL! \n");
}
- glClearColor( 0.f, 0.f, 1.f, 1.f );
+ glClearColor( 0.f, 0.f, 0.f, 1.f );
error = glGetError();
if( error != GL_NO_ERROR )
{
@@ -348,11 +444,33 @@ int main()
vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexSource, NULL);
glCompileShader(vertexShader);
+ {
+ char buf[1024];
+ glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &Result);
+ glGetShaderiv(vertexShader, GL_INFO_LOG_LENGTH, &InfoLogLength);
+ glGetShaderInfoLog(vertexShader, InfoLogLength, NULL, &buf[0]);
+ printf("shader %s\n",buf);
+ if (Result == GL_FALSE)
+ {
+ exit(1);
+ }
+ }
// Create and compile the fragment shader
fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &fragmentSource, NULL);
glCompileShader(fragmentShader);
+ {
+ char buf[1024];
+ glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &Result);
+ glGetShaderiv(fragmentShader, GL_INFO_LOG_LENGTH, &InfoLogLength);
+ glGetShaderInfoLog(fragmentShader, InfoLogLength, NULL, &buf[0]);
+ printf("fragment %s\n",buf);
+ if (Result == GL_FALSE)
+ {
+ exit(1);
+ }
+ }
// Link the vertex and fragment shader into a shader program
shaderProgram = glCreateProgram();
@@ -361,7 +479,7 @@ int main()
glLinkProgram(shaderProgram);
glUseProgram(shaderProgram);
- posAttrib = glGetAttribLocation(shaderProgram, "position");
+ posAttrib = glGetAttribLocation(shaderProgram, "vertexPosition");
glEnableVertexAttribArray(posAttrib);
//changed from 2 to 3
glVertexAttribPointer(posAttrib, 3, GL_FLOAT, GL_FALSE, 0, 0);
diff --git a/index.html b/index.html
new file mode 100644
index 0000000..94606af
--- /dev/null
+++ b/index.html
@@ -0,0 +1,26 @@
+<html>
+ <head>
+ <meta charset="utf-8">
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+ </head>
+ <body>
+ <script type='text/javascript'>
+ var Module = {};
+ fetch('index.wasm')
+ .then(response =>
+ response.arrayBuffer()
+ ).then(buffer => {
+ Module.canvas = document.getElementById("canvas");
+ Module.wasmBinary = buffer;
+ var script = document.createElement('script');
+ script.src = "index.js";
+ script.onload = function() {
+ console.log("Emscripten boilerplate loaded.")
+ }
+ document.body.appendChild(script);
+ });
+ </script>
+ <canvas id="canvas"></canvas>
+
+ </body>
+</html> \ No newline at end of file
diff --git a/index.js b/index.js
new file mode 100644
index 0000000..13d2ce1
--- /dev/null
+++ b/index.js
@@ -0,0 +1 @@
+var Module=typeof Module!=="undefined"?Module:{};var moduleOverrides={};var key;for(key in Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}var arguments_=[];var thisProgram="./this.program";var quit_=function(status,toThrow){throw toThrow};var ENVIRONMENT_IS_WEB=false;var ENVIRONMENT_IS_WORKER=false;var ENVIRONMENT_IS_NODE=false;var ENVIRONMENT_IS_SHELL=false;ENVIRONMENT_IS_WEB=typeof window==="object";ENVIRONMENT_IS_WORKER=typeof importScripts==="function";ENVIRONMENT_IS_NODE=typeof process==="object"&&typeof process.versions==="object"&&typeof process.versions.node==="string";ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var read_,readAsync,readBinary,setWindowTitle;var nodeFS;var nodePath;if(ENVIRONMENT_IS_NODE){if(ENVIRONMENT_IS_WORKER){scriptDirectory=require("path").dirname(scriptDirectory)+"/"}else{scriptDirectory=__dirname+"/"}read_=function shell_read(filename,binary){if(!nodeFS)nodeFS=require("fs");if(!nodePath)nodePath=require("path");filename=nodePath["normalize"](filename);return nodeFS["readFileSync"](filename,binary?null:"utf8")};readBinary=function readBinary(filename){var ret=read_(filename,true);if(!ret.buffer){ret=new Uint8Array(ret)}assert(ret.buffer);return ret};if(process["argv"].length>1){thisProgram=process["argv"][1].replace(/\\/g,"/")}arguments_=process["argv"].slice(2);if(typeof module!=="undefined"){module["exports"]=Module}process["on"]("uncaughtException",function(ex){if(!(ex instanceof ExitStatus)){throw ex}});process["on"]("unhandledRejection",abort);quit_=function(status){process["exit"](status)};Module["inspect"]=function(){return"[Emscripten Module object]"}}else if(ENVIRONMENT_IS_SHELL){if(typeof read!="undefined"){read_=function shell_read(f){return read(f)}}readBinary=function readBinary(f){var data;if(typeof readbuffer==="function"){return new Uint8Array(readbuffer(f))}data=read(f,"binary");assert(typeof data==="object");return data};if(typeof scriptArgs!="undefined"){arguments_=scriptArgs}else if(typeof arguments!="undefined"){arguments_=arguments}if(typeof quit==="function"){quit_=function(status){quit(status)}}if(typeof print!=="undefined"){if(typeof console==="undefined")console={};console.log=print;console.warn=console.error=typeof printErr!=="undefined"?printErr:print}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER){scriptDirectory=self.location.href}else if(document.currentScript){scriptDirectory=document.currentScript.src}if(scriptDirectory.indexOf("blob:")!==0){scriptDirectory=scriptDirectory.substr(0,scriptDirectory.lastIndexOf("/")+1)}else{scriptDirectory=""}{read_=function shell_read(url){var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.send(null);return xhr.responseText};if(ENVIRONMENT_IS_WORKER){readBinary=function readBinary(url){var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=function readAsync(url,onload,onerror){var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=function xhr_onload(){if(xhr.status==200||xhr.status==0&&xhr.response){onload(xhr.response);return}onerror()};xhr.onerror=onerror;xhr.send(null)}}setWindowTitle=function(title){document.title=title}}else{}var out=Module["print"]||console.log.bind(console);var err=Module["printErr"]||console.warn.bind(console);for(key in moduleOverrides){if(moduleOverrides.hasOwnProperty(key)){Module[key]=moduleOverrides[key]}}moduleOverrides=null;if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["quit"])quit_=Module["quit"];var STACK_ALIGN=16;function alignMemory(size,factor){if(!factor)factor=STACK_ALIGN;return Math.ceil(size/factor)*factor}function getNativeTypeSize(type){switch(type){case"i1":case"i8":return 1;case"i16":return 2;case"i32":return 4;case"i64":return 8;case"float":return 4;case"double":return 8;default:{if(type[type.length-1]==="*"){return 4}else if(type[0]==="i"){var bits=Number(type.substr(1));assert(bits%8===0,"getNativeTypeSize invalid bits "+bits+", type "+type);return bits/8}else{return 0}}}}function warnOnce(text){if(!warnOnce.shown)warnOnce.shown={};if(!warnOnce.shown[text]){warnOnce.shown[text]=1;err(text)}}var tempRet0=0;var setTempRet0=function(value){tempRet0=value};var wasmBinary;if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];var noExitRuntime;if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(typeof WebAssembly!=="object"){abort("no native wasm support detected")}function setValue(ptr,value,type,noSafe){type=type||"i8";if(type.charAt(type.length-1)==="*")type="i32";switch(type){case"i1":HEAP8[ptr>>0]=value;break;case"i8":HEAP8[ptr>>0]=value;break;case"i16":HEAP16[ptr>>1]=value;break;case"i32":HEAP32[ptr>>2]=value;break;case"i64":tempI64=[value>>>0,(tempDouble=value,+Math_abs(tempDouble)>=1?tempDouble>0?(Math_min(+Math_floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math_ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[ptr>>2]=tempI64[0],HEAP32[ptr+4>>2]=tempI64[1];break;case"float":HEAPF32[ptr>>2]=value;break;case"double":HEAPF64[ptr>>3]=value;break;default:abort("invalid type for setValue: "+type)}}var wasmMemory;var wasmTable=new WebAssembly.Table({"initial":683,"maximum":683,"element":"anyfunc"});var ABORT=false;var EXITSTATUS=0;function assert(condition,text){if(!condition){abort("Assertion failed: "+text)}}function getCFunc(ident){var func=Module["_"+ident];assert(func,"Cannot call unknown function "+ident+", make sure it is exported");return func}function ccall(ident,returnType,argTypes,args,opts){var toC={"string":function(str){var ret=0;if(str!==null&&str!==undefined&&str!==0){var len=(str.length<<2)+1;ret=stackAlloc(len);stringToUTF8(str,ret,len)}return ret},"array":function(arr){var ret=stackAlloc(arr.length);writeArrayToMemory(arr,ret);return ret}};function convertReturnValue(ret){if(returnType==="string")return UTF8ToString(ret);if(returnType==="boolean")return Boolean(ret);return ret}var func=getCFunc(ident);var cArgs=[];var stack=0;if(args){for(var i=0;i<args.length;i++){var converter=toC[argTypes[i]];if(converter){if(stack===0)stack=stackSave();cArgs[i]=converter(args[i])}else{cArgs[i]=args[i]}}}var ret=func.apply(null,cArgs);ret=convertReturnValue(ret);if(stack!==0)stackRestore(stack);return ret}function cwrap(ident,returnType,argTypes,opts){argTypes=argTypes||[];var numericArgs=argTypes.every(function(type){return type==="number"});var numericRet=returnType!=="string";if(numericRet&&numericArgs&&!opts){return getCFunc(ident)}return function(){return ccall(ident,returnType,argTypes,arguments,opts)}}var ALLOC_NORMAL=0;var ALLOC_NONE=2;function allocate(slab,types,allocator,ptr){var zeroinit,size;if(typeof slab==="number"){zeroinit=true;size=slab}else{zeroinit=false;size=slab.length}var singleType=typeof types==="string"?types:null;var ret;if(allocator==ALLOC_NONE){ret=ptr}else{ret=[_malloc,stackAlloc][allocator](Math.max(size,singleType?1:types.length))}if(zeroinit){var stop;ptr=ret;assert((ret&3)==0);stop=ret+(size&~3);for(;ptr<stop;ptr+=4){HEAP32[ptr>>2]=0}stop=ret+size;while(ptr<stop){HEAP8[ptr++>>0]=0}return ret}if(singleType==="i8"){if(slab.subarray||slab.slice){HEAPU8.set(slab,ret)}else{HEAPU8.set(new Uint8Array(slab),ret)}return ret}var i=0,type,typeSize,previousType;while(i<size){var curr=slab[i];type=singleType||types[i];if(type===0){i++;continue}if(type=="i64")type="i32";setValue(ret+i,curr,type);if(previousType!==type){typeSize=getNativeTypeSize(type);previousType=type}i+=typeSize}return ret}var UTF8Decoder=typeof TextDecoder!=="undefined"?new TextDecoder("utf8"):undefined;function UTF8ArrayToString(heap,idx,maxBytesToRead){var endIdx=idx+maxBytesToRead;var endPtr=idx;while(heap[endPtr]&&!(endPtr>=endIdx))++endPtr;if(endPtr-idx>16&&heap.subarray&&UTF8Decoder){return UTF8Decoder.decode(heap.subarray(idx,endPtr))}else{var str="";while(idx<endPtr){var u0=heap[idx++];if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heap[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heap[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u0=(u0&7)<<18|u1<<12|u2<<6|heap[idx++]&63}if(u0<65536){str+=String.fromCharCode(u0)}else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}}return str}function UTF8ToString(ptr,maxBytesToRead){return ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead):""}function stringToUTF8Array(str,heap,outIdx,maxBytesToWrite){if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i<str.length;++i){var u=str.charCodeAt(i);if(u>=55296&&u<=57343){var u1=str.charCodeAt(++i);u=65536+((u&1023)<<10)|u1&1023}if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}}heap[outIdx]=0;return outIdx-startIdx}function stringToUTF8(str,outPtr,maxBytesToWrite){return stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite)}function lengthBytesUTF8(str){var len=0;for(var i=0;i<str.length;++i){var u=str.charCodeAt(i);if(u>=55296&&u<=57343)u=65536+((u&1023)<<10)|str.charCodeAt(++i)&1023;if(u<=127)++len;else if(u<=2047)len+=2;else if(u<=65535)len+=3;else len+=4}return len}function allocateUTF8(str){var size=lengthBytesUTF8(str)+1;var ret=_malloc(size);if(ret)stringToUTF8Array(str,HEAP8,ret,size);return ret}function writeArrayToMemory(array,buffer){HEAP8.set(array,buffer)}function writeAsciiToMemory(str,buffer,dontAddNull){for(var i=0;i<str.length;++i){HEAP8[buffer++>>0]=str.charCodeAt(i)}if(!dontAddNull)HEAP8[buffer>>0]=0}var WASM_PAGE_SIZE=65536;var buffer,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;function updateGlobalBufferAndViews(buf){buffer=buf;Module["HEAP8"]=HEAP8=new Int8Array(buf);Module["HEAP16"]=HEAP16=new Int16Array(buf);Module["HEAP32"]=HEAP32=new Int32Array(buf);Module["HEAPU8"]=HEAPU8=new Uint8Array(buf);Module["HEAPU16"]=HEAPU16=new Uint16Array(buf);Module["HEAPU32"]=HEAPU32=new Uint32Array(buf);Module["HEAPF32"]=HEAPF32=new Float32Array(buf);Module["HEAPF64"]=HEAPF64=new Float64Array(buf)}var INITIAL_INITIAL_MEMORY=Module["INITIAL_MEMORY"]||16777216;if(Module["wasmMemory"]){wasmMemory=Module["wasmMemory"]}else{wasmMemory=new WebAssembly.Memory({"initial":INITIAL_INITIAL_MEMORY/WASM_PAGE_SIZE,"maximum":INITIAL_INITIAL_MEMORY/WASM_PAGE_SIZE})}if(wasmMemory){buffer=wasmMemory.buffer}INITIAL_INITIAL_MEMORY=buffer.byteLength;updateGlobalBufferAndViews(buffer);var __ATPRERUN__=[];var __ATINIT__=[];var __ATMAIN__=[];var __ATEXIT__=[];var __ATPOSTRUN__=[];var runtimeInitialized=false;var runtimeExited=false;function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=true;if(!Module["noFSInit"]&&!FS.init.initialized)FS.init();TTY.init();callRuntimeCallbacks(__ATINIT__)}function preMain(){FS.ignorePermissions=false;callRuntimeCallbacks(__ATMAIN__)}function exitRuntime(){runtimeExited=true}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(cb){__ATPRERUN__.unshift(cb)}function addOnPostRun(cb){__ATPOSTRUN__.unshift(cb)}var Math_abs=Math.abs;var Math_ceil=Math.ceil;var Math_floor=Math.floor;var Math_min=Math.min;var runDependencies=0;var runDependencyWatcher=null;var dependenciesFulfilled=null;function getUniqueRunDependency(id){return id}function addRunDependency(id){runDependencies++;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}}function removeRunDependency(id){runDependencies--;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}if(runDependencies==0){if(runDependencyWatcher!==null){clearInterval(runDependencyWatcher);runDependencyWatcher=null}if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}Module["preloadedImages"]={};Module["preloadedAudios"]={};function abort(what){if(Module["onAbort"]){Module["onAbort"](what)}what+="";err(what);ABORT=true;EXITSTATUS=1;what="abort("+what+"). Build with -s ASSERTIONS=1 for more info.";var e=new WebAssembly.RuntimeError(what);throw e}function hasPrefix(str,prefix){return String.prototype.startsWith?str.startsWith(prefix):str.indexOf(prefix)===0}var dataURIPrefix="data:application/octet-stream;base64,";function isDataURI(filename){return hasPrefix(filename,dataURIPrefix)}var fileURIPrefix="file://";function isFileURI(filename){return hasPrefix(filename,fileURIPrefix)}var wasmBinaryFile="index.wasm";if(!isDataURI(wasmBinaryFile)){wasmBinaryFile=locateFile(wasmBinaryFile)}function getBinary(){try{if(wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(wasmBinaryFile)}else{throw"both async and sync fetching of the wasm failed"}}catch(err){abort(err)}}function getBinaryPromise(){if(!wasmBinary&&(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)&&typeof fetch==="function"&&!isFileURI(wasmBinaryFile)){return fetch(wasmBinaryFile,{credentials:"same-origin"}).then(function(response){if(!response["ok"]){throw"failed to load wasm binary file at '"+wasmBinaryFile+"'"}return response["arrayBuffer"]()}).catch(function(){return getBinary()})}return Promise.resolve().then(getBinary)}function createWasm(){var info={"a":asmLibraryArg};function receiveInstance(instance,module){var exports=instance.exports;Module["asm"]=exports;removeRunDependency("wasm-instantiate")}addRunDependency("wasm-instantiate");function receiveInstantiatedSource(output){receiveInstance(output["instance"])}function instantiateArrayBuffer(receiver){return getBinaryPromise().then(function(binary){return WebAssembly.instantiate(binary,info)}).then(receiver,function(reason){err("failed to asynchronously prepare wasm: "+reason);abort(reason)})}function instantiateAsync(){if(!wasmBinary&&typeof WebAssembly.instantiateStreaming==="function"&&!isDataURI(wasmBinaryFile)&&!isFileURI(wasmBinaryFile)&&typeof fetch==="function"){fetch(wasmBinaryFile,{credentials:"same-origin"}).then(function(response){var result=WebAssembly.instantiateStreaming(response,info);return result.then(receiveInstantiatedSource,function(reason){err("wasm streaming compile failed: "+reason);err("falling back to ArrayBuffer instantiation");return instantiateArrayBuffer(receiveInstantiatedSource)})})}else{return instantiateArrayBuffer(receiveInstantiatedSource)}}if(Module["instantiateWasm"]){try{var exports=Module["instantiateWasm"](info,receiveInstance);return exports}catch(e){err("Module.instantiateWasm callback failed with error: "+e);return false}}instantiateAsync();return{}}var tempDouble;var tempI64;var ASM_CONSTS={2186:function($0){var str=UTF8ToString($0)+"\n\n"+"Abort/Retry/Ignore/AlwaysIgnore? [ariA] :";var reply=window.prompt(str,"i");if(reply===null){reply="i"}return allocate(intArrayFromString(reply),"i8",ALLOC_NORMAL)},38092: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&255;data[dst+1]=val>>8&255;data[dst+2]=val>>16&255;data[dst+3]=255;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]=255;i=i+4|0;data8[i]=255;i=i+4|0;data8[i]=255;i=i+4|0;data8[i]=255;i=i+4|0;data8[i]=255;i=i+4|0;data8[i]=255;i=i+4|0;data8[i]=255;i=i+4|0;data8[i]=255;i=i+4|0}}else{while(i<j){data8[i]=255;i=i+4|0}}}SDL2.ctx.putImageData(SDL2.image,0,0);return 0},39571: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&255;data[dst+1]=val>>8&255;data[dst+2]=val>>16&255;data[dst+3]=val>>24&255;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},40560:function($0){if(Module["canvas"]){Module["canvas"].style["cursor"]=UTF8ToString($0)}return 0},40653:function(){if(Module["canvas"]){Module["canvas"].style["cursor"]="none"}},41878:function(){return screen.width},41905:function(){return screen.height},41933:function(){return window.innerWidth},41965:function(){return window.innerHeight},42043:function($0){if(typeof setWindowTitle!=="undefined"){setWindowTitle(UTF8ToString($0))}return 0},42177:function(){if(typeof AudioContext!=="undefined"){return 1}else if(typeof webkitAudioContext!=="undefined"){return 1}return 0},42343:function(){if(typeof navigator.mediaDevices!=="undefined"&&typeof navigator.mediaDevices.getUserMedia!=="undefined"){return 1}else if(typeof navigator.webkitGetUserMedia!=="undefined"){return 1}return 0},42569: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}if(SDL2.audioContext){autoResumeAudioContext(SDL2.audioContext)}}return SDL2.audioContext===undefined?-1:0},43122:function(){var SDL2=Module["SDL2"];return SDL2.audioContext.sampleRate},43192: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);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);var silence_callback=function(){SDL2.capture.currentCaptureBuffer=SDL2.capture.silenceBuffer;dynCall("vi",$2,[$3])};SDL2.capture.silenceTimer=setTimeout(silence_callback,$1/SDL2.audioContext.sampleRate*1e3);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)}},44844: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"])},45254: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")}}}},45859: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]}}},46339: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}}};function listenOnce(object,event,func){object.addEventListener(event,func,{"once":true})}function autoResumeAudioContext(ctx,elements){if(!elements){elements=[document,document.getElementById("canvas")]}["keydown","mousedown","touchstart"].forEach(function(event){elements.forEach(function(element){if(element){listenOnce(element,event,function(){if(ctx.state==="suspended")ctx.resume()})}})})}function callRuntimeCallbacks(callbacks){while(callbacks.length>0){var callback=callbacks.shift();if(typeof callback=="function"){callback(Module);continue}var func=callback.func;if(typeof func==="number"){if(callback.arg===undefined){wasmTable.get(func)()}else{wasmTable.get(func)(callback.arg)}}else{func(callback.arg===undefined?null:callback.arg)}}}function demangle(func){return func}function demangleAll(text){var regex=/\b_Z[\w\d_]+/g;return text.replace(regex,function(x){var y=demangle(x);return x===y?x:y+" ["+x+"]"})}function dynCallLegacy(sig,ptr,args){if(args&&args.length){return Module["dynCall_"+sig].apply(null,[ptr].concat(args))}return Module["dynCall_"+sig].call(null,ptr)}function dynCall(sig,ptr,args){if(sig.indexOf("j")!=-1){return dynCallLegacy(sig,ptr,args)}return wasmTable.get(ptr).apply(null,args)}function jsStackTrace(){var error=new Error;if(!error.stack){try{throw new Error}catch(e){error=e}if(!error.stack){return"(no stack trace available)"}}return error.stack.toString()}function stackTrace(){var js=jsStackTrace();if(Module["extraStackTrace"])js+="\n"+Module["extraStackTrace"]();return demangleAll(js)}function setErrNo(value){HEAP32[___errno_location()>>2]=value;return value}var PATH={splitPath:function(filename){var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return splitPathRe.exec(filename).slice(1)},normalizeArray:function(parts,allowAboveRoot){var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last==="."){parts.splice(i,1)}else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot){for(;up;up--){parts.unshift("..")}}return parts},normalize:function(path){var isAbsolute=path.charAt(0)==="/",trailingSlash=path.substr(-1)==="/";path=PATH.normalizeArray(path.split("/").filter(function(p){return!!p}),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path},dirname:function(path){var result=PATH.splitPath(path),root=result[0],dir=result[1];if(!root&&!dir){return"."}if(dir){dir=dir.substr(0,dir.length-1)}return root+dir},basename:function(path){if(path==="/")return"/";path=PATH.normalize(path);path=path.replace(/\/$/,"");var lastSlash=path.lastIndexOf("/");if(lastSlash===-1)return path;return path.substr(lastSlash+1)},extname:function(path){return PATH.splitPath(path)[3]},join:function(){var paths=Array.prototype.slice.call(arguments,0);return PATH.normalize(paths.join("/"))},join2:function(l,r){return PATH.normalize(l+"/"+r)}};var PATH_FS={resolve:function(){var resolvedPath="",resolvedAbsolute=false;for(var i=arguments.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?arguments[i]:FS.cwd();if(typeof path!=="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!path){return""}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=path.charAt(0)==="/"}resolvedPath=PATH.normalizeArray(resolvedPath.split("/").filter(function(p){return!!p}),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."},relative:function(from,to){from=PATH_FS.resolve(from).substr(1);to=PATH_FS.resolve(to).substr(1);function trim(arr){var start=0;for(;start<arr.length;start++){if(arr[start]!=="")break}var end=arr.length-1;for(;end>=0;end--){if(arr[end]!=="")break}if(start>end)return[];return arr.slice(start,end-start+1)}var fromParts=trim(from.split("/"));var toParts=trim(to.split("/"));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i<length;i++){if(fromParts[i]!==toParts[i]){samePartsLength=i;break}}var outputParts=[];for(var i=samePartsLength;i<fromParts.length;i++){outputParts.push("..")}outputParts=outputParts.concat(toParts.slice(samePartsLength));return outputParts.join("/")}};var TTY={ttys:[],init:function(){},shutdown:function(){},register:function(dev,ops){TTY.ttys[dev]={input:[],output:[],ops:ops};FS.registerDevice(dev,TTY.stream_ops)},stream_ops:{open:function(stream){var tty=TTY.ttys[stream.node.rdev];if(!tty){throw new FS.ErrnoError(43)}stream.tty=tty;stream.seekable=false},close:function(stream){stream.tty.ops.flush(stream.tty)},flush:function(stream){stream.tty.ops.flush(stream.tty)},read:function(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.get_char){throw new FS.ErrnoError(60)}var bytesRead=0;for(var i=0;i<length;i++){var result;try{result=stream.tty.ops.get_char(stream.tty)}catch(e){throw new FS.ErrnoError(29)}if(result===undefined&&bytesRead===0){throw new FS.ErrnoError(6)}if(result===null||result===undefined)break;bytesRead++;buffer[offset+i]=result}if(bytesRead){stream.node.timestamp=Date.now()}return bytesRead},write:function(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.put_char){throw new FS.ErrnoError(60)}try{for(var i=0;i<length;i++){stream.tty.ops.put_char(stream.tty,buffer[offset+i])}}catch(e){throw new FS.ErrnoError(29)}if(length){stream.node.timestamp=Date.now()}return i}},default_tty_ops:{get_char:function(tty){if(!tty.input.length){var result=null;if(ENVIRONMENT_IS_NODE){var BUFSIZE=256;var buf=Buffer.alloc?Buffer.alloc(BUFSIZE):new Buffer(BUFSIZE);var bytesRead=0;try{bytesRead=nodeFS.readSync(process.stdin.fd,buf,0,BUFSIZE,null)}catch(e){if(e.toString().indexOf("EOF")!=-1)bytesRead=0;else throw e}if(bytesRead>0){result=buf.slice(0,bytesRead).toString("utf-8")}else{result=null}}else if(typeof window!="undefined"&&typeof window.prompt=="function"){result=window.prompt("Input: ");if(result!==null){result+="\n"}}else if(typeof readline=="function"){result=readline();if(result!==null){result+="\n"}}if(!result){return null}tty.input=intArrayFromString(result,true)}return tty.input.shift()},put_char:function(tty,val){if(val===null||val===10){out(UTF8ArrayToString(tty.output,0));tty.output=[]}else{if(val!=0)tty.output.push(val)}},flush:function(tty){if(tty.output&&tty.output.length>0){out(UTF8ArrayToString(tty.output,0));tty.output=[]}}},default_tty1_ops:{put_char:function(tty,val){if(val===null||val===10){err(UTF8ArrayToString(tty.output,0));tty.output=[]}else{if(val!=0)tty.output.push(val)}},flush:function(tty){if(tty.output&&tty.output.length>0){err(UTF8ArrayToString(tty.output,0));tty.output=[]}}}};var MEMFS={ops_table:null,mount:function(mount){return MEMFS.createNode(null,"/",16384|511,0)},createNode:function(parent,name,mode,dev){if(FS.isBlkdev(mode)||FS.isFIFO(mode)){throw new FS.ErrnoError(63)}if(!MEMFS.ops_table){MEMFS.ops_table={dir:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,lookup:MEMFS.node_ops.lookup,mknod:MEMFS.node_ops.mknod,rename:MEMFS.node_ops.rename,unlink:MEMFS.node_ops.unlink,rmdir:MEMFS.node_ops.rmdir,readdir:MEMFS.node_ops.readdir,symlink:MEMFS.node_ops.symlink},stream:{llseek:MEMFS.stream_ops.llseek}},file:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:{llseek:MEMFS.stream_ops.llseek,read:MEMFS.stream_ops.read,write:MEMFS.stream_ops.write,allocate:MEMFS.stream_ops.allocate,mmap:MEMFS.stream_ops.mmap,msync:MEMFS.stream_ops.msync}},link:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,readlink:MEMFS.node_ops.readlink},stream:{}},chrdev:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:FS.chrdev_stream_ops}}}var node=FS.createNode(parent,name,mode,dev);if(FS.isDir(node.mode)){node.node_ops=MEMFS.ops_table.dir.node;node.stream_ops=MEMFS.ops_table.dir.stream;node.contents={}}else if(FS.isFile(node.mode)){node.node_ops=MEMFS.ops_table.file.node;node.stream_ops=MEMFS.ops_table.file.stream;node.usedBytes=0;node.contents=null}else if(FS.isLink(node.mode)){node.node_ops=MEMFS.ops_table.link.node;node.stream_ops=MEMFS.ops_table.link.stream}else if(FS.isChrdev(node.mode)){node.node_ops=MEMFS.ops_table.chrdev.node;node.stream_ops=MEMFS.ops_table.chrdev.stream}node.timestamp=Date.now();if(parent){parent.contents[name]=node}return node},getFileDataAsRegularArray:function(node){if(node.contents&&node.contents.subarray){var arr=[];for(var i=0;i<node.usedBytes;++i)arr.push(node.contents[i]);return arr}return node.contents},getFileDataAsTypedArray:function(node){if(!node.contents)return new Uint8Array(0);if(node.contents.subarray)return node.contents.subarray(0,node.usedBytes);return new Uint8Array(node.contents)},expandFileStorage:function(node,newCapacity){var prevCapacity=node.contents?node.contents.length:0;if(prevCapacity>=newCapacity)return;var CAPACITY_DOUBLING_MAX=1024*1024;newCapacity=Math.max(newCapacity,prevCapacity*(prevCapacity<CAPACITY_DOUBLING_MAX?2:1.125)>>>0);if(prevCapacity!=0)newCapacity=Math.max(newCapacity,256);var oldContents=node.contents;node.contents=new Uint8Array(newCapacity);if(node.usedBytes>0)node.contents.set(oldContents.subarray(0,node.usedBytes),0);return},resizeFileStorage:function(node,newSize){if(node.usedBytes==newSize)return;if(newSize==0){node.contents=null;node.usedBytes=0;return}if(!node.contents||node.contents.subarray){var oldContents=node.contents;node.contents=new Uint8Array(newSize);if(oldContents){node.contents.set(oldContents.subarray(0,Math.min(newSize,node.usedBytes)))}node.usedBytes=newSize;return}if(!node.contents)node.contents=[];if(node.contents.length>newSize)node.contents.length=newSize;else while(node.contents.length<newSize)node.contents.push(0);node.usedBytes=newSize},node_ops:{getattr:function(node){var attr={};attr.dev=FS.isChrdev(node.mode)?node.id:1;attr.ino=node.id;attr.mode=node.mode;attr.nlink=1;attr.uid=0;attr.gid=0;attr.rdev=node.rdev;if(FS.isDir(node.mode)){attr.size=4096}else if(FS.isFile(node.mode)){attr.size=node.usedBytes}else if(FS.isLink(node.mode)){attr.size=node.link.length}else{attr.size=0}attr.atime=new Date(node.timestamp);attr.mtime=new Date(node.timestamp);attr.ctime=new Date(node.timestamp);attr.blksize=4096;attr.blocks=Math.ceil(attr.size/attr.blksize);return attr},setattr:function(node,attr){if(attr.mode!==undefined){node.mode=attr.mode}if(attr.timestamp!==undefined){node.timestamp=attr.timestamp}if(attr.size!==undefined){MEMFS.resizeFileStorage(node,attr.size)}},lookup:function(parent,name){throw FS.genericErrors[44]},mknod:function(parent,name,mode,dev){return MEMFS.createNode(parent,name,mode,dev)},rename:function(old_node,new_dir,new_name){if(FS.isDir(old_node.mode)){var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(new_node){for(var i in new_node.contents){throw new FS.ErrnoError(55)}}}delete old_node.parent.contents[old_node.name];old_node.name=new_name;new_dir.contents[new_name]=old_node;old_node.parent=new_dir},unlink:function(parent,name){delete parent.contents[name]},rmdir:function(parent,name){var node=FS.lookupNode(parent,name);for(var i in node.contents){throw new FS.ErrnoError(55)}delete parent.contents[name]},readdir:function(node){var entries=[".",".."];for(var key in node.contents){if(!node.contents.hasOwnProperty(key)){continue}entries.push(key)}return entries},symlink:function(parent,newname,oldpath){var node=MEMFS.createNode(parent,newname,511|40960,0);node.link=oldpath;return node},readlink:function(node){if(!FS.isLink(node.mode)){throw new FS.ErrnoError(28)}return node.link}},stream_ops:{read:function(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=stream.node.usedBytes)return 0;var size=Math.min(stream.node.usedBytes-position,length);if(size>8&&contents.subarray){buffer.set(contents.subarray(position,position+size),offset)}else{for(var i=0;i<size;i++)buffer[offset+i]=contents[position+i]}return size},write:function(stream,buffer,offset,length,position,canOwn){if(!length)return 0;var node=stream.node;node.timestamp=Date.now();if(buffer.subarray&&(!node.contents||node.contents.subarray)){if(canOwn){node.contents=buffer.subarray(offset,offset+length);node.usedBytes=length;return length}else if(node.usedBytes===0&&position===0){node.contents=buffer.slice(offset,offset+length);node.usedBytes=length;return length}else if(position+length<=node.usedBytes){node.contents.set(buffer.subarray(offset,offset+length),position);return length}}MEMFS.expandFileStorage(node,position+length);if(node.contents.subarray&&buffer.subarray){node.contents.set(buffer.subarray(offset,offset+length),position)}else{for(var i=0;i<length;i++){node.contents[position+i]=buffer[offset+i]}}node.usedBytes=Math.max(node.usedBytes,position+length);return length},llseek:function(stream,offset,whence){var position=offset;if(whence===1){position+=stream.position}else if(whence===2){if(FS.isFile(stream.node.mode)){position+=stream.node.usedBytes}}if(position<0){throw new FS.ErrnoError(28)}return position},allocate:function(stream,offset,length){MEMFS.expandFileStorage(stream.node,offset+length);stream.node.usedBytes=Math.max(stream.node.usedBytes,offset+length)},mmap:function(stream,address,length,position,prot,flags){assert(address===0);if(!FS.isFile(stream.node.mode)){throw new FS.ErrnoError(43)}var ptr;var allocated;var contents=stream.node.contents;if(!(flags&2)&&contents.buffer===buffer){allocated=false;ptr=contents.byteOffset}else{if(position>0||position+length<contents.length){if(contents.subarray){contents=contents.subarray(position,position+length)}else{contents=Array.prototype.slice.call(contents,position,position+length)}}allocated=true;ptr=FS.mmapAlloc(length);if(!ptr){throw new FS.ErrnoError(48)}HEAP8.set(contents,ptr)}return{ptr:ptr,allocated:allocated}},msync:function(stream,buffer,offset,length,mmapFlags){if(!FS.isFile(stream.node.mode)){throw new FS.ErrnoError(43)}if(mmapFlags&2){return 0}var bytesWritten=MEMFS.stream_ops.write(stream,buffer,0,length,offset,false);return 0}}};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){if(!(e instanceof FS.ErrnoError))throw e+" : "+stackTrace();return setErrNo(e.errno)},lookupPath:function(path,opts){path=PATH_FS.resolve(FS.cwd(),path);opts=opts||{};if(!path)return{path:"",node:null};var defaults={follow_mount:true,recurse_count:0};for(var key in defaults){if(opts[key]===undefined){opts[key]=defaults[key]}}if(opts.recurse_count>8){throw new FS.ErrnoError(32)}var parts=PATH.normalizeArray(path.split("/").filter(function(p){return!!p}),false);var current=FS.root;var current_path="/";for(var i=0;i<parts.length;i++){var islast=i===parts.length-1;if(islast&&opts.parent){break}current=FS.lookupNode(current,parts[i]);current_path=PATH.join2(current_path,parts[i]);if(FS.isMountpoint(current)){if(!islast||islast&&opts.follow_mount){current=current.mounted.root}}if(!islast||opts.follow){var count=0;while(FS.isLink(current.mode)){var link=FS.readlink(current_path);current_path=PATH_FS.resolve(PATH.dirname(current_path),link);var lookup=FS.lookupPath(current_path,{recurse_count:opts.recurse_count});current=lookup.node;if(count++>40){throw new FS.ErrnoError(32)}}}}return{path:current_path,node:current}},getPath:function(node){var path;while(true){if(FS.isRoot(node)){var mount=node.mount.mountpoint;if(!path)return mount;return mount[mount.length-1]!=="/"?mount+"/"+path:mount+path}path=path?node.name+"/"+path:node.name;node=node.parent}},hashName:function(parentid,name){var hash=0;for(var i=0;i<name.length;i++){hash=(hash<<5)-hash+name.charCodeAt(i)|0}return(parentid+hash>>>0)%FS.nameTable.length},hashAddNode:function(node){var hash=FS.hashName(node.parent.id,node.name);node.name_next=FS.nameTable[hash];FS.nameTable[hash]=node},hashRemoveNode:function(node){var hash=FS.hashName(node.parent.id,node.name);if(FS.nameTable[hash]===node){FS.nameTable[hash]=node.name_next}else{var current=FS.nameTable[hash];while(current){if(current.name_next===node){current.name_next=node.name_next;break}current=current.name_next}}},lookupNode:function(parent,name){var errCode=FS.mayLookup(parent);if(errCode){throw new FS.ErrnoError(errCode,parent)}var hash=FS.hashName(parent.id,name);for(var node=FS.nameTable[hash];node;node=node.name_next){var nodeName=node.name;if(node.parent.id===parent.id&&nodeName===name){return node}}return FS.lookup(parent,name)},createNod