diff --git a/apps/web/public/assets/occt/occt-wasm.js b/apps/web/public/assets/occt/occt-wasm.js new file mode 100644 index 0000000..9eb174a --- /dev/null +++ b/apps/web/public/assets/occt/occt-wasm.js @@ -0,0 +1,2 @@ +async function createOcctWasm(moduleArg={}){var moduleRtn;var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer";if(ENVIRONMENT_IS_NODE){const{createRequire}=await import("node:module");var require=createRequire(import.meta.url)}var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var _scriptName=import.meta.url;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");if(_scriptName.startsWith("file:")){scriptDirectory=require("node:path").dirname(require("node:url").fileURLToPath(_scriptName))+"/"}readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(process.argv.length>1){thisProgram=process.argv[1].replace(/\\/g,"/")}arguments_=process.argv.slice(2);quit_=(status,toThrow)=>{process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{if(isFileURI(url)){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){resolve(xhr.response);return}reject(xhr.status)};xhr.onerror=reject;xhr.send(null)})}var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var EXITSTATUS;var isFileURI=filename=>filename.startsWith("file://");var readyPromiseResolve,readyPromiseReject;var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;var HEAP64,HEAPU64;var runtimeInitialized=false;function updateMemoryViews(){var b=wasmMemory.buffer;HEAP8=new Int8Array(b);HEAP16=new Int16Array(b);HEAPU8=new Uint8Array(b);HEAPU16=new Uint16Array(b);Module["HEAP32"]=HEAP32=new Int32Array(b);Module["HEAPU32"]=HEAPU32=new Uint32Array(b);Module["HEAPF32"]=HEAPF32=new Float32Array(b);HEAPF64=new Float64Array(b);HEAP64=new BigInt64Array(b);HEAPU64=new BigUint64Array(b)}function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;if(!Module["noFSInit"]&&!FS.initialized)FS.init();TTY.init();wasmExports["ba"]();FS.ignorePermissions=false}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what="Aborted("+what+")";err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";if(runtimeInitialized){___trap()}var e=new WebAssembly.RuntimeError(what);readyPromiseReject?.(e);throw e}var wasmBinaryFile;function findWasmBinary(){if(Module["locateFile"]){return locateFile("occt-wasm.wasm")}return new URL("occt-wasm.wasm",import.meta.url).href}function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance,module){wasmExports=instance.exports;wasmExports=applySignatureConversions(wasmExports);assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();if(Module["instantiateWasm"]){return new Promise((resolve,reject)=>{Module["instantiateWasm"](info,(inst,mod)=>{resolve(receiveInstance(inst,mod))})})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var addOnPostRun=cb=>onPostRuns.push(cb);var onPreRuns=[];var addOnPreRun=cb=>onPreRuns.push(cb);var noExitRuntime=true;var INT53_MAX=9007199254740992;var INT53_MIN=-9007199254740992;var bigintToI53Checked=num=>numINT53_MAX?NaN:Number(num);var wasmTableMirror=[];var getWasmTableEntry=funcPtr=>{var func=wasmTableMirror[funcPtr];if(!func){wasmTableMirror[funcPtr]=func=wasmTable.get(funcPtr)}return func};function ___call_sighandler(fp,sig){fp>>>=0;return getWasmTableEntry(fp)(sig)}var PATH={isAbs:path=>path.charAt(0)==="/",splitPath:filename=>{var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return splitPathRe.exec(filename).slice(1)},normalizeArray:(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:path=>{var isAbsolute=PATH.isAbs(path),trailingSlash=path.slice(-1)==="/";path=PATH.normalizeArray(path.split("/").filter(p=>!!p),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path},dirname:path=>{var result=PATH.splitPath(path),root=result[0],dir=result[1];if(!root&&!dir){return"."}if(dir){dir=dir.slice(0,-1)}return root+dir},basename:path=>path&&path.match(/([^\/]+|\/)\/*$/)[1],join:(...paths)=>PATH.normalize(paths.join("/")),join2:(l,r)=>PATH.normalize(l+"/"+r)};var initRandomFill=()=>{if(ENVIRONMENT_IS_NODE){var nodeCrypto=require("node:crypto");return view=>nodeCrypto.randomFillSync(view)}return view=>crypto.getRandomValues(view)};var randomFill=view=>{(randomFill=initRandomFill())(view)};var PATH_FS={resolve:(...args)=>{var resolvedPath="",resolvedAbsolute=false;for(var i=args.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?args[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.isAbs(path)}resolvedPath=PATH.normalizeArray(resolvedPath.split("/").filter(p=>!!p),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."},relative:(from,to)=>{from=PATH_FS.resolve(from).slice(1);to=PATH_FS.resolve(to).slice(1);function trim(arr){var start=0;for(;start=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{var maxIdx=idx+maxBytesToRead;if(ignoreNul)return maxIdx;while(heapOrArray[idx]&&!(idx>=maxIdx))++idx;return idx};var UTF8ArrayToString=(heapOrArray,idx=0,maxBytesToRead,ignoreNul)=>{idx>>>=0;var endPtr=findStringEnd(heapOrArray,idx,maxBytesToRead,ignoreNul);if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx>10,56320|ch&1023)}}return str};var FS_stdin_getChar_buffer=[];var lengthBytesUTF8=str=>{var len=0;for(var i=0;i=55296&&c<=57343){len+=4;++i}else{len+=3}}return len};var stringToUTF8Array=(str,heap,outIdx,maxBytesToWrite)=>{outIdx>>>=0;if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i=endIdx)break;heap[outIdx++>>>0]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++>>>0]=192|u>>6;heap[outIdx++>>>0]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++>>>0]=224|u>>12;heap[outIdx++>>>0]=128|u>>6&63;heap[outIdx++>>>0]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++>>>0]=240|u>>18;heap[outIdx++>>>0]=128|u>>12&63;heap[outIdx++>>>0]=128|u>>6&63;heap[outIdx++>>>0]=128|u&63;i++}}heap[outIdx>>>0]=0;return outIdx-startIdx};var intArrayFromString=(stringy,dontAddNull,length)=>{var len=length>0?length:lengthBytesUTF8(stringy)+1;var u8array=new Array(len);var numBytesWritten=stringToUTF8Array(stringy,u8array,0,u8array.length);if(dontAddNull)u8array.length=numBytesWritten;return u8array};var FS_stdin_getChar=()=>{if(!FS_stdin_getChar_buffer.length){var result=null;if(ENVIRONMENT_IS_NODE){var BUFSIZE=256;var buf=Buffer.alloc(BUFSIZE);var bytesRead=0;var fd=process.stdin.fd;try{bytesRead=fs.readSync(fd,buf,0,BUFSIZE)}catch(e){if(e.toString().includes("EOF"))bytesRead=0;else throw e}if(bytesRead>0){result=buf.slice(0,bytesRead).toString("utf-8")}}else if(globalThis.window?.prompt){result=window.prompt("Input: ");if(result!==null){result+="\n"}}else{}if(!result){return null}FS_stdin_getChar_buffer=intArrayFromString(result,true)}return FS_stdin_getChar_buffer.shift()};var TTY={ttys:[],init(){},shutdown(){},register(dev,ops){TTY.ttys[dev]={input:[],output:[],ops};FS.registerDevice(dev,TTY.stream_ops)},stream_ops:{open(stream){var tty=TTY.ttys[stream.node.rdev];if(!tty){throw new FS.ErrnoError(43)}stream.tty=tty;stream.seekable=false},close(stream){stream.tty.ops.fsync(stream.tty)},fsync(stream){stream.tty.ops.fsync(stream.tty)},read(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;i0){out(UTF8ArrayToString(tty.output));tty.output=[]}},ioctl_tcgets(tty){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets(tty,optional_actions,data){return 0},ioctl_tiocgwinsz(tty){return[24,80]}},default_tty1_ops:{put_char(tty,val){if(val===null||val===10){err(UTF8ArrayToString(tty.output));tty.output=[]}else{if(val!=0)tty.output.push(val)}},fsync(tty){if(tty.output?.length>0){err(UTF8ArrayToString(tty.output));tty.output=[]}}}};var mmapAlloc=size=>{abort()};var MEMFS={ops_table:null,mount(mount){return MEMFS.createNode(null,"/",16895,0)},createNode(parent,name,mode,dev){if(FS.isBlkdev(mode)||FS.isFIFO(mode)){throw new FS.ErrnoError(63)}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,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=MEMFS.emptyFileContents??=new Uint8Array(0)}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.atime=node.mtime=node.ctime=Date.now();if(parent){parent.contents[name]=node;parent.atime=parent.mtime=parent.ctime=node.atime}return node},getFileDataAsTypedArray(node){return node.contents.subarray(0,node.usedBytes)},expandFileStorage(node,newCapacity){var prevCapacity=node.contents.length;if(prevCapacity>=newCapacity)return;var CAPACITY_DOUBLING_MAX=1024*1024;newCapacity=Math.max(newCapacity,prevCapacity*(prevCapacity>>0);if(prevCapacity)newCapacity=Math.max(newCapacity,256);var oldContents=MEMFS.getFileDataAsTypedArray(node);node.contents=new Uint8Array(newCapacity);node.contents.set(oldContents)},resizeFileStorage(node,newSize){if(node.usedBytes==newSize)return;var oldContents=node.contents;node.contents=new Uint8Array(newSize);node.contents.set(oldContents.subarray(0,Math.min(newSize,node.usedBytes)));node.usedBytes=newSize},node_ops:{getattr(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.atime);attr.mtime=new Date(node.mtime);attr.ctime=new Date(node.ctime);attr.blksize=4096;attr.blocks=Math.ceil(attr.size/attr.blksize);return attr},setattr(node,attr){for(const key of["mode","atime","mtime","ctime"]){if(attr[key]!=null){node[key]=attr[key]}}if(attr.size!==undefined){MEMFS.resizeFileStorage(node,attr.size)}},lookup(parent,name){if(!MEMFS.doesNotExistError){MEMFS.doesNotExistError=new FS.ErrnoError(44);MEMFS.doesNotExistError.stack=""}throw MEMFS.doesNotExistError},mknod(parent,name,mode,dev){return MEMFS.createNode(parent,name,mode,dev)},rename(old_node,new_dir,new_name){var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(new_node){if(FS.isDir(old_node.mode)){for(var i in new_node.contents){throw new FS.ErrnoError(55)}}FS.hashRemoveNode(new_node)}delete old_node.parent.contents[old_node.name];new_dir.contents[new_name]=old_node;old_node.name=new_name;new_dir.ctime=new_dir.mtime=old_node.parent.ctime=old_node.parent.mtime=Date.now()},unlink(parent,name){delete parent.contents[name];parent.ctime=parent.mtime=Date.now()},rmdir(parent,name){var node=FS.lookupNode(parent,name);for(var i in node.contents){throw new FS.ErrnoError(55)}delete parent.contents[name];parent.ctime=parent.mtime=Date.now()},readdir(node){return[".","..",...Object.keys(node.contents)]},symlink(parent,newname,oldpath){var node=MEMFS.createNode(parent,newname,511|40960,0);node.link=oldpath;return node},readlink(node){if(!FS.isLink(node.mode)){throw new FS.ErrnoError(28)}return node.link}},stream_ops:{read(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);buffer.set(contents.subarray(position,position+size),offset);return size},write(stream,buffer,offset,length,position,canOwn){if(buffer.buffer===HEAP8.buffer){canOwn=false}if(!length)return 0;var node=stream.node;node.mtime=node.ctime=Date.now();if(canOwn){node.contents=buffer.subarray(offset,offset+length);node.usedBytes=length}else if(node.usedBytes===0&&position===0){node.contents=buffer.slice(offset,offset+length);node.usedBytes=length}else{MEMFS.expandFileStorage(node,position+length);node.contents.set(buffer.subarray(offset,offset+length),position);node.usedBytes=Math.max(node.usedBytes,position+length)}return length},llseek(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},mmap(stream,length,position,prot,flags){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===HEAP8.buffer){allocated=false;ptr=contents.byteOffset}else{allocated=true;ptr=mmapAlloc(length);if(!ptr){throw new FS.ErrnoError(48)}if(contents){if(position>0||position+length>>0)}}return{ptr,allocated}},msync(stream,buffer,offset,length,mmapFlags){MEMFS.stream_ops.write(stream,buffer,0,length,offset,false);return 0}}};var FS_modeStringToFlags=str=>{if(typeof str!="string")return str;var flagModes={r:0,"r+":2,w:512|64|1,"w+":512|64|2,a:1024|64|1,"a+":1024|64|2};var flags=flagModes[str];if(typeof flags=="undefined"){throw new Error(`Unknown file open mode: ${str}`)}return flags};var FS_fileDataToTypedArray=data=>{if(typeof data=="string"){data=intArrayFromString(data,true)}if(!data.subarray){data=new Uint8Array(data)}return data};var FS_getMode=(canRead,canWrite)=>{var mode=0;if(canRead)mode|=292|73;if(canWrite)mode|=146;return mode};var asyncLoad=async url=>{var arrayBuffer=await readAsync(url);return new Uint8Array(arrayBuffer)};var FS_createDataFile=(...args)=>FS.createDataFile(...args);var getUniqueRunDependency=id=>id;var runDependencies=0;var dependenciesFulfilled=null;var removeRunDependency=id=>{runDependencies--;Module["monitorRunDependencies"]?.(runDependencies);if(runDependencies==0){if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}};var addRunDependency=id=>{runDependencies++;Module["monitorRunDependencies"]?.(runDependencies)};var preloadPlugins=[];var FS_handledByPreloadPlugin=async(byteArray,fullname)=>{if(typeof Browser!="undefined")Browser.init();for(var plugin of preloadPlugins){if(plugin["canHandle"](fullname)){return plugin["handle"](byteArray,fullname)}}return byteArray};var FS_preloadFile=async(parent,name,url,canRead,canWrite,dontCreateFile,canOwn,preFinish)=>{var fullname=name?PATH_FS.resolve(PATH.join2(parent,name)):parent;var dep=getUniqueRunDependency(`cp ${fullname}`);addRunDependency(dep);try{var byteArray=url;if(typeof url=="string"){byteArray=await asyncLoad(url)}byteArray=await FS_handledByPreloadPlugin(byteArray,fullname);preFinish?.();if(!dontCreateFile){FS_createDataFile(parent,name,byteArray,canRead,canWrite,canOwn)}}finally{removeRunDependency(dep)}};var FS_createPreloadedFile=(parent,name,url,canRead,canWrite,onload,onerror,dontCreateFile,canOwn,preFinish)=>{FS_preloadFile(parent,name,url,canRead,canWrite,dontCreateFile,canOwn,preFinish).then(onload).catch(onerror)};var FS={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:false,ignorePermissions:true,filesystems:null,syncFSRequests:0,ErrnoError:class{name="ErrnoError";constructor(errno){this.errno=errno}},FSStream:class{shared={};get object(){return this.node}set object(val){this.node=val}get isRead(){return(this.flags&2097155)!==1}get isWrite(){return(this.flags&2097155)!==0}get isAppend(){return this.flags&1024}get flags(){return this.shared.flags}set flags(val){this.shared.flags=val}get position(){return this.shared.position}set position(val){this.shared.position=val}},FSNode:class{node_ops={};stream_ops={};readMode=292|73;writeMode=146;mounted=null;constructor(parent,name,mode,rdev){if(!parent){parent=this}this.parent=parent;this.mount=parent.mount;this.id=FS.nextInode++;this.name=name;this.mode=mode;this.rdev=rdev;this.atime=this.mtime=this.ctime=Date.now()}get read(){return(this.mode&this.readMode)===this.readMode}set read(val){val?this.mode|=this.readMode:this.mode&=~this.readMode}get write(){return(this.mode&this.writeMode)===this.writeMode}set write(val){val?this.mode|=this.writeMode:this.mode&=~this.writeMode}get isFolder(){return FS.isDir(this.mode)}get isDevice(){return FS.isChrdev(this.mode)}},lookupPath(path,opts={}){if(!path){throw new FS.ErrnoError(44)}opts.follow_mount??=true;if(!PATH.isAbs(path)){path=FS.cwd()+"/"+path}linkloop:for(var nlinks=0;nlinks<40;nlinks++){var parts=path.split("/").filter(p=>!!p);var current=FS.root;var current_path="/";for(var i=0;i>>0)%FS.nameTable.length},hashAddNode(node){var hash=FS.hashName(node.parent.id,node.name);node.name_next=FS.nameTable[hash];FS.nameTable[hash]=node},hashRemoveNode(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(parent,name){var errCode=FS.mayLookup(parent);if(errCode){throw new FS.ErrnoError(errCode)}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)},createNode(parent,name,mode,rdev){var node=new FS.FSNode(parent,name,mode,rdev);FS.hashAddNode(node);return node},destroyNode(node){FS.hashRemoveNode(node)},isRoot(node){return node===node.parent},isMountpoint(node){return!!node.mounted},isFile(mode){return(mode&61440)===32768},isDir(mode){return(mode&61440)===16384},isLink(mode){return(mode&61440)===40960},isChrdev(mode){return(mode&61440)===8192},isBlkdev(mode){return(mode&61440)===24576},isFIFO(mode){return(mode&61440)===4096},isSocket(mode){return(mode&49152)===49152},flagsToPermissionString(flag){var perms=["r","w","rw"][flag&3];if(flag&512){perms+="w"}return perms},nodePermissions(node,perms){if(FS.ignorePermissions){return 0}if(perms.includes("r")&&!(node.mode&292)){return 2}if(perms.includes("w")&&!(node.mode&146)){return 2}if(perms.includes("x")&&!(node.mode&73)){return 2}return 0},mayLookup(dir){if(!FS.isDir(dir.mode))return 54;var errCode=FS.nodePermissions(dir,"x");if(errCode)return errCode;if(!dir.node_ops.lookup)return 2;return 0},mayCreate(dir,name){if(!FS.isDir(dir.mode)){return 54}try{var node=FS.lookupNode(dir,name);return 20}catch(e){}return FS.nodePermissions(dir,"wx")},mayDelete(dir,name,isdir){var node;try{node=FS.lookupNode(dir,name)}catch(e){return e.errno}var errCode=FS.nodePermissions(dir,"wx");if(errCode){return errCode}if(isdir){if(!FS.isDir(node.mode)){return 54}if(FS.isRoot(node)||FS.getPath(node)===FS.cwd()){return 10}}else if(FS.isDir(node.mode)){return 31}return 0},mayOpen(node,flags){if(!node){return 44}if(FS.isLink(node.mode)){return 32}var mode=FS.flagsToPermissionString(flags);if(FS.isDir(node.mode)){if(mode!=="r"||flags&(512|64)){return 31}}return FS.nodePermissions(node,mode)},checkOpExists(op,err){if(!op){throw new FS.ErrnoError(err)}return op},MAX_OPEN_FDS:4096,nextfd(){for(var fd=0;fd<=FS.MAX_OPEN_FDS;fd++){if(!FS.streams[fd]){return fd}}throw new FS.ErrnoError(33)},getStreamChecked(fd){var stream=FS.getStream(fd);if(!stream){throw new FS.ErrnoError(8)}return stream},getStream:fd=>FS.streams[fd],createStream(stream,fd=-1){stream=Object.assign(new FS.FSStream,stream);if(fd==-1){fd=FS.nextfd()}stream.fd=fd;FS.streams[fd]=stream;return stream},closeStream(fd){FS.streams[fd]=null},dupStream(origStream,fd=-1){var stream=FS.createStream(origStream,fd);stream.stream_ops?.dup?.(stream);return stream},doSetAttr(stream,node,attr){var setattr=stream?.stream_ops.setattr;var arg=setattr?stream:node;setattr??=node.node_ops.setattr;FS.checkOpExists(setattr,63);setattr(arg,attr)},chrdev_stream_ops:{open(stream){var device=FS.getDevice(stream.node.rdev);stream.stream_ops=device.stream_ops;stream.stream_ops.open?.(stream)},llseek(){throw new FS.ErrnoError(70)}},major:dev=>dev>>8,minor:dev=>dev&255,makedev:(ma,mi)=>ma<<8|mi,registerDevice(dev,ops){FS.devices[dev]={stream_ops:ops}},getDevice:dev=>FS.devices[dev],getMounts(mount){var mounts=[];var check=[mount];while(check.length){var m=check.pop();mounts.push(m);check.push(...m.mounts)}return mounts},syncfs(populate,callback){if(typeof populate=="function"){callback=populate;populate=false}FS.syncFSRequests++;if(FS.syncFSRequests>1){err(`warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`)}var mounts=FS.getMounts(FS.root.mount);var completed=0;function doCallback(errCode){FS.syncFSRequests--;return callback(errCode)}function done(errCode){if(errCode){if(!done.errored){done.errored=true;return doCallback(errCode)}return}if(++completed>=mounts.length){doCallback(null)}}for(var mount of mounts){if(mount.type.syncfs){mount.type.syncfs(mount,populate,done)}else{done(null)}}},mount(type,opts,mountpoint){var root=mountpoint==="/";var pseudo=!mountpoint;var node;if(root&&FS.root){throw new FS.ErrnoError(10)}else if(!root&&!pseudo){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});mountpoint=lookup.path;node=lookup.node;if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}if(!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}}var mount={type,opts,mountpoint,mounts:[]};var mountRoot=type.mount(mount);mountRoot.mount=mount;mount.root=mountRoot;if(root){FS.root=mountRoot}else if(node){node.mounted=mount;if(node.mount){node.mount.mounts.push(mount)}}return mountRoot},unmount(mountpoint){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});if(!FS.isMountpoint(lookup.node)){throw new FS.ErrnoError(28)}var node=lookup.node;var mount=node.mounted;var mounts=FS.getMounts(mount);for(var[hash,current]of Object.entries(FS.nameTable)){while(current){var next=current.name_next;if(mounts.includes(current.mount)){FS.destroyNode(current)}current=next}}node.mounted=null;var idx=node.mount.mounts.indexOf(mount);node.mount.mounts.splice(idx,1)},lookup(parent,name){return parent.node_ops.lookup(parent,name)},mknod(path,mode,dev){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);if(!name){throw new FS.ErrnoError(28)}if(name==="."||name===".."){throw new FS.ErrnoError(20)}var errCode=FS.mayCreate(parent,name);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.mknod){throw new FS.ErrnoError(63)}return parent.node_ops.mknod(parent,name,mode,dev)},statfs(path){return FS.statfsNode(FS.lookupPath(path,{follow:true}).node)},statfsStream(stream){return FS.statfsNode(stream.node)},statfsNode(node){var rtn={bsize:4096,frsize:4096,blocks:1e6,bfree:5e5,bavail:5e5,files:FS.nextInode,ffree:FS.nextInode-1,fsid:42,flags:2,namelen:255};if(node.node_ops.statfs){Object.assign(rtn,node.node_ops.statfs(node.mount.opts.root))}return rtn},create(path,mode=438){mode&=4095;mode|=32768;return FS.mknod(path,mode,0)},mkdir(path,mode=511){mode&=511|512;mode|=16384;return FS.mknod(path,mode,0)},mkdirTree(path,mode){var dirs=path.split("/");var d="";for(var dir of dirs){if(!dir)continue;if(d||PATH.isAbs(path))d+="/";d+=dir;try{FS.mkdir(d,mode)}catch(e){if(e.errno!=20)throw e}}},mkdev(path,mode,dev){if(typeof dev=="undefined"){dev=mode;mode=438}mode|=8192;return FS.mknod(path,mode,dev)},symlink(oldpath,newpath){if(!PATH_FS.resolve(oldpath)){throw new FS.ErrnoError(44)}var lookup=FS.lookupPath(newpath,{parent:true});var parent=lookup.node;if(!parent){throw new FS.ErrnoError(44)}var newname=PATH.basename(newpath);var errCode=FS.mayCreate(parent,newname);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.symlink){throw new FS.ErrnoError(63)}return parent.node_ops.symlink(parent,newname,oldpath)},rename(old_path,new_path){var old_dirname=PATH.dirname(old_path);var new_dirname=PATH.dirname(new_path);var old_name=PATH.basename(old_path);var new_name=PATH.basename(new_path);var lookup,old_dir,new_dir;lookup=FS.lookupPath(old_path,{parent:true});old_dir=lookup.node;lookup=FS.lookupPath(new_path,{parent:true});new_dir=lookup.node;if(!old_dir||!new_dir)throw new FS.ErrnoError(44);if(old_dir.mount!==new_dir.mount){throw new FS.ErrnoError(75)}var old_node=FS.lookupNode(old_dir,old_name);var relative=PATH_FS.relative(old_path,new_dirname);if(relative.charAt(0)!=="."){throw new FS.ErrnoError(28)}relative=PATH_FS.relative(new_path,old_dirname);if(relative.charAt(0)!=="."){throw new FS.ErrnoError(55)}var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(old_node===new_node){return}var isdir=FS.isDir(old_node.mode);var errCode=FS.mayDelete(old_dir,old_name,isdir);if(errCode){throw new FS.ErrnoError(errCode)}errCode=new_node?FS.mayDelete(new_dir,new_name,isdir):FS.mayCreate(new_dir,new_name);if(errCode){throw new FS.ErrnoError(errCode)}if(!old_dir.node_ops.rename){throw new FS.ErrnoError(63)}if(FS.isMountpoint(old_node)||new_node&&FS.isMountpoint(new_node)){throw new FS.ErrnoError(10)}if(new_dir!==old_dir){errCode=FS.nodePermissions(old_dir,"w");if(errCode){throw new FS.ErrnoError(errCode)}}FS.hashRemoveNode(old_node);try{old_dir.node_ops.rename(old_node,new_dir,new_name);old_node.parent=new_dir}catch(e){throw e}finally{FS.hashAddNode(old_node)}},rmdir(path){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);var node=FS.lookupNode(parent,name);var errCode=FS.mayDelete(parent,name,true);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.rmdir){throw new FS.ErrnoError(63)}if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}parent.node_ops.rmdir(parent,name);FS.destroyNode(node)},readdir(path){var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;var readdir=FS.checkOpExists(node.node_ops.readdir,54);return readdir(node)},unlink(path){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;if(!parent){throw new FS.ErrnoError(44)}var name=PATH.basename(path);var node=FS.lookupNode(parent,name);var errCode=FS.mayDelete(parent,name,false);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.unlink){throw new FS.ErrnoError(63)}if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}parent.node_ops.unlink(parent,name);FS.destroyNode(node)},readlink(path){var lookup=FS.lookupPath(path);var link=lookup.node;if(!link){throw new FS.ErrnoError(44)}if(!link.node_ops.readlink){throw new FS.ErrnoError(28)}return link.node_ops.readlink(link)},stat(path,dontFollow){var lookup=FS.lookupPath(path,{follow:!dontFollow});var node=lookup.node;var getattr=FS.checkOpExists(node.node_ops.getattr,63);return getattr(node)},fstat(fd){var stream=FS.getStreamChecked(fd);var node=stream.node;var getattr=stream.stream_ops.getattr;var arg=getattr?stream:node;getattr??=node.node_ops.getattr;FS.checkOpExists(getattr,63);return getattr(arg)},lstat(path){return FS.stat(path,true)},doChmod(stream,node,mode,dontFollow){FS.doSetAttr(stream,node,{mode:mode&4095|node.mode&~4095,ctime:Date.now(),dontFollow})},chmod(path,mode,dontFollow){var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}FS.doChmod(null,node,mode,dontFollow)},lchmod(path,mode){FS.chmod(path,mode,true)},fchmod(fd,mode){var stream=FS.getStreamChecked(fd);FS.doChmod(stream,stream.node,mode,false)},doChown(stream,node,dontFollow){FS.doSetAttr(stream,node,{timestamp:Date.now(),dontFollow})},chown(path,uid,gid,dontFollow){var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}FS.doChown(null,node,dontFollow)},lchown(path,uid,gid){FS.chown(path,uid,gid,true)},fchown(fd,uid,gid){var stream=FS.getStreamChecked(fd);FS.doChown(stream,stream.node,false)},doTruncate(stream,node,len){if(FS.isDir(node.mode)){throw new FS.ErrnoError(31)}if(!FS.isFile(node.mode)){throw new FS.ErrnoError(28)}var errCode=FS.nodePermissions(node,"w");if(errCode){throw new FS.ErrnoError(errCode)}FS.doSetAttr(stream,node,{size:len,timestamp:Date.now()})},truncate(path,len){if(len<0){throw new FS.ErrnoError(28)}var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:true});node=lookup.node}else{node=path}FS.doTruncate(null,node,len)},ftruncate(fd,len){var stream=FS.getStreamChecked(fd);if(len<0||(stream.flags&2097155)===0){throw new FS.ErrnoError(28)}FS.doTruncate(stream,stream.node,len)},utime(path,atime,mtime){var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;var setattr=FS.checkOpExists(node.node_ops.setattr,63);setattr(node,{atime,mtime})},open(path,flags,mode=438){if(path===""){throw new FS.ErrnoError(44)}flags=FS_modeStringToFlags(flags);if(flags&64){mode=mode&4095|32768}else{mode=0}var node;var isDirPath;if(typeof path=="object"){node=path}else{isDirPath=path.endsWith("/");var lookup=FS.lookupPath(path,{follow:!(flags&131072),noent_okay:true});node=lookup.node;path=lookup.path}var created=false;if(flags&64){if(node){if(flags&128){throw new FS.ErrnoError(20)}}else if(isDirPath){throw new FS.ErrnoError(31)}else{node=FS.mknod(path,mode|511,0);created=true}}if(!node){throw new FS.ErrnoError(44)}if(FS.isChrdev(node.mode)){flags&=~512}if(flags&65536&&!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}if(!created){var errCode=FS.mayOpen(node,flags);if(errCode){throw new FS.ErrnoError(errCode)}}if(flags&512&&!created){FS.truncate(node,0)}flags&=~(128|512|131072);var stream=FS.createStream({node,path:FS.getPath(node),flags,seekable:true,position:0,stream_ops:node.stream_ops,ungotten:[],error:false});if(stream.stream_ops.open){stream.stream_ops.open(stream)}if(created){FS.chmod(node,mode&511)}return stream},close(stream){if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(stream.getdents)stream.getdents=null;try{if(stream.stream_ops.close){stream.stream_ops.close(stream)}}catch(e){throw e}finally{FS.closeStream(stream.fd)}stream.fd=null},isClosed(stream){return stream.fd===null},llseek(stream,offset,whence){if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(!stream.seekable||!stream.stream_ops.llseek){throw new FS.ErrnoError(70)}if(whence!=0&&whence!=1&&whence!=2){throw new FS.ErrnoError(28)}stream.position=stream.stream_ops.llseek(stream,offset,whence);stream.ungotten=[];return stream.position},read(stream,buffer,offset,length,position){if(length<0||position<0){throw new FS.ErrnoError(28)}if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if((stream.flags&2097155)===1){throw new FS.ErrnoError(8)}if(FS.isDir(stream.node.mode)){throw new FS.ErrnoError(31)}if(!stream.stream_ops.read){throw new FS.ErrnoError(28)}var seeking=typeof position!="undefined";if(!seeking){position=stream.position}else if(!stream.seekable){throw new FS.ErrnoError(70)}var bytesRead=stream.stream_ops.read(stream,buffer,offset,length,position);if(!seeking)stream.position+=bytesRead;return bytesRead},write(stream,buffer,offset,length,position,canOwn){if(length<0||position<0){throw new FS.ErrnoError(28)}if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if((stream.flags&2097155)===0){throw new FS.ErrnoError(8)}if(FS.isDir(stream.node.mode)){throw new FS.ErrnoError(31)}if(!stream.stream_ops.write){throw new FS.ErrnoError(28)}if(stream.seekable&&stream.flags&1024){FS.llseek(stream,0,2)}var seeking=typeof position!="undefined";if(!seeking){position=stream.position}else if(!stream.seekable){throw new FS.ErrnoError(70)}var bytesWritten=stream.stream_ops.write(stream,buffer,offset,length,position,canOwn);if(!seeking)stream.position+=bytesWritten;return bytesWritten},mmap(stream,length,position,prot,flags){if((prot&2)!==0&&(flags&2)===0&&(stream.flags&2097155)!==2){throw new FS.ErrnoError(2)}if((stream.flags&2097155)===1){throw new FS.ErrnoError(2)}if(!stream.stream_ops.mmap){throw new FS.ErrnoError(43)}if(!length){throw new FS.ErrnoError(28)}return stream.stream_ops.mmap(stream,length,position,prot,flags)},msync(stream,buffer,offset,length,mmapFlags){if(!stream.stream_ops.msync){return 0}return stream.stream_ops.msync(stream,buffer,offset,length,mmapFlags)},ioctl(stream,cmd,arg){if(!stream.stream_ops.ioctl){throw new FS.ErrnoError(59)}return stream.stream_ops.ioctl(stream,cmd,arg)},readFile(path,opts={}){opts.flags=opts.flags||0;opts.encoding=opts.encoding||"binary";if(opts.encoding!=="utf8"&&opts.encoding!=="binary"){abort(`Invalid encoding type "${opts.encoding}"`)}var stream=FS.open(path,opts.flags);var stat=FS.stat(path);var length=stat.size;var buf=new Uint8Array(length);FS.read(stream,buf,0,length,0);if(opts.encoding==="utf8"){buf=UTF8ArrayToString(buf)}FS.close(stream);return buf},writeFile(path,data,opts={}){opts.flags=opts.flags||577;var stream=FS.open(path,opts.flags,opts.mode);data=FS_fileDataToTypedArray(data);FS.write(stream,data,0,data.byteLength,undefined,opts.canOwn);FS.close(stream)},cwd:()=>FS.currentPath,chdir(path){var lookup=FS.lookupPath(path,{follow:true});if(lookup.node===null){throw new FS.ErrnoError(44)}if(!FS.isDir(lookup.node.mode)){throw new FS.ErrnoError(54)}var errCode=FS.nodePermissions(lookup.node,"x");if(errCode){throw new FS.ErrnoError(errCode)}FS.currentPath=lookup.path},createDefaultDirectories(){FS.mkdir("/tmp");FS.mkdir("/home");FS.mkdir("/home/web_user")},createDefaultDevices(){FS.mkdir("/dev");FS.registerDevice(FS.makedev(1,3),{read:()=>0,write:(stream,buffer,offset,length,pos)=>length,llseek:()=>0});FS.mkdev("/dev/null",FS.makedev(1,3));TTY.register(FS.makedev(5,0),TTY.default_tty_ops);TTY.register(FS.makedev(6,0),TTY.default_tty1_ops);FS.mkdev("/dev/tty",FS.makedev(5,0));FS.mkdev("/dev/tty1",FS.makedev(6,0));var randomBuffer=new Uint8Array(1024),randomLeft=0;var randomByte=()=>{if(randomLeft===0){randomFill(randomBuffer);randomLeft=randomBuffer.byteLength}return randomBuffer[--randomLeft]};FS.createDevice("/dev","random",randomByte);FS.createDevice("/dev","urandom",randomByte);FS.mkdir("/dev/shm");FS.mkdir("/dev/shm/tmp")},createSpecialDirectories(){FS.mkdir("/proc");var proc_self=FS.mkdir("/proc/self");FS.mkdir("/proc/self/fd");FS.mount({mount(){var node=FS.createNode(proc_self,"fd",16895,73);node.stream_ops={llseek:MEMFS.stream_ops.llseek};node.node_ops={lookup(parent,name){var fd=+name;var stream=FS.getStreamChecked(fd);var ret={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>stream.path},id:fd+1};ret.parent=ret;return ret},readdir(){return Array.from(FS.streams.entries()).filter(([k,v])=>v).map(([k,v])=>k.toString())}};return node}},{},"/proc/self/fd")},createStandardStreams(input,output,error){if(input){FS.createDevice("/dev","stdin",input)}else{FS.symlink("/dev/tty","/dev/stdin")}if(output){FS.createDevice("/dev","stdout",null,output)}else{FS.symlink("/dev/tty","/dev/stdout")}if(error){FS.createDevice("/dev","stderr",null,error)}else{FS.symlink("/dev/tty1","/dev/stderr")}var stdin=FS.open("/dev/stdin",0);var stdout=FS.open("/dev/stdout",1);var stderr=FS.open("/dev/stderr",1)},staticInit(){FS.nameTable=new Array(4096);FS.mount(MEMFS,{},"/");FS.createDefaultDirectories();FS.createDefaultDevices();FS.createSpecialDirectories();FS.filesystems={MEMFS}},init(input,output,error){FS.initialized=true;input??=Module["stdin"];output??=Module["stdout"];error??=Module["stderr"];FS.createStandardStreams(input,output,error)},quit(){FS.initialized=false;for(var stream of FS.streams){if(stream){FS.close(stream)}}},findObject(path,dontResolveLastLink){var ret=FS.analyzePath(path,dontResolveLastLink);if(!ret.exists){return null}return ret.object},analyzePath(path,dontResolveLastLink){try{var lookup=FS.lookupPath(path,{follow:!dontResolveLastLink});path=lookup.path}catch(e){}var ret={isRoot:false,exists:false,error:0,name:null,path:null,object:null,parentExists:false,parentPath:null,parentObject:null};try{var lookup=FS.lookupPath(path,{parent:true});ret.parentExists=true;ret.parentPath=lookup.path;ret.parentObject=lookup.node;ret.name=PATH.basename(path);lookup=FS.lookupPath(path,{follow:!dontResolveLastLink});ret.exists=true;ret.path=lookup.path;ret.object=lookup.node;ret.name=lookup.node.name;ret.isRoot=lookup.path==="/"}catch(e){ret.error=e.errno}return ret},createPath(parent,path,canRead,canWrite){parent=typeof parent=="string"?parent:FS.getPath(parent);var parts=path.split("/").reverse();while(parts.length){var part=parts.pop();if(!part)continue;var current=PATH.join2(parent,part);try{FS.mkdir(current)}catch(e){if(e.errno!=20)throw e}parent=current}return current},createFile(parent,name,properties,canRead,canWrite){var path=PATH.join2(typeof parent=="string"?parent:FS.getPath(parent),name);var mode=FS_getMode(canRead,canWrite);return FS.create(path,mode)},createDataFile(parent,name,data,canRead,canWrite,canOwn){var path=name;if(parent){parent=typeof parent=="string"?parent:FS.getPath(parent);path=name?PATH.join2(parent,name):parent}var mode=FS_getMode(canRead,canWrite);var node=FS.create(path,mode);if(data){data=FS_fileDataToTypedArray(data);FS.chmod(node,mode|146);var stream=FS.open(node,577);FS.write(stream,data,0,data.length,0,canOwn);FS.close(stream);FS.chmod(node,mode)}},createDevice(parent,name,input,output){var path=PATH.join2(typeof parent=="string"?parent:FS.getPath(parent),name);var mode=FS_getMode(!!input,!!output);FS.createDevice.major??=64;var dev=FS.makedev(FS.createDevice.major++,0);FS.registerDevice(dev,{open(stream){stream.seekable=false},close(stream){if(output?.buffer?.length){output(10)}},read(stream,buffer,offset,length,pos){var bytesRead=0;for(var i=0;ithis.length-1||idx<0){return undefined}var chunkOffset=idx%this.chunkSize;var chunkNum=idx/this.chunkSize|0;return this.getter(chunkNum)[chunkOffset]}setDataGetter(getter){this.getter=getter}cacheLength(){var xhr=new XMLHttpRequest;xhr.open("HEAD",url,false);xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))abort("Couldn't load "+url+". Status: "+xhr.status);var datalength=Number(xhr.getResponseHeader("Content-length"));var header;var hasByteServing=(header=xhr.getResponseHeader("Accept-Ranges"))&&header==="bytes";var usesGzip=(header=xhr.getResponseHeader("Content-Encoding"))&&header==="gzip";var chunkSize=1024*1024;if(!hasByteServing)chunkSize=datalength;var doXHR=(from,to)=>{if(from>to)abort("invalid range ("+from+", "+to+") or no bytes requested!");if(to>datalength-1)abort("only "+datalength+" bytes available! programmer error!");var xhr=new XMLHttpRequest;xhr.open("GET",url,false);if(datalength!==chunkSize)xhr.setRequestHeader("Range","bytes="+from+"-"+to);xhr.responseType="arraybuffer";if(xhr.overrideMimeType){xhr.overrideMimeType("text/plain; charset=x-user-defined")}xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))abort("Couldn't load "+url+". Status: "+xhr.status);if(xhr.response!==undefined){return new Uint8Array(xhr.response||[])}return intArrayFromString(xhr.responseText||"",true)};var lazyArray=this;lazyArray.setDataGetter(chunkNum=>{var start=chunkNum*chunkSize;var end=(chunkNum+1)*chunkSize-1;end=Math.min(end,datalength-1);if(typeof lazyArray.chunks[chunkNum]=="undefined"){lazyArray.chunks[chunkNum]=doXHR(start,end)}if(typeof lazyArray.chunks[chunkNum]=="undefined")abort("doXHR failed!");return lazyArray.chunks[chunkNum]});if(usesGzip||!datalength){chunkSize=datalength=1;datalength=this.getter(0).length;chunkSize=datalength;out("LazyFiles on gzip forces download of the whole file when length is accessed")}this._length=datalength;this._chunkSize=chunkSize;this.lengthKnown=true}get length(){if(!this.lengthKnown){this.cacheLength()}return this._length}get chunkSize(){if(!this.lengthKnown){this.cacheLength()}return this._chunkSize}}if(globalThis.XMLHttpRequest){if(!ENVIRONMENT_IS_WORKER)abort("Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc");var lazyArray=new LazyUint8Array;var properties={isDevice:false,contents:lazyArray}}else{var properties={isDevice:false,url}}var node=FS.createFile(parent,name,properties,canRead,canWrite);if(properties.contents){node.contents=properties.contents}else if(properties.url){node.contents=null;node.url=properties.url}Object.defineProperties(node,{usedBytes:{get:function(){return this.contents.length}}});var stream_ops={};for(const[key,fn]of Object.entries(node.stream_ops)){stream_ops[key]=(...args)=>{FS.forceLoadFile(node);return fn(...args)}}function writeChunks(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=contents.length)return 0;var size=Math.min(contents.length-position,length);if(contents.slice){for(var i=0;i{FS.forceLoadFile(node);return writeChunks(stream,buffer,offset,length,position)};stream_ops.mmap=(stream,length,position,prot,flags)=>{FS.forceLoadFile(node);var ptr=mmapAlloc(length);if(!ptr){throw new FS.ErrnoError(48)}writeChunks(stream,HEAP8,ptr,length,position);return{ptr,allocated:true}};node.stream_ops=stream_ops;return node}};var UTF8ToString=(ptr,maxBytesToRead,ignoreNul)=>{ptr>>>=0;return ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead,ignoreNul):""};var SYSCALLS={calculateAt(dirfd,path,allowEmpty){if(PATH.isAbs(path)){return path}var dir;if(dirfd===-100){dir=FS.cwd()}else{var dirstream=SYSCALLS.getStreamFromFD(dirfd);dir=dirstream.path}if(path.length==0){if(!allowEmpty){throw new FS.ErrnoError(44)}return dir}return dir+"/"+path},writeStat(buf,stat){HEAPU32[buf>>>2>>>0]=stat.dev;HEAPU32[buf+4>>>2>>>0]=stat.mode;HEAPU32[buf+8>>>2>>>0]=stat.nlink;HEAPU32[buf+12>>>2>>>0]=stat.uid;HEAPU32[buf+16>>>2>>>0]=stat.gid;HEAPU32[buf+20>>>2>>>0]=stat.rdev;HEAP64[buf+24>>>3>>>0]=BigInt(stat.size);HEAP32[buf+32>>>2>>>0]=4096;HEAP32[buf+36>>>2>>>0]=stat.blocks;var atime=stat.atime.getTime();var mtime=stat.mtime.getTime();var ctime=stat.ctime.getTime();HEAP64[buf+40>>>3>>>0]=BigInt(Math.floor(atime/1e3));HEAPU32[buf+48>>>2>>>0]=atime%1e3*1e3*1e3;HEAP64[buf+56>>>3>>>0]=BigInt(Math.floor(mtime/1e3));HEAPU32[buf+64>>>2>>>0]=mtime%1e3*1e3*1e3;HEAP64[buf+72>>>3>>>0]=BigInt(Math.floor(ctime/1e3));HEAPU32[buf+80>>>2>>>0]=ctime%1e3*1e3*1e3;HEAP64[buf+88>>>3>>>0]=BigInt(stat.ino);return 0},writeStatFs(buf,stats){HEAPU32[buf+4>>>2>>>0]=stats.bsize;HEAPU32[buf+60>>>2>>>0]=stats.bsize;HEAP64[buf+8>>>3>>>0]=BigInt(stats.blocks);HEAP64[buf+16>>>3>>>0]=BigInt(stats.bfree);HEAP64[buf+24>>>3>>>0]=BigInt(stats.bavail);HEAP64[buf+32>>>3>>>0]=BigInt(stats.files);HEAP64[buf+40>>>3>>>0]=BigInt(stats.ffree);HEAPU32[buf+48>>>2>>>0]=stats.fsid;HEAPU32[buf+64>>>2>>>0]=stats.flags;HEAPU32[buf+56>>>2>>>0]=stats.namelen},doMsync(addr,stream,len,flags,offset){if(!FS.isFile(stream.node.mode)){throw new FS.ErrnoError(43)}if(flags&2){return 0}var buffer=HEAPU8.slice(addr,addr+len);FS.msync(stream,buffer,offset,len,flags)},getStreamFromFD(fd){var stream=FS.getStreamChecked(fd);return stream},varargs:undefined,getStr(ptr){var ret=UTF8ToString(ptr);return ret}};function ___syscall_chmod(path,mode){path>>>=0;try{path=SYSCALLS.getStr(path);FS.chmod(path,mode);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_faccessat(dirfd,path,amode,flags){path>>>=0;try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);if(amode&~7){return-28}var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;if(!node){return-44}var perms="";if(amode&4)perms+="r";if(amode&2)perms+="w";if(amode&1)perms+="x";if(perms&&FS.nodePermissions(node,perms)){return-2}return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var syscallGetVarargI=()=>{var ret=HEAP32[+SYSCALLS.varargs>>>2>>>0];SYSCALLS.varargs+=4;return ret};var syscallGetVarargP=syscallGetVarargI;function ___syscall_fcntl64(fd,cmd,varargs){varargs>>>=0;SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(cmd){case 0:{var arg=syscallGetVarargI();if(arg<0){return-28}while(FS.streams[arg]){arg++}var newStream;newStream=FS.dupStream(stream,arg);return newStream.fd}case 1:case 2:return 0;case 3:return stream.flags;case 4:{var arg=syscallGetVarargI();stream.flags|=arg;return 0}case 12:{var arg=syscallGetVarargP();var offset=0;HEAP16[arg+offset>>>1>>>0]=2;return 0}case 13:case 14:return 0}return-28}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_fstat64(fd,buf){buf>>>=0;try{return SYSCALLS.writeStat(buf,FS.fstat(fd))}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var stringToUTF8=(str,outPtr,maxBytesToWrite)=>stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite);function ___syscall_getdents64(fd,dirp,count){dirp>>>=0;count>>>=0;try{var stream=SYSCALLS.getStreamFromFD(fd);stream.getdents||=FS.readdir(stream.path);var struct_size=280;var pos=0;var off=FS.llseek(stream,0,1);var startIdx=Math.floor(off/struct_size);var endIdx=Math.min(stream.getdents.length,startIdx+Math.floor(count/struct_size));for(var idx=startIdx;idx>>3>>>0]=BigInt(id);HEAP64[dirp+pos+8>>>3>>>0]=BigInt((idx+1)*struct_size);HEAP16[dirp+pos+16>>>1>>>0]=280;HEAP8[dirp+pos+18>>>0]=type;stringToUTF8(name,dirp+pos+19,256);pos+=struct_size}FS.llseek(stream,idx*struct_size,0);return pos}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_ioctl(fd,op,varargs){varargs>>>=0;SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(op){case 21509:{if(!stream.tty)return-59;return 0}case 21505:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tcgets){var termios=stream.tty.ops.ioctl_tcgets(stream);var argp=syscallGetVarargP();HEAP32[argp>>>2>>>0]=termios.c_iflag||0;HEAP32[argp+4>>>2>>>0]=termios.c_oflag||0;HEAP32[argp+8>>>2>>>0]=termios.c_cflag||0;HEAP32[argp+12>>>2>>>0]=termios.c_lflag||0;for(var i=0;i<32;i++){HEAP8[argp+i+17>>>0]=termios.c_cc[i]||0}return 0}return 0}case 21510:case 21511:case 21512:{if(!stream.tty)return-59;return 0}case 21506:case 21507:case 21508:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tcsets){var argp=syscallGetVarargP();var c_iflag=HEAP32[argp>>>2>>>0];var c_oflag=HEAP32[argp+4>>>2>>>0];var c_cflag=HEAP32[argp+8>>>2>>>0];var c_lflag=HEAP32[argp+12>>>2>>>0];var c_cc=[];for(var i=0;i<32;i++){c_cc.push(HEAP8[argp+i+17>>>0])}return stream.tty.ops.ioctl_tcsets(stream.tty,op,{c_iflag,c_oflag,c_cflag,c_lflag,c_cc})}return 0}case 21519:{if(!stream.tty)return-59;var argp=syscallGetVarargP();HEAP32[argp>>>2>>>0]=0;return 0}case 21520:{if(!stream.tty)return-59;return-28}case 21537:case 21531:{var argp=syscallGetVarargP();return FS.ioctl(stream,op,argp)}case 21523:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tiocgwinsz){var winsize=stream.tty.ops.ioctl_tiocgwinsz(stream.tty);var argp=syscallGetVarargP();HEAP16[argp>>>1>>>0]=winsize[0];HEAP16[argp+2>>>1>>>0]=winsize[1]}return 0}case 21524:{if(!stream.tty)return-59;return 0}case 21515:{if(!stream.tty)return-59;return 0}default:return-28}}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_lstat64(path,buf){path>>>=0;buf>>>=0;try{path=SYSCALLS.getStr(path);return SYSCALLS.writeStat(buf,FS.lstat(path))}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_mkdirat(dirfd,path,mode){path>>>=0;try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);FS.mkdir(path,mode,0);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_newfstatat(dirfd,path,buf,flags){path>>>=0;buf>>>=0;try{path=SYSCALLS.getStr(path);var nofollow=flags&256;var allowEmpty=flags&4096;flags=flags&~6400;path=SYSCALLS.calculateAt(dirfd,path,allowEmpty);return SYSCALLS.writeStat(buf,nofollow?FS.lstat(path):FS.stat(path))}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_openat(dirfd,path,flags,varargs){path>>>=0;varargs>>>=0;SYSCALLS.varargs=varargs;try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);var mode=varargs?syscallGetVarargI():0;return FS.open(path,flags,mode).fd}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_rmdir(path){path>>>=0;try{path=SYSCALLS.getStr(path);FS.rmdir(path);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_stat64(path,buf){path>>>=0;buf>>>=0;try{path=SYSCALLS.getStr(path);return SYSCALLS.writeStat(buf,FS.stat(path))}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_unlinkat(dirfd,path,flags){path>>>=0;try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);if(!flags){FS.unlink(path)}else if(flags===512){FS.rmdir(path)}else{return-28}return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var __abort_js=()=>abort("");var structRegistrations={};var runDestructors=destructors=>{while(destructors.length){var ptr=destructors.pop();var del=destructors.pop();del(ptr)}};function readPointer(pointer){return this.fromWireType(HEAPU32[pointer>>>2>>>0])}var awaitingDependencies={};var registeredTypes={};var typeDependencies={};var InternalError=class InternalError extends Error{constructor(message){super(message);this.name="InternalError"}};var throwInternalError=message=>{throw new InternalError(message)};var whenDependentTypesAreResolved=(myTypes,dependentTypes,getTypeConverters)=>{myTypes.forEach(type=>typeDependencies[type]=dependentTypes);function onComplete(typeConverters){var myTypeConverters=getTypeConverters(typeConverters);if(myTypeConverters.length!==myTypes.length){throwInternalError("Mismatched type converter count")}for(var i=0;i{typeConverters[i]=registeredTypes[dt];++registered;if(registered===unregisteredTypes.length){onComplete(typeConverters)}})}}if(0===unregisteredTypes.length){onComplete(typeConverters)}};var __embind_finalize_value_object=function(structType){structType>>>=0;var reg=structRegistrations[structType];delete structRegistrations[structType];var rawConstructor=reg.rawConstructor;var rawDestructor=reg.rawDestructor;var fieldRecords=reg.fields;var fieldTypes=fieldRecords.map(field=>field.getterReturnType).concat(fieldRecords.map(field=>field.setterArgumentType));whenDependentTypesAreResolved([structType],fieldTypes,fieldTypes=>{var fields={};for(var[i,field]of fieldRecords.entries()){const getterReturnType=fieldTypes[i];const getter=field.getter;const getterContext=field.getterContext;const setterArgumentType=fieldTypes[i+fieldRecords.length];const setter=field.setter;const setterContext=field.setterContext;fields[field.fieldName]={read:ptr=>getterReturnType.fromWireType(getter(getterContext,ptr)),write:(ptr,o)=>{var destructors=[];setter(setterContext,ptr,setterArgumentType.toWireType(destructors,o));runDestructors(destructors)},optional:getterReturnType.optional}}return[{name:reg.name,fromWireType:ptr=>{var rv={};for(var i in fields){rv[i]=fields[i].read(ptr)}rawDestructor(ptr);return rv},toWireType:(destructors,o)=>{for(var fieldName in fields){if(!(fieldName in o)&&!fields[fieldName].optional){throw new TypeError(`Missing field: "${fieldName}"`)}}var ptr=rawConstructor();for(fieldName in fields){fields[fieldName].write(ptr,o[fieldName])}if(destructors!==null){destructors.push(rawDestructor,ptr)}return ptr},readValueFromPointer:readPointer,destructorFunction:rawDestructor}]})};var AsciiToString=ptr=>{ptr>>>=0;var str="";while(1){var ch=HEAPU8[ptr++>>>0];if(!ch)return str;str+=String.fromCharCode(ch)}};var BindingError=class BindingError extends Error{constructor(message){super(message);this.name="BindingError"}};var throwBindingError=message=>{throw new BindingError(message)};function sharedRegisterType(rawType,registeredInstance,options={}){var name=registeredInstance.name;if(!rawType){throwBindingError(`type "${name}" must have a positive integer typeid pointer`)}if(registeredTypes.hasOwnProperty(rawType)){if(options.ignoreDuplicateRegistrations){return}else{throwBindingError(`Cannot register type '${name}' twice`)}}registeredTypes[rawType]=registeredInstance;delete typeDependencies[rawType];if(awaitingDependencies.hasOwnProperty(rawType)){var callbacks=awaitingDependencies[rawType];delete awaitingDependencies[rawType];callbacks.forEach(cb=>cb())}}function registerType(rawType,registeredInstance,options={}){return sharedRegisterType(rawType,registeredInstance,options)}var integerReadValueFromPointer=(name,width,signed)=>{switch(width){case 1:return signed?pointer=>HEAP8[pointer>>>0]:pointer=>HEAPU8[pointer>>>0];case 2:return signed?pointer=>HEAP16[pointer>>>1>>>0]:pointer=>HEAPU16[pointer>>>1>>>0];case 4:return signed?pointer=>HEAP32[pointer>>>2>>>0]:pointer=>HEAPU32[pointer>>>2>>>0];case 8:return signed?pointer=>HEAP64[pointer>>>3>>>0]:pointer=>HEAPU64[pointer>>>3>>>0];default:throw new TypeError(`invalid integer width (${width}): ${name}`)}};var __embind_register_bigint=function(primitiveType,name,size,minRange,maxRange){primitiveType>>>=0;name>>>=0;size>>>=0;name=AsciiToString(name);const isUnsignedType=minRange===0n;let fromWireType=value=>value;if(isUnsignedType){const bitSize=size*8;fromWireType=value=>BigInt.asUintN(bitSize,value);maxRange=fromWireType(maxRange)}registerType(primitiveType,{name,fromWireType,toWireType:(destructors,value)=>{if(typeof value=="number"){value=BigInt(value)}return value},readValueFromPointer:integerReadValueFromPointer(name,size,!isUnsignedType),destructorFunction:null})};function __embind_register_bool(rawType,name,trueValue,falseValue){rawType>>>=0;name>>>=0;name=AsciiToString(name);registerType(rawType,{name,fromWireType:function(wt){return!!wt},toWireType:function(destructors,o){return o?trueValue:falseValue},readValueFromPointer:function(pointer){return this.fromWireType(HEAPU8[pointer>>>0])},destructorFunction:null})}var shallowCopyInternalPointer=o=>({count:o.count,deleteScheduled:o.deleteScheduled,preservePointerOnDelete:o.preservePointerOnDelete,ptr:o.ptr,ptrType:o.ptrType,smartPtr:o.smartPtr,smartPtrType:o.smartPtrType});var throwInstanceAlreadyDeleted=obj=>{function getInstanceTypeName(handle){return handle.$$.ptrType.registeredClass.name}throwBindingError(getInstanceTypeName(obj)+" instance already deleted")};var finalizationRegistry=false;var detachFinalizer=handle=>{};var runDestructor=$$=>{if($$.smartPtr){$$.smartPtrType.rawDestructor($$.smartPtr)}else{$$.ptrType.registeredClass.rawDestructor($$.ptr)}};var releaseClassHandle=$$=>{$$.count.value-=1;var toDelete=0===$$.count.value;if(toDelete){runDestructor($$)}};var attachFinalizer=handle=>{if(!globalThis.FinalizationRegistry){attachFinalizer=handle=>handle;return handle}finalizationRegistry=new FinalizationRegistry(info=>{releaseClassHandle(info.$$)});attachFinalizer=handle=>{var $$=handle.$$;var hasSmartPtr=!!$$.smartPtr;if(hasSmartPtr){var info={$$};finalizationRegistry.register(handle,info,handle)}return handle};detachFinalizer=handle=>finalizationRegistry.unregister(handle);return attachFinalizer(handle)};var deletionQueue=[];var flushPendingDeletes=()=>{while(deletionQueue.length){var obj=deletionQueue.pop();obj.$$.deleteScheduled=false;obj["delete"]()}};var delayFunction;var init_ClassHandle=()=>{let proto=ClassHandle.prototype;Object.assign(proto,{isAliasOf(other){if(!(this instanceof ClassHandle)){return false}if(!(other instanceof ClassHandle)){return false}var leftClass=this.$$.ptrType.registeredClass;var left=this.$$.ptr;other.$$=other.$$;var rightClass=other.$$.ptrType.registeredClass;var right=other.$$.ptr;while(leftClass.baseClass){left=leftClass.upcast(left);leftClass=leftClass.baseClass}while(rightClass.baseClass){right=rightClass.upcast(right);rightClass=rightClass.baseClass}return leftClass===rightClass&&left===right},clone(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.preservePointerOnDelete){this.$$.count.value+=1;return this}else{var clone=attachFinalizer(Object.create(Object.getPrototypeOf(this),{$$:{value:shallowCopyInternalPointer(this.$$)}}));clone.$$.count.value+=1;clone.$$.deleteScheduled=false;return clone}},delete(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete){throwBindingError("Object already scheduled for deletion")}detachFinalizer(this);releaseClassHandle(this.$$);if(!this.$$.preservePointerOnDelete){this.$$.smartPtr=undefined;this.$$.ptr=undefined}},isDeleted(){return!this.$$.ptr},deleteLater(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete){throwBindingError("Object already scheduled for deletion")}deletionQueue.push(this);if(deletionQueue.length===1&&delayFunction){delayFunction(flushPendingDeletes)}this.$$.deleteScheduled=true;return this}});const symbolDispose=Symbol.dispose;if(symbolDispose){proto[symbolDispose]=proto["delete"]}};function ClassHandle(){}var createNamedFunction=(name,func)=>Object.defineProperty(func,"name",{value:name});var registeredPointers={};var ensureOverloadTable=(proto,methodName,humanName)=>{if(undefined===proto[methodName].overloadTable){var prevFunc=proto[methodName];proto[methodName]=function(...args){if(!proto[methodName].overloadTable.hasOwnProperty(args.length)){throwBindingError(`Function '${humanName}' called with an invalid number of arguments (${args.length}) - expects one of (${proto[methodName].overloadTable})!`)}return proto[methodName].overloadTable[args.length].apply(this,args)};proto[methodName].overloadTable=[];proto[methodName].overloadTable[prevFunc.argCount]=prevFunc}};var exposePublicSymbol=(name,value,numArguments)=>{if(Module.hasOwnProperty(name)){if(undefined===numArguments||undefined!==Module[name].overloadTable&&undefined!==Module[name].overloadTable[numArguments]){throwBindingError(`Cannot register public name '${name}' twice`)}ensureOverloadTable(Module,name,name);if(Module[name].overloadTable.hasOwnProperty(numArguments)){throwBindingError(`Cannot register multiple overloads of a function with the same number of arguments (${numArguments})!`)}Module[name].overloadTable[numArguments]=value}else{Module[name]=value;Module[name].argCount=numArguments}};var char_0=48;var char_9=57;var makeLegalFunctionName=name=>{name=name.replace(/[^a-zA-Z0-9_]/g,"$");var f=name.charCodeAt(0);if(f>=char_0&&f<=char_9){return`_${name}`}return name};function RegisteredClass(name,constructor,instancePrototype,rawDestructor,baseClass,getActualType,upcast,downcast){this.name=name;this.constructor=constructor;this.instancePrototype=instancePrototype;this.rawDestructor=rawDestructor;this.baseClass=baseClass;this.getActualType=getActualType;this.upcast=upcast;this.downcast=downcast;this.pureVirtualFunctions=[]}var upcastPointer=(ptr,ptrClass,desiredClass)=>{while(ptrClass!==desiredClass){if(!ptrClass.upcast){throwBindingError(`Expected null or instance of ${desiredClass.name}, got an instance of ${ptrClass.name}`)}ptr=ptrClass.upcast(ptr);ptrClass=ptrClass.baseClass}return ptr};var embindRepr=v=>{if(v===null){return"null"}var t=typeof v;if(t==="object"||t==="array"||t==="function"){return v.toString()}else{return""+v}};function constNoSmartPtrRawPointerToWireType(destructors,handle){if(handle===null){if(this.isReference){throwBindingError(`null is not a valid ${this.name}`)}return 0}if(!handle.$$){throwBindingError(`Cannot pass "${embindRepr(handle)}" as a ${this.name}`)}if(!handle.$$.ptr){throwBindingError(`Cannot pass deleted object as a pointer of type ${this.name}`)}var handleClass=handle.$$.ptrType.registeredClass;var ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);return ptr}function genericPointerToWireType(destructors,handle){var ptr;if(handle===null){if(this.isReference){throwBindingError(`null is not a valid ${this.name}`)}if(this.isSmartPointer){ptr=this.rawConstructor();if(destructors!==null){destructors.push(this.rawDestructor,ptr)}return ptr}else{return 0}}if(!handle||!handle.$$){throwBindingError(`Cannot pass "${embindRepr(handle)}" as a ${this.name}`)}if(!handle.$$.ptr){throwBindingError(`Cannot pass deleted object as a pointer of type ${this.name}`)}if(!this.isConst&&handle.$$.ptrType.isConst){throwBindingError(`Cannot convert argument of type ${handle.$$.smartPtrType?handle.$$.smartPtrType.name:handle.$$.ptrType.name} to parameter type ${this.name}`)}var handleClass=handle.$$.ptrType.registeredClass;ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);if(this.isSmartPointer){if(undefined===handle.$$.smartPtr){throwBindingError("Passing raw pointer to smart pointer is illegal")}switch(this.sharingPolicy){case 0:if(handle.$$.smartPtrType===this){ptr=handle.$$.smartPtr}else{throwBindingError(`Cannot convert argument of type ${handle.$$.smartPtrType?handle.$$.smartPtrType.name:handle.$$.ptrType.name} to parameter type ${this.name}`)}break;case 1:ptr=handle.$$.smartPtr;break;case 2:if(handle.$$.smartPtrType===this){ptr=handle.$$.smartPtr}else{var clonedHandle=handle["clone"]();ptr=this.rawShare(ptr,Emval.toHandle(()=>clonedHandle["delete"]()));if(destructors!==null){destructors.push(this.rawDestructor,ptr)}}break;default:throwBindingError("Unsupported sharing policy")}}return ptr}function nonConstNoSmartPtrRawPointerToWireType(destructors,handle){if(handle===null){if(this.isReference){throwBindingError(`null is not a valid ${this.name}`)}return 0}if(!handle.$$){throwBindingError(`Cannot pass "${embindRepr(handle)}" as a ${this.name}`)}if(!handle.$$.ptr){throwBindingError(`Cannot pass deleted object as a pointer of type ${this.name}`)}if(handle.$$.ptrType.isConst){throwBindingError(`Cannot convert argument of type ${handle.$$.ptrType.name} to parameter type ${this.name}`)}var handleClass=handle.$$.ptrType.registeredClass;var ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);return ptr}var downcastPointer=(ptr,ptrClass,desiredClass)=>{if(ptrClass===desiredClass){return ptr}if(undefined===desiredClass.baseClass){return null}var rv=downcastPointer(ptr,ptrClass,desiredClass.baseClass);if(rv===null){return null}return desiredClass.downcast(rv)};var registeredInstances={};var getBasestPointer=(class_,ptr)=>{if(ptr===undefined){throwBindingError("ptr should not be undefined")}while(class_.baseClass){ptr=class_.upcast(ptr);class_=class_.baseClass}return ptr};var getInheritedInstance=(class_,ptr)=>{ptr=getBasestPointer(class_,ptr);return registeredInstances[ptr]};var makeClassHandle=(prototype,record)=>{if(!record.ptrType||!record.ptr){throwInternalError("makeClassHandle requires ptr and ptrType")}var hasSmartPtrType=!!record.smartPtrType;var hasSmartPtr=!!record.smartPtr;if(hasSmartPtrType!==hasSmartPtr){throwInternalError("Both smartPtrType and smartPtr must be specified")}record.count={value:1};return attachFinalizer(Object.create(prototype,{$$:{value:record,writable:true}}))};function RegisteredPointer_fromWireType(ptr){var rawPointer=this.getPointee(ptr);if(!rawPointer){this.destructor(ptr);return null}var registeredInstance=getInheritedInstance(this.registeredClass,rawPointer);if(undefined!==registeredInstance){if(0===registeredInstance.$$.count.value){registeredInstance.$$.ptr=rawPointer;registeredInstance.$$.smartPtr=ptr;return registeredInstance["clone"]()}else{var rv=registeredInstance["clone"]();this.destructor(ptr);return rv}}function makeDefaultHandle(){if(this.isSmartPointer){return makeClassHandle(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:rawPointer,smartPtrType:this,smartPtr:ptr})}else{return makeClassHandle(this.registeredClass.instancePrototype,{ptrType:this,ptr})}}var actualType=this.registeredClass.getActualType(rawPointer);var registeredPointerRecord=registeredPointers[actualType];if(!registeredPointerRecord){return makeDefaultHandle.call(this)}var toType;if(this.isConst){toType=registeredPointerRecord.constPointerType}else{toType=registeredPointerRecord.pointerType}var dp=downcastPointer(rawPointer,this.registeredClass,toType.registeredClass);if(dp===null){return makeDefaultHandle.call(this)}if(this.isSmartPointer){return makeClassHandle(toType.registeredClass.instancePrototype,{ptrType:toType,ptr:dp,smartPtrType:this,smartPtr:ptr})}else{return makeClassHandle(toType.registeredClass.instancePrototype,{ptrType:toType,ptr:dp})}}var init_RegisteredPointer=()=>{Object.assign(RegisteredPointer.prototype,{getPointee(ptr){if(this.rawGetPointee){ptr=this.rawGetPointee(ptr)}return ptr},destructor(ptr){this.rawDestructor?.(ptr)},readValueFromPointer:readPointer,fromWireType:RegisteredPointer_fromWireType})};function RegisteredPointer(name,registeredClass,isReference,isConst,isSmartPointer,pointeeType,sharingPolicy,rawGetPointee,rawConstructor,rawShare,rawDestructor){this.name=name;this.registeredClass=registeredClass;this.isReference=isReference;this.isConst=isConst;this.isSmartPointer=isSmartPointer;this.pointeeType=pointeeType;this.sharingPolicy=sharingPolicy;this.rawGetPointee=rawGetPointee;this.rawConstructor=rawConstructor;this.rawShare=rawShare;this.rawDestructor=rawDestructor;if(!isSmartPointer&®isteredClass.baseClass===undefined){if(isConst){this.toWireType=constNoSmartPtrRawPointerToWireType;this.destructorFunction=null}else{this.toWireType=nonConstNoSmartPtrRawPointerToWireType;this.destructorFunction=null}}else{this.toWireType=genericPointerToWireType}}var replacePublicSymbol=(name,value,numArguments)=>{if(!Module.hasOwnProperty(name)){throwInternalError("Replacing nonexistent public symbol")}if(undefined!==Module[name].overloadTable&&undefined!==numArguments){Module[name].overloadTable[numArguments]=value}else{Module[name]=value;Module[name].argCount=numArguments}};var dynCall=(sig,ptr,args=[],promising=false)=>{var func=getWasmTableEntry(ptr);var rtn=func(...args);function convert(rtn){return sig[0]=="p"?rtn>>>0:rtn}return convert(rtn)};var getDynCaller=(sig,ptr,promising=false)=>(...args)=>dynCall(sig,ptr,args,promising);var embind__requireFunction=(signature,rawFunction,isAsync=false)=>{signature=AsciiToString(signature);function makeDynCaller(){if(signature.includes("p")){return getDynCaller(signature,rawFunction,isAsync)}var rtn=getWasmTableEntry(rawFunction);return rtn}var fp=makeDynCaller();if(typeof fp!="function"){throwBindingError(`unknown function pointer with signature ${signature}: ${rawFunction}`)}return fp};class UnboundTypeError extends Error{}var getTypeName=type=>{var ptr=___getTypeName(type);var rv=AsciiToString(ptr);_free(ptr);return rv};var throwUnboundTypeError=(message,types)=>{var unboundTypes=[];var seen={};function visit(type){if(seen[type]){return}if(registeredTypes[type]){return}if(typeDependencies[type]){typeDependencies[type].forEach(visit);return}unboundTypes.push(type);seen[type]=true}types.forEach(visit);throw new UnboundTypeError(`${message}: `+unboundTypes.map(getTypeName).join([", "]))};function __embind_register_class(rawType,rawPointerType,rawConstPointerType,baseClassRawType,getActualTypeSignature,getActualType,upcastSignature,upcast,downcastSignature,downcast,name,destructorSignature,rawDestructor){rawType>>>=0;rawPointerType>>>=0;rawConstPointerType>>>=0;baseClassRawType>>>=0;getActualTypeSignature>>>=0;getActualType>>>=0;upcastSignature>>>=0;upcast>>>=0;downcastSignature>>>=0;downcast>>>=0;name>>>=0;destructorSignature>>>=0;rawDestructor>>>=0;name=AsciiToString(name);getActualType=embind__requireFunction(getActualTypeSignature,getActualType);upcast&&=embind__requireFunction(upcastSignature,upcast);downcast&&=embind__requireFunction(downcastSignature,downcast);rawDestructor=embind__requireFunction(destructorSignature,rawDestructor);var legalFunctionName=makeLegalFunctionName(name);exposePublicSymbol(legalFunctionName,function(){throwUnboundTypeError(`Cannot construct ${name} due to unbound types`,[baseClassRawType])});whenDependentTypesAreResolved([rawType,rawPointerType,rawConstPointerType],baseClassRawType?[baseClassRawType]:[],base=>{base=base[0];var baseClass;var basePrototype;if(baseClassRawType){baseClass=base.registeredClass;basePrototype=baseClass.instancePrototype}else{basePrototype=ClassHandle.prototype}var constructor=createNamedFunction(name,function(...args){if(Object.getPrototypeOf(this)!==instancePrototype){throw new BindingError(`Use 'new' to construct ${name}`)}if(undefined===registeredClass.constructor_body){throw new BindingError(`${name} has no accessible constructor`)}var body=registeredClass.constructor_body[args.length];if(undefined===body){throw new BindingError(`Tried to invoke ctor of ${name} with invalid number of parameters (${args.length}) - expected (${Object.keys(registeredClass.constructor_body).toString()}) parameters instead!`)}return body.apply(this,args)});var instancePrototype=Object.create(basePrototype,{constructor:{value:constructor}});constructor.prototype=instancePrototype;var registeredClass=new RegisteredClass(name,constructor,instancePrototype,rawDestructor,baseClass,getActualType,upcast,downcast);if(registeredClass.baseClass){registeredClass.baseClass.__derivedClasses??=[];registeredClass.baseClass.__derivedClasses.push(registeredClass)}var referenceConverter=new RegisteredPointer(name,registeredClass,true,false,false);var pointerConverter=new RegisteredPointer(name+"*",registeredClass,false,false,false);var constPointerConverter=new RegisteredPointer(name+" const*",registeredClass,false,true,false);registeredPointers[rawType]={pointerType:pointerConverter,constPointerType:constPointerConverter};replacePublicSymbol(legalFunctionName,constructor);return[referenceConverter,pointerConverter,constPointerConverter]})}var heap32VectorToArray=(count,firstElement)=>{var array=[];for(var i=0;i>>2>>>0])}return array};function usesDestructorStack(argTypes){for(var i=1;i>>=0;rawArgTypesAddr>>>=0;invokerSignature>>>=0;invoker>>>=0;rawConstructor>>>=0;var rawArgTypes=heap32VectorToArray(argCount,rawArgTypesAddr);invoker=embind__requireFunction(invokerSignature,invoker);whenDependentTypesAreResolved([],[rawClassType],classType=>{classType=classType[0];var humanName=`constructor ${classType.name}`;if(undefined===classType.registeredClass.constructor_body){classType.registeredClass.constructor_body=[]}if(undefined!==classType.registeredClass.constructor_body[argCount-1]){throw new BindingError(`Cannot register multiple constructors with identical number of parameters (${argCount-1}) for class '${classType.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`)}classType.registeredClass.constructor_body[argCount-1]=()=>{throwUnboundTypeError(`Cannot construct ${classType.name} due to unbound types`,rawArgTypes)};whenDependentTypesAreResolved([],rawArgTypes,argTypes=>{argTypes.splice(1,0,null);classType.registeredClass.constructor_body[argCount-1]=craftInvokerFunction(humanName,argTypes,null,invoker,rawConstructor);return[]});return[]})};var getFunctionName=signature=>{signature=signature.trim();const argsIndex=signature.indexOf("(");if(argsIndex===-1)return signature;return signature.slice(0,argsIndex)};var __embind_register_class_function=function(rawClassType,methodName,argCount,rawArgTypesAddr,invokerSignature,rawInvoker,context,isPureVirtual,isAsync,isNonnullReturn){rawClassType>>>=0;methodName>>>=0;rawArgTypesAddr>>>=0;invokerSignature>>>=0;rawInvoker>>>=0;context>>>=0;var rawArgTypes=heap32VectorToArray(argCount,rawArgTypesAddr);methodName=AsciiToString(methodName);methodName=getFunctionName(methodName);rawInvoker=embind__requireFunction(invokerSignature,rawInvoker,isAsync);whenDependentTypesAreResolved([],[rawClassType],classType=>{classType=classType[0];var humanName=`${classType.name}.${methodName}`;if(methodName.startsWith("@@")){methodName=Symbol[methodName.substring(2)]}if(isPureVirtual){classType.registeredClass.pureVirtualFunctions.push(methodName)}function unboundTypesHandler(){throwUnboundTypeError(`Cannot call ${humanName} due to unbound types`,rawArgTypes)}var proto=classType.registeredClass.instancePrototype;var method=proto[methodName];if(undefined===method||undefined===method.overloadTable&&method.className!==classType.name&&method.argCount===argCount-2){unboundTypesHandler.argCount=argCount-2;unboundTypesHandler.className=classType.name;proto[methodName]=unboundTypesHandler}else{ensureOverloadTable(proto,methodName,humanName);proto[methodName].overloadTable[argCount-2]=unboundTypesHandler}whenDependentTypesAreResolved([],rawArgTypes,argTypes=>{var memberFunction=craftInvokerFunction(humanName,argTypes,classType,rawInvoker,context,isAsync);if(undefined===proto[methodName].overloadTable){memberFunction.argCount=argCount-2;proto[methodName]=memberFunction}else{proto[methodName].overloadTable[argCount-2]=memberFunction}return[]});return[]})};var validateThis=(this_,classType,humanName)=>{if(!(this_ instanceof Object)){throwBindingError(`${humanName} with invalid "this": ${this_}`)}if(!(this_ instanceof classType.registeredClass.constructor)){throwBindingError(`${humanName} incompatible with "this" of type ${this_.constructor.name}`)}if(!this_.$$.ptr){throwBindingError(`cannot call emscripten binding method ${humanName} on deleted object`)}return upcastPointer(this_.$$.ptr,this_.$$.ptrType.registeredClass,classType.registeredClass)};var __embind_register_class_property=function(classType,fieldName,getterReturnType,getterSignature,getter,getterContext,setterArgumentType,setterSignature,setter,setterContext){classType>>>=0;fieldName>>>=0;getterReturnType>>>=0;getterSignature>>>=0;getter>>>=0;getterContext>>>=0;setterArgumentType>>>=0;setterSignature>>>=0;setter>>>=0;setterContext>>>=0;fieldName=AsciiToString(fieldName);getter=embind__requireFunction(getterSignature,getter);whenDependentTypesAreResolved([],[classType],classType=>{classType=classType[0];var humanName=`${classType.name}.${fieldName}`;var desc={get(){throwUnboundTypeError(`Cannot access ${humanName} due to unbound types`,[getterReturnType,setterArgumentType])},enumerable:true,configurable:true};if(setter){desc.set=()=>throwUnboundTypeError(`Cannot access ${humanName} due to unbound types`,[getterReturnType,setterArgumentType])}else{desc.set=v=>throwBindingError(humanName+" is a read-only property")}Object.defineProperty(classType.registeredClass.instancePrototype,fieldName,desc);whenDependentTypesAreResolved([],setter?[getterReturnType,setterArgumentType]:[getterReturnType],types=>{var getterReturnType=types[0];var desc={get(){var ptr=validateThis(this,classType,humanName+" getter");return getterReturnType.fromWireType(getter(getterContext,ptr))},enumerable:true};if(setter){setter=embind__requireFunction(setterSignature,setter);var setterArgumentType=types[1];desc.set=function(v){var ptr=validateThis(this,classType,humanName+" setter");var destructors=[];setter(setterContext,ptr,setterArgumentType.toWireType(destructors,v));runDestructors(destructors)}}Object.defineProperty(classType.registeredClass.instancePrototype,fieldName,desc);return[]});return[]})};var emval_freelist=[];var emval_handles=[0,1,,1,null,1,true,1,false,1];function __emval_decref(handle){handle>>>=0;if(handle>9&&0===--emval_handles[handle+1]){emval_handles[handle]=undefined;emval_freelist.push(handle)}}var Emval={toValue:handle=>{if(!handle){throwBindingError(`Cannot use deleted val. handle = ${handle}`)}return emval_handles[handle]},toHandle:value=>{switch(value){case undefined:return 2;case null:return 4;case true:return 6;case false:return 8;default:{const handle=emval_freelist.pop()||emval_handles.length;emval_handles[handle]=value;emval_handles[handle+1]=1;return handle}}}};var EmValType={name:"emscripten::val",fromWireType:handle=>{var rv=Emval.toValue(handle);__emval_decref(handle);return rv},toWireType:(destructors,value)=>Emval.toHandle(value),readValueFromPointer:readPointer,destructorFunction:null};function __embind_register_emval(rawType){rawType>>>=0;return registerType(rawType,EmValType)}var floatReadValueFromPointer=(name,width)=>{switch(width){case 4:return function(pointer){return this.fromWireType(HEAPF32[pointer>>>2>>>0])};case 8:return function(pointer){return this.fromWireType(HEAPF64[pointer>>>3>>>0])};default:throw new TypeError(`invalid float width (${width}): ${name}`)}};var __embind_register_float=function(rawType,name,size){rawType>>>=0;name>>>=0;size>>>=0;name=AsciiToString(name);registerType(rawType,{name,fromWireType:value=>value,toWireType:(destructors,value)=>value,readValueFromPointer:floatReadValueFromPointer(name,size),destructorFunction:null})};var __embind_register_integer=function(primitiveType,name,size,minRange,maxRange){primitiveType>>>=0;name>>>=0;size>>>=0;name=AsciiToString(name);const isUnsignedType=minRange===0;let fromWireType=value=>value;if(isUnsignedType){var bitshift=32-8*size;fromWireType=value=>value<>>bitshift;maxRange=fromWireType(maxRange)}registerType(primitiveType,{name,fromWireType,toWireType:(destructors,value)=>value,readValueFromPointer:integerReadValueFromPointer(name,size,minRange!==0),destructorFunction:null})};var installIndexedIterator=(proto,sizeMethodName,getMethodName)=>{const makeIterator=(size,getValue)=>{let index=0;return{next(){if(index>=size){return{done:true}}const current=index;index++;const value=getValue(current);return{value,done:false}},[Symbol.iterator](){return this}}};if(!proto[Symbol.iterator]){proto[Symbol.iterator]=function(){const size=this[sizeMethodName]();return makeIterator(size,i=>this[getMethodName](i))}}};var __embind_register_iterable=function(rawClassType,rawElementType,sizeMethodName,getMethodName){rawClassType>>>=0;rawElementType>>>=0;sizeMethodName>>>=0;getMethodName>>>=0;sizeMethodName=AsciiToString(sizeMethodName);getMethodName=AsciiToString(getMethodName);whenDependentTypesAreResolved([],[rawClassType,rawElementType],types=>{const classType=types[0];installIndexedIterator(classType.registeredClass.instancePrototype,sizeMethodName,getMethodName);return[]})};function __embind_register_memory_view(rawType,dataTypeIndex,name){rawType>>>=0;name>>>=0;var typeMapping=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array];var TA=typeMapping[dataTypeIndex];function decodeMemoryView(handle){var size=HEAPU32[handle>>>2>>>0];var data=HEAPU32[handle+4>>>2>>>0];return new TA(HEAP8.buffer,data,size)}name=AsciiToString(name);registerType(rawType,{name,fromWireType:decodeMemoryView,readValueFromPointer:decodeMemoryView},{ignoreDuplicateRegistrations:true})}var EmValOptionalType=Object.assign({optional:true},EmValType);function __embind_register_optional(rawOptionalType,rawType){rawOptionalType>>>=0;rawType>>>=0;registerType(rawOptionalType,EmValOptionalType)}function __embind_register_std_string(rawType,name){rawType>>>=0;name>>>=0;name=AsciiToString(name);var stdStringIsUTF8=true;registerType(rawType,{name,fromWireType(value){var length=HEAPU32[value>>>2>>>0];var payload=value+4;var str;if(stdStringIsUTF8){str=UTF8ToString(payload,length,true)}else{str="";for(var i=0;i>>0])}}_free(value);return str},toWireType(destructors,value){if(value instanceof ArrayBuffer){value=new Uint8Array(value)}var length;var valueIsOfTypeString=typeof value=="string";if(!(valueIsOfTypeString||ArrayBuffer.isView(value)&&value.BYTES_PER_ELEMENT==1)){throwBindingError("Cannot pass non-string to std::string")}if(stdStringIsUTF8&&valueIsOfTypeString){length=lengthBytesUTF8(value)}else{length=value.length}var base=_malloc(4+length+1);var ptr=base+4;HEAPU32[base>>>2>>>0]=length;if(valueIsOfTypeString){if(stdStringIsUTF8){stringToUTF8(value,ptr,length+1)}else{for(var i=0;i255){_free(base);throwBindingError("String has UTF-16 code units that do not fit in 8 bits")}HEAPU8[ptr+i>>>0]=charCode}}}else{HEAPU8.set(value,ptr>>>0)}if(destructors!==null){destructors.push(_free,base)}return base},readValueFromPointer:readPointer,destructorFunction(ptr){_free(ptr)}})}var UTF16Decoder=globalThis.TextDecoder?new TextDecoder("utf-16le"):undefined;var UTF16ToString=(ptr,maxBytesToRead,ignoreNul)=>{var idx=ptr>>>1;var endIdx=findStringEnd(HEAPU16,idx,maxBytesToRead/2,ignoreNul);if(endIdx-idx>16&&UTF16Decoder)return UTF16Decoder.decode(HEAPU16.subarray(idx>>>0,endIdx>>>0));var str="";for(var i=idx;i>>0];str+=String.fromCharCode(codeUnit)}return str};var stringToUTF16=(str,outPtr,maxBytesToWrite)=>{maxBytesToWrite??=2147483647;if(maxBytesToWrite<2)return 0;maxBytesToWrite-=2;var startPtr=outPtr;var numCharsToWrite=maxBytesToWrite>>1>>>0]=codeUnit;outPtr+=2}HEAP16[outPtr>>>1>>>0]=0;return outPtr-startPtr};var lengthBytesUTF16=str=>str.length*2;var UTF32ToString=(ptr,maxBytesToRead,ignoreNul)=>{var str="";var startIdx=ptr>>>2;for(var i=0;!(i>=maxBytesToRead/4);i++){var utf32=HEAPU32[startIdx+i>>>0];if(!utf32&&!ignoreNul)break;str+=String.fromCodePoint(utf32)}return str};var stringToUTF32=(str,outPtr,maxBytesToWrite)=>{outPtr>>>=0;maxBytesToWrite??=2147483647;if(maxBytesToWrite<4)return 0;var startPtr=outPtr;var endPtr=startPtr+maxBytesToWrite-4;for(var i=0;i65535){i++}HEAP32[outPtr>>>2>>>0]=codePoint;outPtr+=4;if(outPtr+4>endPtr)break}HEAP32[outPtr>>>2>>>0]=0;return outPtr-startPtr};var lengthBytesUTF32=str=>{var len=0;for(var i=0;i65535){i++}len+=4}return len};function __embind_register_std_wstring(rawType,charSize,name){rawType>>>=0;charSize>>>=0;name>>>=0;name=AsciiToString(name);var decodeString,encodeString,lengthBytesUTF;if(charSize===2){decodeString=UTF16ToString;encodeString=stringToUTF16;lengthBytesUTF=lengthBytesUTF16}else{decodeString=UTF32ToString;encodeString=stringToUTF32;lengthBytesUTF=lengthBytesUTF32}registerType(rawType,{name,fromWireType:value=>{var length=HEAPU32[value>>>2>>>0];var str=decodeString(value+4,length*charSize,true);_free(value);return str},toWireType:(destructors,value)=>{if(!(typeof value=="string")){throwBindingError(`Cannot pass non-string to C++ string type ${name}`)}var length=lengthBytesUTF(value);var ptr=_malloc(4+length+charSize);HEAPU32[ptr>>>2>>>0]=length/charSize;encodeString(value,ptr+4,length+charSize);if(destructors!==null){destructors.push(_free,ptr)}return ptr},readValueFromPointer:readPointer,destructorFunction(ptr){_free(ptr)}})}function __embind_register_value_object(rawType,name,constructorSignature,rawConstructor,destructorSignature,rawDestructor){rawType>>>=0;name>>>=0;constructorSignature>>>=0;rawConstructor>>>=0;destructorSignature>>>=0;rawDestructor>>>=0;structRegistrations[rawType]={name:AsciiToString(name),rawConstructor:embind__requireFunction(constructorSignature,rawConstructor),rawDestructor:embind__requireFunction(destructorSignature,rawDestructor),fields:[]}}function __embind_register_value_object_field(structType,fieldName,getterReturnType,getterSignature,getter,getterContext,setterArgumentType,setterSignature,setter,setterContext){structType>>>=0;fieldName>>>=0;getterReturnType>>>=0;getterSignature>>>=0;getter>>>=0;getterContext>>>=0;setterArgumentType>>>=0;setterSignature>>>=0;setter>>>=0;setterContext>>>=0;structRegistrations[structType].fields.push({fieldName:AsciiToString(fieldName),getterReturnType,getter:embind__requireFunction(getterSignature,getter),getterContext,setterArgumentType,setter:embind__requireFunction(setterSignature,setter),setterContext})}var __embind_register_void=function(rawType,name){rawType>>>=0;name>>>=0;name=AsciiToString(name);registerType(rawType,{isVoid:true,name,fromWireType:()=>undefined,toWireType:(destructors,o)=>undefined})};var inetPton4=str=>{var b=str.split(".");for(var i=0;i<4;i++){var tmp=Number(b[i]);if(isNaN(tmp))return null;b[i]=tmp}return(b[0]|b[1]<<8|b[2]<<16|b[3]<<24)>>>0};var inetPton6=str=>{var words;var w,offset,z;var valid6regx=/^((?=.*::)(?!.*::.+::)(::)?([\dA-F]{1,4}:(:|\b)|){5}|([\dA-F]{1,4}:){6})((([\dA-F]{1,4}((?!\3)::|:\b|$))|(?!\2\3)){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4})$/i;var parts=[];if(!valid6regx.test(str)){return null}if(str==="::"){return[0,0,0,0,0,0,0,0]}if(str.startsWith("::")){str=str.replace("::","Z:")}else{str=str.replace("::",":Z:")}if(str.indexOf(".")>0){str=str.replace(new RegExp("[.]","g"),":");words=str.split(":");words[words.length-4]=Number(words[words.length-4])+Number(words[words.length-3])*256;words[words.length-3]=Number(words[words.length-2])+Number(words[words.length-1])*256;words=words.slice(0,words.length-2)}else{words=str.split(":")}offset=0;z=0;for(w=0;w>>=0;var nameString=UTF8ToString(name);return inetPton4(DNS.lookup_name(nameString))}var runtimeKeepaliveCounter=0;var __emscripten_runtime_keepalive_clear=()=>{noExitRuntime=false;runtimeKeepaliveCounter=0};var emval_methodCallers=[];var emval_addMethodCaller=caller=>{var id=emval_methodCallers.length;emval_methodCallers.push(caller);return id};var requireRegisteredType=(rawType,humanName)=>{var impl=registeredTypes[rawType];if(undefined===impl){throwBindingError(`${humanName} has unknown type ${getTypeName(rawType)}`)}return impl};var emval_lookupTypes=(argCount,argTypes)=>{var a=new Array(argCount);for(var i=0;i>>2>>>0],`parameter ${i}`)}return a};var emval_returnValue=(toReturnWire,destructorsRef,handle)=>{var destructors=[];var result=toReturnWire(destructors,handle);if(destructors.length){HEAPU32[destructorsRef>>>2>>>0]=Emval.toHandle(destructors)}return result};var emval_symbols={};var getStringOrSymbol=address=>{var symbol=emval_symbols[address];if(symbol===undefined){return AsciiToString(address)}return symbol};var __emval_create_invoker=function(argCount,argTypesPtr,kind){argTypesPtr>>>=0;var GenericWireTypeSize=8;var[retType,...argTypes]=emval_lookupTypes(argCount,argTypesPtr);var toReturnWire=retType.toWireType.bind(retType);var argFromPtr=argTypes.map(type=>type.readValueFromPointer.bind(type));argCount--;var captures={toValue:Emval.toValue};var args=argFromPtr.map((argFromPtr,i)=>{var captureName=`argFromPtr${i}`;captures[captureName]=argFromPtr;return`${captureName}(args${i?"+"+i*GenericWireTypeSize:""})`});var functionBody;switch(kind){case 0:functionBody="toValue(handle)";break;case 2:functionBody="new (toValue(handle))";break;case 3:functionBody="";break;case 1:captures["getStringOrSymbol"]=getStringOrSymbol;functionBody="toValue(handle)[getStringOrSymbol(methodName)]";break}functionBody+=`(${args})`;if(!retType.isVoid){captures["toReturnWire"]=toReturnWire;captures["emval_returnValue"]=emval_returnValue;functionBody=`return emval_returnValue(toReturnWire, destructorsRef, ${functionBody})`}functionBody=`return function (handle, methodName, destructorsRef, args) {\n${functionBody}\n}`;var invokerFunction=new Function(Object.keys(captures),functionBody)(...Object.values(captures));var functionName=`methodCaller<(${argTypes.map(t=>t.name)}) => ${retType.name}>`;return emval_addMethodCaller(createNamedFunction(functionName,invokerFunction))};function __emval_invoke(caller,handle,methodName,destructorsRef,args){caller>>>=0;handle>>>=0;methodName>>>=0;destructorsRef>>>=0;args>>>=0;return emval_methodCallers[caller](handle,methodName,destructorsRef,args)}function __emval_run_destructors(handle){handle>>>=0;var destructors=Emval.toValue(handle);runDestructors(destructors);__emval_decref(handle)}var isLeapYear=year=>year%4===0&&(year%100!==0||year%400===0);var MONTH_DAYS_LEAP_CUMULATIVE=[0,31,60,91,121,152,182,213,244,274,305,335];var MONTH_DAYS_REGULAR_CUMULATIVE=[0,31,59,90,120,151,181,212,243,273,304,334];var ydayFromDate=date=>{var leap=isLeapYear(date.getFullYear());var monthDaysCumulative=leap?MONTH_DAYS_LEAP_CUMULATIVE:MONTH_DAYS_REGULAR_CUMULATIVE;var yday=monthDaysCumulative[date.getMonth()]+date.getDate()-1;return yday};function __localtime_js(time,tmPtr){time=bigintToI53Checked(time);tmPtr>>>=0;var date=new Date(time*1e3);HEAP32[tmPtr>>>2>>>0]=date.getSeconds();HEAP32[tmPtr+4>>>2>>>0]=date.getMinutes();HEAP32[tmPtr+8>>>2>>>0]=date.getHours();HEAP32[tmPtr+12>>>2>>>0]=date.getDate();HEAP32[tmPtr+16>>>2>>>0]=date.getMonth();HEAP32[tmPtr+20>>>2>>>0]=date.getFullYear()-1900;HEAP32[tmPtr+24>>>2>>>0]=date.getDay();var yday=ydayFromDate(date)|0;HEAP32[tmPtr+28>>>2>>>0]=yday;HEAP32[tmPtr+36>>>2>>>0]=-(date.getTimezoneOffset()*60);var start=new Date(date.getFullYear(),0,1);var summerOffset=new Date(date.getFullYear(),6,1).getTimezoneOffset();var winterOffset=start.getTimezoneOffset();var dst=(summerOffset!=winterOffset&&date.getTimezoneOffset()==Math.min(winterOffset,summerOffset))|0;HEAP32[tmPtr+32>>>2>>>0]=dst}var timers={};var handleException=e=>{if(e instanceof ExitStatus||e=="unwind"){return EXITSTATUS}quit_(1,e)};var keepRuntimeAlive=()=>noExitRuntime||runtimeKeepaliveCounter>0;var _proc_exit=code=>{EXITSTATUS=code;if(!keepRuntimeAlive()){Module["onExit"]?.(code);ABORT=true}quit_(code,new ExitStatus(code))};var exitJS=(status,implicit)=>{EXITSTATUS=status;_proc_exit(status)};var _exit=exitJS;var maybeExit=()=>{if(!keepRuntimeAlive()){try{_exit(EXITSTATUS)}catch(e){handleException(e)}}};var callUserCallback=func=>{if(ABORT){return}try{return func()}catch(e){handleException(e)}finally{maybeExit()}};var _emscripten_get_now=()=>performance.now();var __setitimer_js=(which,timeout_ms)=>{if(timers[which]){clearTimeout(timers[which].id);delete timers[which]}if(!timeout_ms)return 0;var id=setTimeout(()=>{delete timers[which];callUserCallback(()=>__emscripten_timeout(which,_emscripten_get_now()))},timeout_ms);timers[which]={id,timeout_ms};return 0};var __tzset_js=function(timezone,daylight,std_name,dst_name){timezone>>>=0;daylight>>>=0;std_name>>>=0;dst_name>>>=0;var currentYear=(new Date).getFullYear();var winter=new Date(currentYear,0,1);var summer=new Date(currentYear,6,1);var winterOffset=winter.getTimezoneOffset();var summerOffset=summer.getTimezoneOffset();var stdTimezoneOffset=Math.max(winterOffset,summerOffset);HEAPU32[timezone>>>2>>>0]=stdTimezoneOffset*60;HEAP32[daylight>>>2>>>0]=Number(winterOffset!=summerOffset);var extractZone=timezoneOffset=>{var sign=timezoneOffset>=0?"-":"+";var absOffset=Math.abs(timezoneOffset);var hours=String(Math.floor(absOffset/60)).padStart(2,"0");var minutes=String(absOffset%60).padStart(2,"0");return`UTC${sign}${hours}${minutes}`};var winterName=extractZone(winterOffset);var summerName=extractZone(summerOffset);if(summerOffsetDate.now();var nowIsMonotonic=1;var checkWasiClock=clock_id=>clock_id>=0&&clock_id<=3;function _clock_time_get(clk_id,ignored_precision,ptime){ignored_precision=bigintToI53Checked(ignored_precision);ptime>>>=0;if(!checkWasiClock(clk_id)){return 28}var now;if(clk_id===0){now=_emscripten_date_now()}else if(nowIsMonotonic){now=_emscripten_get_now()}else{return 52}var nsec=Math.round(now*1e3*1e3);HEAP64[ptime>>>3>>>0]=BigInt(nsec);return 0}var jsStackTrace=()=>(new Error).stack.toString();var getCallstack=flags=>{var callstack=jsStackTrace();var lines=callstack.split("\n");callstack="";var firefoxRe=new RegExp("\\s*(.*?)@(.*?):([0-9]+):([0-9]+)");var chromeRe=new RegExp("\\s*at (.*?) \\((.*):(.*):(.*)\\)");for(var line of lines){var symbolName="";var file="";var lineno=0;var column=0;var parts=chromeRe.exec(line);if(parts?.length==5){symbolName=parts[1];file=parts[2];lineno=parts[3];column=parts[4]}else{parts=firefoxRe.exec(line);if(parts?.length>=4){symbolName=parts[1];file=parts[2];lineno=parts[3];column=parts[4]|0}else{callstack+=line+"\n";continue}}if(symbolName=="_emscripten_log"||symbolName=="_emscripten_get_callstack"){callstack="";continue}if(flags&24){if(flags&64){file=file.substring(file.replace(/\\/g,"/").lastIndexOf("/")+1)}callstack+=` at ${symbolName} (${file}:${lineno}:${column})\n`}}callstack=callstack.replace(/\s+$/,"");return callstack};function _emscripten_get_callstack(flags,str,maxbytes){str>>>=0;var callstack=getCallstack(flags);if(!str||maxbytes<=0){return lengthBytesUTF8(callstack)+1}var bytesWrittenExcludingNull=stringToUTF8(callstack,str,maxbytes);return bytesWrittenExcludingNull+1}var getHeapMax=()=>4294901760;function _emscripten_get_heap_max(){return getHeapMax()}function getFullscreenElement(){return document.fullscreenElement||document.mozFullScreenElement||document.webkitFullscreenElement||document.webkitCurrentFullScreenElement||document.msFullscreenElement}var safeSetTimeout=(func,timeout)=>setTimeout(()=>{callUserCallback(func)},timeout);var warnOnce=text=>{warnOnce.shown||={};if(!warnOnce.shown[text]){warnOnce.shown[text]=1;if(ENVIRONMENT_IS_NODE)text="warning: "+text;err(text)}};var Browser={useWebGL:false,isFullscreen:false,pointerLock:false,moduleContextCreatedCallbacks:[],workers:[],preloadedImages:{},preloadedAudios:{},getCanvas:()=>Module["canvas"],init(){if(Browser.initted)return;Browser.initted=true;var imagePlugin={};imagePlugin["canHandle"]=name=>!Module["noImageDecoding"]&&/\.(jpg|jpeg|png|bmp|webp)$/i.test(name);imagePlugin["handle"]=async(byteArray,name)=>{var b=new Blob([byteArray],{type:Browser.getMimetype(name)});if(b.size!==byteArray.length){b=new Blob([new Uint8Array(byteArray).buffer],{type:Browser.getMimetype(name)})}var url=URL.createObjectURL(b);return new Promise((resolve,reject)=>{var img=new Image;img.onload=()=>{var canvas=document.createElement("canvas");canvas.width=img.width;canvas.height=img.height;var ctx=canvas.getContext("2d");ctx.drawImage(img,0,0);Browser.preloadedImages[name]=canvas;URL.revokeObjectURL(url);resolve(byteArray)};img.onerror=event=>{err(`Image ${url} could not be decoded`);reject()};img.src=url})};preloadPlugins.push(imagePlugin);var audioPlugin={};audioPlugin["canHandle"]=name=>!Module["noAudioDecoding"]&&name.slice(-4)in{".ogg":1,".wav":1,".mp3":1};audioPlugin["handle"]=async(byteArray,name)=>new Promise((resolve,reject)=>{var done=false;function finish(audio){if(done)return;done=true;Browser.preloadedAudios[name]=audio;resolve(byteArray)}var b=new Blob([byteArray],{type:Browser.getMimetype(name)});var url=URL.createObjectURL(b);var audio=new Audio;audio.addEventListener("canplaythrough",()=>finish(audio),false);audio.onerror=event=>{if(done)return;err(`warning: browser could not fully decode audio ${name}, trying slower base64 approach`);function encode64(data){var BASE="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";var PAD="=";var ret="";var leftchar=0;var leftbits=0;for(var i=0;i=6){var curr=leftchar>>leftbits-6&63;leftbits-=6;ret+=BASE[curr]}}if(leftbits==2){ret+=BASE[(leftchar&3)<<4];ret+=PAD+PAD}else if(leftbits==4){ret+=BASE[(leftchar&15)<<2];ret+=PAD}return ret}audio.src="data:audio/x-"+name.slice(-3)+";base64,"+encode64(byteArray);finish(audio)};audio.src=url;safeSetTimeout(()=>{finish(audio)},1e4)});preloadPlugins.push(audioPlugin);function pointerLockChange(){var canvas=Browser.getCanvas();Browser.pointerLock=document.pointerLockElement===canvas}var canvas=Browser.getCanvas();if(canvas){document.addEventListener("pointerlockchange",pointerLockChange,false);if(Module["elementPointerLock"]){canvas.addEventListener("click",ev=>{if(!Browser.pointerLock&&Browser.getCanvas().requestPointerLock){Browser.getCanvas().requestPointerLock();ev.preventDefault()}},false)}}},createContext(canvas,useWebGL,setInModule,webGLContextAttributes){if(useWebGL&&Module["ctx"]&&canvas==Browser.getCanvas())return Module["ctx"];var ctx;var contextHandle;if(useWebGL){var contextAttributes={antialias:false,alpha:false,majorVersion:1};if(webGLContextAttributes){for(var attribute in webGLContextAttributes){contextAttributes[attribute]=webGLContextAttributes[attribute]}}if(typeof GL!="undefined"){contextHandle=GL.createContext(canvas,contextAttributes);if(contextHandle){ctx=GL.getContext(contextHandle).GLctx}}}else{ctx=canvas.getContext("2d")}if(!ctx)return null;if(setInModule){Module["ctx"]=ctx;if(useWebGL)GL.makeContextCurrent(contextHandle);Browser.useWebGL=useWebGL;Browser.moduleContextCreatedCallbacks.forEach(callback=>callback());Browser.init()}return ctx},fullscreenHandlersInstalled:false,lockPointer:undefined,resizeCanvas:undefined,requestFullscreen(lockPointer,resizeCanvas){Browser.lockPointer=lockPointer;Browser.resizeCanvas=resizeCanvas;if(typeof Browser.lockPointer=="undefined")Browser.lockPointer=true;if(typeof Browser.resizeCanvas=="undefined")Browser.resizeCanvas=false;var canvas=Browser.getCanvas();function fullscreenChange(){Browser.isFullscreen=false;var canvasContainer=canvas.parentNode;if(getFullscreenElement()===canvasContainer){canvas.exitFullscreen=Browser.exitFullscreen;if(Browser.lockPointer)canvas.requestPointerLock();Browser.isFullscreen=true;if(Browser.resizeCanvas){Browser.setFullscreenCanvasSize()}else{Browser.updateCanvasDimensions(canvas)}}else{canvasContainer.parentNode.insertBefore(canvas,canvasContainer);canvasContainer.parentNode.removeChild(canvasContainer);if(Browser.resizeCanvas){Browser.setWindowedCanvasSize()}else{Browser.updateCanvasDimensions(canvas)}}Module["onFullScreen"]?.(Browser.isFullscreen);Module["onFullscreen"]?.(Browser.isFullscreen)}if(!Browser.fullscreenHandlersInstalled){Browser.fullscreenHandlersInstalled=true;document.addEventListener("fullscreenchange",fullscreenChange,false);document.addEventListener("mozfullscreenchange",fullscreenChange,false);document.addEventListener("webkitfullscreenchange",fullscreenChange,false);document.addEventListener("MSFullscreenChange",fullscreenChange,false)}var canvasContainer=document.createElement("div");canvas.parentNode.insertBefore(canvasContainer,canvas);canvasContainer.appendChild(canvas);canvasContainer.requestFullscreen=canvasContainer["requestFullscreen"]||canvasContainer["mozRequestFullScreen"]||canvasContainer["msRequestFullscreen"]||(canvasContainer["webkitRequestFullscreen"]?()=>canvasContainer["webkitRequestFullscreen"](Element["ALLOW_KEYBOARD_INPUT"]):null)||(canvasContainer["webkitRequestFullScreen"]?()=>canvasContainer["webkitRequestFullScreen"](Element["ALLOW_KEYBOARD_INPUT"]):null);canvasContainer.requestFullscreen()},exitFullscreen(){if(!Browser.isFullscreen){return false}var CFS=document["exitFullscreen"]||document["cancelFullScreen"]||document["mozCancelFullScreen"]||document["msExitFullscreen"]||document["webkitCancelFullScreen"]||(()=>{});CFS.apply(document,[]);return true},safeSetTimeout(func,timeout){return safeSetTimeout(func,timeout)},getMimetype(name){return{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",bmp:"image/bmp",ogg:"audio/ogg",wav:"audio/wav",mp3:"audio/mpeg"}[name.slice(name.lastIndexOf(".")+1)]},getUserMedia(func){window.getUserMedia||=navigator["getUserMedia"]||navigator["mozGetUserMedia"];window.getUserMedia(func)},getMovementX(event){return event["movementX"]||event["mozMovementX"]||event["webkitMovementX"]||0},getMovementY(event){return event["movementY"]||event["mozMovementY"]||event["webkitMovementY"]||0},getMouseWheelDelta(event){var delta=0;switch(event.type){case"DOMMouseScroll":delta=event.detail/3;break;case"mousewheel":delta=event.wheelDelta/120;break;case"wheel":delta=event.deltaY;switch(event.deltaMode){case 0:delta/=100;break;case 1:delta/=3;break;case 2:delta*=80;break;default:abort("unrecognized mouse wheel delta mode: "+event.deltaMode)}break;default:abort("unrecognized mouse wheel event: "+event.type)}return delta},mouseX:0,mouseY:0,mouseMovementX:0,mouseMovementY:0,touches:{},lastTouches:{},calculateMouseCoords(pageX,pageY){var canvas=Browser.getCanvas();var rect=canvas.getBoundingClientRect();var scrollX=typeof window.scrollX!="undefined"?window.scrollX:window.pageXOffset;var scrollY=typeof window.scrollY!="undefined"?window.scrollY:window.pageYOffset;var adjustedX=pageX-(scrollX+rect.left);var adjustedY=pageY-(scrollY+rect.top);adjustedX=adjustedX*(canvas.width/rect.width);adjustedY=adjustedY*(canvas.height/rect.height);return{x:adjustedX,y:adjustedY}},setMouseCoords(pageX,pageY){const{x,y}=Browser.calculateMouseCoords(pageX,pageY);Browser.mouseMovementX=x-Browser.mouseX;Browser.mouseMovementY=y-Browser.mouseY;Browser.mouseX=x;Browser.mouseY=y},calculateMouseEvent(event){if(Browser.pointerLock){if(event.type!="mousemove"&&"mozMovementX"in event){Browser.mouseMovementX=Browser.mouseMovementY=0}else{Browser.mouseMovementX=Browser.getMovementX(event);Browser.mouseMovementY=Browser.getMovementY(event)}Browser.mouseX+=Browser.mouseMovementX;Browser.mouseY+=Browser.mouseMovementY}else{if(event.type==="touchstart"||event.type==="touchend"||event.type==="touchmove"){var touch=event.touch;if(touch===undefined){return}var coords=Browser.calculateMouseCoords(touch.pageX,touch.pageY);if(event.type==="touchstart"){Browser.lastTouches[touch.identifier]=coords;Browser.touches[touch.identifier]=coords}else if(event.type==="touchend"||event.type==="touchmove"){var last=Browser.touches[touch.identifier];last||=coords;Browser.lastTouches[touch.identifier]=last;Browser.touches[touch.identifier]=coords}return}Browser.setMouseCoords(event.pageX,event.pageY)}},resizeListeners:[],updateResizeListeners(){var canvas=Browser.getCanvas();Browser.resizeListeners.forEach(listener=>listener(canvas.width,canvas.height))},setCanvasSize(width,height,noUpdates){var canvas=Browser.getCanvas();Browser.updateCanvasDimensions(canvas,width,height);if(!noUpdates)Browser.updateResizeListeners()},windowedWidth:0,windowedHeight:0,setFullscreenCanvasSize(){if(typeof SDL!="undefined"){var flags=HEAPU32[SDL.screen>>>2>>>0];flags=flags|8388608;HEAP32[SDL.screen>>>2>>>0]=flags}Browser.updateCanvasDimensions(Browser.getCanvas());Browser.updateResizeListeners()},setWindowedCanvasSize(){if(typeof SDL!="undefined"){var flags=HEAPU32[SDL.screen>>>2>>>0];flags=flags&~8388608;HEAP32[SDL.screen>>>2>>>0]=flags}Browser.updateCanvasDimensions(Browser.getCanvas());Browser.updateResizeListeners()},updateCanvasDimensions(canvas,wNative,hNative){if(wNative&&hNative){canvas.widthNative=wNative;canvas.heightNative=hNative}else{wNative=canvas.widthNative;hNative=canvas.heightNative}var w=wNative;var h=hNative;if(Module["forcedAspectRatio"]>0){if(w/h{path=PATH_FS.resolve(path);var canvas=Browser.preloadedImages[path];if(!canvas)return 0;var ctx=canvas.getContext("2d");var image=ctx.getImageData(0,0,canvas.width,canvas.height);var buf=_malloc(canvas.width*canvas.height*4);HEAPU8.set(image.data,buf>>>0);HEAP32[w>>>2>>>0]=canvas.width;HEAP32[h>>>2>>>0]=canvas.height;return buf};function _emscripten_get_preloaded_image_data(path,w,h){path>>>=0;w>>>=0;h>>>=0;return getPreloadedImageData(UTF8ToString(path),w,h)}var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};function _emscripten_resize_heap(requestedSize){requestedSize>>>=0;var oldSize=HEAPU8.length;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false}var ENV={};var getExecutableName=()=>thisProgram||"./this.program";var getEnvStrings=()=>{if(!getEnvStrings.strings){var lang=(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8";var env={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:lang,_:getExecutableName()};for(var x in ENV){if(ENV[x]===undefined)delete env[x];else env[x]=ENV[x]}var strings=[];for(var x in env){strings.push(`${x}=${env[x]}`)}getEnvStrings.strings=strings}return getEnvStrings.strings};function _fd_close(fd){try{var stream=SYSCALLS.getStreamFromFD(fd);FS.close(stream);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var doReadv=(stream,iov,iovcnt,offset)=>{var ret=0;for(var i=0;i>>2>>>0];var len=HEAPU32[iov+4>>>2>>>0];iov+=8;var curr=FS.read(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr;if(curr>>=0;iovcnt>>>=0;pnum>>>=0;try{var stream=SYSCALLS.getStreamFromFD(fd);var num=doReadv(stream,iov,iovcnt);HEAPU32[pnum>>>2>>>0]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}function _fd_seek(fd,offset,whence,newOffset){offset=bigintToI53Checked(offset);newOffset>>>=0;try{if(isNaN(offset))return 61;var stream=SYSCALLS.getStreamFromFD(fd);FS.llseek(stream,offset,whence);HEAP64[newOffset>>>3>>>0]=BigInt(stream.position);if(stream.getdents&&offset===0&&whence===0)stream.getdents=null;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var doWritev=(stream,iov,iovcnt,offset)=>{var ret=0;for(var i=0;i>>2>>>0];var len=HEAPU32[iov+4>>>2>>>0];iov+=8;var curr=FS.write(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr;if(curr>>=0;iovcnt>>>=0;pnum>>>=0;try{var stream=SYSCALLS.getStreamFromFD(fd);var num=doWritev(stream,iov,iovcnt);HEAPU32[pnum>>>2>>>0]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var getCppExceptionTag=()=>___cpp_exception;var getCppExceptionThrownObjectFromWebAssemblyException=ex=>{var unwind_header=ex.getArg(getCppExceptionTag(),0);return ___thrown_object_from_unwind_exception(unwind_header)};var incrementExceptionRefcount=ex=>{var ptr=getCppExceptionThrownObjectFromWebAssemblyException(ex);___cxa_increment_exception_refcount(ptr)};var decrementExceptionRefcount=ex=>{var ptr=getCppExceptionThrownObjectFromWebAssemblyException(ex);___cxa_decrement_exception_refcount(ptr)};var stackSave=()=>_emscripten_stack_get_current();var stackRestore=val=>__emscripten_stack_restore(val);var stackAlloc=sz=>__emscripten_stack_alloc(sz);var getExceptionMessageCommon=ptr=>{var sp=stackSave();var type_addr_addr=stackAlloc(4);var message_addr_addr=stackAlloc(4);___get_exception_message(ptr,type_addr_addr,message_addr_addr);var type_addr=HEAPU32[type_addr_addr>>>2>>>0];var message_addr=HEAPU32[message_addr_addr>>>2>>>0];var type=UTF8ToString(type_addr);_free(type_addr);var message;if(message_addr){message=UTF8ToString(message_addr);_free(message_addr)}stackRestore(sp);return[type,message]};var getExceptionMessage=ex=>{var ptr=getCppExceptionThrownObjectFromWebAssemblyException(ex);return getExceptionMessageCommon(ptr)};FS.createPreloadedFile=FS_createPreloadedFile;FS.preloadFile=FS_preloadFile;FS.staticInit();init_ClassHandle();init_RegisteredPointer();{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["preloadPlugins"])preloadPlugins=Module["preloadPlugins"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].shift()()}}}Module["FS"]=FS;Module["incrementExceptionRefcount"]=incrementExceptionRefcount;Module["decrementExceptionRefcount"]=decrementExceptionRefcount;Module["getExceptionMessage"]=getExceptionMessage;function OSD_MemInfo_getModuleHeapLength(){return Module.HEAP8.length}var ___getTypeName,_malloc,_free,_htons,__emscripten_timeout,___trap,__emscripten_stack_restore,__emscripten_stack_alloc,_emscripten_stack_get_current,___cxa_decrement_exception_refcount,___cxa_increment_exception_refcount,___thrown_object_from_unwind_exception,___get_exception_message,memory,__indirect_function_table,___cpp_exception,wasmMemory,wasmTable;function assignWasmExports(wasmExports){___getTypeName=wasmExports["ca"];_malloc=wasmExports["ea"];_free=wasmExports["ga"];_htons=wasmExports["ha"];__emscripten_timeout=wasmExports["ia"];___trap=wasmExports["ja"];__emscripten_stack_restore=wasmExports["ka"];__emscripten_stack_alloc=wasmExports["la"];_emscripten_stack_get_current=wasmExports["ma"];___cxa_decrement_exception_refcount=wasmExports["na"];___cxa_increment_exception_refcount=wasmExports["oa"];___thrown_object_from_unwind_exception=wasmExports["pa"];___get_exception_message=wasmExports["qa"];memory=wasmMemory=wasmExports["aa"];__indirect_function_table=wasmTable=wasmExports["da"];___cpp_exception=wasmExports["fa"]}var wasmImports={V:OSD_MemInfo_getModuleHeapLength,D:___call_sighandler,R:___syscall_chmod,S:___syscall_faccessat,o:___syscall_fcntl64,O:___syscall_fstat64,H:___syscall_getdents64,U:___syscall_ioctl,M:___syscall_lstat64,J:___syscall_mkdirat,L:___syscall_newfstatat,u:___syscall_openat,s:___syscall_rmdir,N:___syscall_stat64,t:___syscall_unlinkat,G:__abort_js,h:__embind_finalize_value_object,y:__embind_register_bigint,_:__embind_register_bool,g:__embind_register_class,i:__embind_register_class_constructor,a:__embind_register_class_function,b:__embind_register_class_property,Y:__embind_register_emval,x:__embind_register_float,f:__embind_register_integer,l:__embind_register_iterable,d:__embind_register_memory_view,m:__embind_register_optional,Z:__embind_register_std_string,p:__embind_register_std_wstring,n:__embind_register_value_object,c:__embind_register_value_object_field,$:__embind_register_void,A:__emscripten_lookup_name,F:__emscripten_runtime_keepalive_clear,k:__emval_create_invoker,r:__emval_invoke,q:__emval_run_destructors,I:__localtime_js,z:__setitimer_js,T:__tzset_js,Q:_clock_time_get,P:_emscripten_date_now,W:_emscripten_get_callstack,C:_emscripten_get_heap_max,X:_emscripten_get_preloaded_image_data,B:_emscripten_resize_heap,e:_exit,j:_fd_close,w:_fd_read,K:_fd_seek,v:_fd_write,E:_proc_exit};function applySignatureConversions(wasmExports){wasmExports=Object.assign({},wasmExports);var makeWrapper_pp=f=>a0=>f(a0)>>>0;var makeWrapper_p=f=>()=>f()>>>0;wasmExports["ca"]=makeWrapper_pp(wasmExports["ca"]);wasmExports["ea"]=makeWrapper_pp(wasmExports["ea"]);wasmExports["la"]=makeWrapper_pp(wasmExports["la"]);wasmExports["ma"]=makeWrapper_p(wasmExports["ma"]);return wasmExports}function run(){if(runDependencies>0){dependenciesFulfilled=run;return}preRun();if(runDependencies>0){dependenciesFulfilled=run;return}function doRun(){Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve?.(Module);Module["onRuntimeInitialized"]?.();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(()=>{setTimeout(()=>Module["setStatus"](""),1);doRun()},1)}else{doRun()}}var wasmExports;wasmExports=await (createWasm());run();if(typeof Symbol!=="undefined"&&Symbol.dispose){const proto=Module["__proto__"]||Object.getPrototypeOf(Module);for(const key of Object.getOwnPropertyNames(Module)){const val=Module[key];if(typeof val==="function"&&val.prototype&&typeof val.prototype.delete==="function"&&!val.prototype[Symbol.dispose]){val.prototype[Symbol.dispose]=function(){if(!this.isDeleted()){this.delete()}}}}}if(runtimeInitialized){moduleRtn=Module}else{moduleRtn=new Promise((resolve,reject)=>{readyPromiseResolve=resolve;readyPromiseReject=reject})} +;return moduleRtn}export default createOcctWasm; diff --git a/apps/web/public/assets/occt/occt-wasm.wasm b/apps/web/public/assets/occt/occt-wasm.wasm new file mode 100644 index 0000000..83c144d Binary files /dev/null and b/apps/web/public/assets/occt/occt-wasm.wasm differ diff --git a/apps/web/src/app/globals.css b/apps/web/src/app/globals.css index 6407643..e84b4fc 100644 --- a/apps/web/src/app/globals.css +++ b/apps/web/src/app/globals.css @@ -19,6 +19,8 @@ --workplane-soft: rgba(154, 220, 240, 0.28); --shadow: 0 2px 6px rgba(35, 55, 75, 0.12); --font-ui: "Avenir Next", Avenir, "Helvetica Neue", Arial, sans-serif; + --editor-toolbar-height: 108px; + --editor-toolbar-tools-height: 76px; } * { @@ -732,8 +734,8 @@ button { } .editor-home-control svg { - width: 25px; - height: 25px; + width: 43px; + height: 43px; } .dashboard-settings-panel { @@ -964,17 +966,396 @@ button { position: fixed; inset: 0 0 auto 0; z-index: 19; - display: flex; - align-items: stretch; - height: 76px; - background: linear-gradient(180deg, #fbfcfd 0%, #f4f7f9 54%, #edf2f5 100%); + height: var(--editor-toolbar-height); + overflow: visible; + background: #f4f7f9; border-bottom: 1px solid #d2dce5; box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.92), 0 1px 2px rgba(32, 54, 72, 0.06); } +.edge-modifier-panel { + position: fixed; + top: calc(var(--editor-toolbar-height) + 14px); + right: 14px; + z-index: 46; + width: min(340px, calc(100vw - 28px)); + padding: 14px; + color: #274158; + background: rgba(250, 252, 254, 0.98); + border: 1px solid #c8d6e1; + border-radius: 12px; + box-shadow: 0 14px 38px rgba(30, 55, 74, 0.2); + backdrop-filter: blur(12px); +} + +.edge-modifier-header, +.edge-modifier-value-row, +.edge-modifier-quick-actions, +.edge-modifier-footer, +.edge-modifier-check { + display: flex; + align-items: center; +} + +.edge-modifier-header { + justify-content: space-between; + gap: 12px; + padding-bottom: 11px; + border-bottom: 1px solid #dce5ec; +} + +.edge-modifier-header strong, +.edge-modifier-header span { + display: block; +} + +.edge-modifier-header strong { + font-size: 16px; +} + +.edge-modifier-header span { + margin-top: 2px; + color: #6b7f90; + font-size: 11px; +} + +.edge-modifier-header button { + display: grid; + width: 30px; + height: 30px; + place-items: center; + color: #526b7e; + background: transparent; + border: 0; + border-radius: 7px; + cursor: pointer; +} + +.edge-modifier-header button:hover { + background: #e8eff4; +} + +.edge-modifier-target { + display: grid; + gap: 2px; + margin-top: 10px; + padding: 8px 10px; + color: #536b7e; + background: #eef3f7; + border: 1px solid #d8e3eb; + border-radius: 7px; +} + +.edge-modifier-target.grouped { + color: #17688a; + background: #eaf7fb; + border-color: #b8ddea; +} + +.edge-modifier-target strong { + font-size: 12px; +} + +.edge-modifier-target span { + font-size: 10px; + font-weight: 700; +} + +.edge-modifier-selection-help { + margin: 11px 0 8px; + color: #607486; + font-size: 11px; + line-height: 1.35; +} + +.edge-modifier-quick-actions { + gap: 7px; + margin-bottom: 12px; +} + +.edge-modifier-quick-actions button, +.edge-modifier-footer button { + min-height: 32px; + padding: 0 11px; + border: 1px solid #c4d3df; + border-radius: 7px; + font-size: 12px; + font-weight: 700; + cursor: pointer; +} + +.edge-modifier-quick-actions button { + color: #33556d; + background: #f4f8fb; +} + +.edge-modifier-history-actions { + display: grid; + gap: 6px; + margin-bottom: 12px; + padding: 8px; + background: #fff8ed; + border: 1px solid #efd7ad; + border-radius: 8px; +} + +.edge-modifier-history-actions button { + min-height: 31px; + color: #7a4d13; + background: white; + border: 1px solid #e0bd80; + border-radius: 7px; + font-size: 12px; + font-weight: 800; + cursor: pointer; +} + +.edge-modifier-history-actions button:disabled { + color: #9aa8b3; + background: #f4f6f8; + border-color: #d5dde4; + cursor: not-allowed; +} + +.edge-modifier-history-actions span { + color: #7a6851; + font-size: 10px; + line-height: 1.35; +} + +.edge-modifier-field { + display: block; + margin-top: 11px; + color: #415a6e; + font-size: 12px; + font-weight: 700; +} + +.edge-modifier-value-row { + gap: 7px; + margin-top: 5px; +} + +.edge-modifier-value-row input[type="range"] { + min-width: 0; + flex: 1; + accent-color: #139ed0; +} + +.edge-modifier-value-row input[type="number"], +.edge-modifier-field select { + height: 31px; + color: #263f53; + background: white; + border: 1px solid #bdcdda; + border-radius: 6px; +} + +.edge-modifier-value-row input[type="number"] { + width: 72px; + padding: 0 6px; +} + +.edge-modifier-field select { + width: 100%; + margin-top: 5px; + padding: 0 7px; +} + +.edge-modifier-check { + gap: 8px; + margin-top: 12px; + color: #415a6e; + font-size: 12px; + font-weight: 700; +} + +.edge-modifier-check input { + accent-color: #139ed0; +} + +.edge-modifier-error { + margin-top: 12px; + padding: 8px 9px; + color: #9f2730; + background: #fff0f1; + border: 1px solid #efc4c8; + border-radius: 7px; + font-size: 11px; + line-height: 1.35; +} + +.edge-modifier-footer { + justify-content: flex-end; + gap: 8px; + margin-top: 15px; + padding-top: 12px; + border-top: 1px solid #dce5ec; +} + +.edge-modifier-footer .secondary { + color: #486174; + background: white; +} + +.edge-modifier-footer .primary { + display: inline-flex; + align-items: center; + gap: 6px; + color: white; + background: #119dcc; + border-color: #0787b3; +} + +.edge-modifier-footer .primary:disabled { + opacity: 0.48; + cursor: default; +} + +.edge-modifier-spinner { + animation: edge-modifier-spin 0.8s linear infinite; +} + +@keyframes edge-modifier-spin { + to { transform: rotate(360deg); } +} + +.toolbar-mode-content { + position: absolute; + top: calc(var(--editor-toolbar-height) - var(--editor-toolbar-tools-height)); + right: 0; + bottom: 0; + left: 0; + display: flex; + width: 100%; + height: var(--editor-toolbar-tools-height); + align-items: stretch; + background: #f4f7f9; + border-top: 1px solid #d2dce5; +} + +.sketch-toolbar-ribbon { + display: flex; + width: 100%; + height: 100%; + align-items: stretch; + background: #f4f7f9; +} + +.sketch-create-section { + min-width: 150px; +} + +.sketch-edit-section { + min-width: 150px; +} + +.sketch-history-section { + min-width: 104px; +} + +.sketch-measure-section { + min-width: 58px; +} + +.sketch-start-section { + min-width: 250px; +} + +.sketch-finish-section { + min-width: 190px; + border-left: 1px solid rgba(203, 215, 226, 0.82); +} + +.sketch-tool-icon svg { + width: 30px; + height: 30px; + stroke-width: 1.8; +} + +.sketch-command-button { + display: inline-flex; + height: 43px; + min-width: 80px; + padding: 3px 9px; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 1px; + color: #39546a; + background: transparent; + border: 1px solid transparent; + border-radius: 3px; + cursor: pointer; + font-size: 10px; + font-weight: 800; +} + +.sketch-command-button svg { + width: 25px; + height: 25px; + stroke-width: 1.8; +} + +.sketch-command-button:hover:not(:disabled) { + color: #17405d; + background: #e7f5fb; + border-color: #bcdce8; +} + +.sketch-command-button.primary { + color: #126b8e; +} + +.sketch-command-button.cancel { + color: #835059; +} + +.sketch-command-button.disabled, +.sketch-command-button:disabled { + opacity: 0.32; + cursor: default; +} + +.toolbar-workspace-tabs { + position: absolute; + top: 0; + left: 10px; + z-index: 2; + display: flex; + width: max-content; + height: calc(var(--editor-toolbar-height) - var(--editor-toolbar-tools-height)); + align-items: stretch; +} + +.toolbar-workspace-tabs button { + flex: 0 0 auto; + min-width: 0; + padding: 0 18px; + color: #607589; + background: transparent; + border-bottom: 3px solid transparent; + cursor: pointer; + font-size: 12px; + font-weight: 900; + letter-spacing: 0.04em; + text-transform: uppercase; +} + +.toolbar-workspace-tabs button:hover { + color: #294a63; + background: rgba(255, 255, 255, 0.58); +} + +.toolbar-workspace-tabs button.active { + color: #264d68; + background: rgba(255, 255, 255, 0.8); + border-bottom-color: #159fd0; +} + .tool-group { display: flex; - height: 76px; + height: var(--editor-toolbar-tools-height); border-right: 1px solid #d7e0e8; } @@ -986,7 +1367,7 @@ button { position: relative; display: flex; min-width: 88px; - height: 76px; + height: var(--editor-toolbar-tools-height); flex-direction: column; justify-content: flex-start; border-right: 1px solid rgba(203, 215, 226, 0.82); @@ -1069,8 +1450,8 @@ button { .toolbar-icon .toolbar-sprite-icon, .toolbar-icon .vector-toolbar-sprite-icon, .toolbar-icon .toolbar-command-icon { - width: 32px; - height: 32px; + width: 43px; + height: 43px; } .toolbar-command-icon { @@ -1124,8 +1505,8 @@ button { } .toolbar-icon .toolbar-user-art-icon { - width: 40px; - height: 40px; + width: 43px; + height: 43px; } .toolbar-icon.disabled .toolbar-command-icon { @@ -1237,13 +1618,13 @@ button { } .shape-menu-trigger .vector-toolbar-sprite-icon { - width: 32px; - height: 32px; + width: 43px; + height: 43px; } .shape-menu-dropdown { position: absolute; - top: 76px; + top: var(--editor-toolbar-tools-height); left: 0; z-index: 60; width: 244px; @@ -1357,29 +1738,29 @@ button { } .action-buttons button .vector-toolbar-sprite-icon { - width: 32px; - height: 32px; + width: 43px; + height: 43px; } .action-buttons .action-icon-button .vector-toolbar-sprite-icon { - width: 32px; - height: 32px; + width: 43px; + height: 43px; } .action-buttons .action-icon-button .toolbar-command-icon { - width: 32px; - height: 32px; + width: 43px; + height: 43px; object-fit: contain; } .action-buttons .action-icon-button .toolbar-user-art-icon { - width: 40px; - height: 40px; + width: 43px; + height: 43px; } .top-dropdown { position: fixed; - top: 76px; + top: var(--editor-toolbar-height); left: 96px; z-index: 45; width: 218px; @@ -1410,7 +1791,7 @@ button { .top-action-panel { position: fixed; - top: 84px; + top: calc(var(--editor-toolbar-height) + 8px); right: 18px; z-index: 44; width: 322px; @@ -1560,7 +1941,7 @@ button { .editor-body { position: fixed; - inset: 76px 0 0 0; + inset: var(--editor-toolbar-height) 0 0 0; display: flex; min-height: 0; background: var(--background); @@ -1570,11 +1951,485 @@ button { position: relative; flex: 1; min-width: 0; - height: calc(100vh - 76px); + height: calc(100vh - var(--editor-toolbar-height)); overflow: hidden; background: var(--background); } +.sketch-workspace-stage { + position: relative; + flex: 1; + min-width: 0; + height: calc(100vh - var(--editor-toolbar-height)); + overflow: hidden; + background: #f8fbfc; +} + +.sketch-mode-badge { + position: absolute; + top: 8px; + left: 50%; + z-index: 9; + padding: 4px 10px; + color: #ffffff; + background: #37a95b; + border-radius: 12px; + box-shadow: 0 1px 3px rgba(25, 64, 43, 0.2); + font-size: 11px; + font-weight: 900; + transform: translateX(-50%); + pointer-events: none; +} + +.sketch-plate-wrap { + position: absolute; + inset: 14px 14px 42px; + display: grid; + place-items: center; + overflow: hidden; +} + +.sketch-plate { + display: block; + width: 100%; + height: 100%; + overflow: visible; + touch-action: none; + cursor: crosshair; +} + +.sketch-plate.panning { + cursor: grabbing; +} + +.sketch-plate.tool-select:not(.panning) { + cursor: default; +} + +.sketch-selection-marquee { + fill: rgba(0, 159, 227, 0.1); + stroke: rgba(0, 159, 227, 0.86); + stroke-width: 1; + stroke-dasharray: 4 3; + vector-effect: non-scaling-stroke; +} + +.sketch-plate-background { + fill: #ddf8ff; + stroke: none; +} + +.sketch-plate-border { + fill: none; + stroke: #4bbddf; + stroke-width: 1.5; + vector-effect: non-scaling-stroke; +} + +.sketch-grid line { + stroke-width: 1; + vector-effect: non-scaling-stroke; +} + +.sketch-grid .minor { + stroke: rgba(96, 204, 231, 0.46); +} + +.sketch-grid .major { + stroke: rgba(54, 174, 207, 0.68); +} + +.sketch-grid .axis { + stroke: #178db5; + stroke-width: 1.6; +} + +.sketch-reference-shapes rect, +.sketch-reference-shapes ellipse { + fill: rgba(207, 142, 42, 0.22); + stroke: rgba(188, 113, 18, 0.65); + stroke-width: 1.25; + vector-effect: non-scaling-stroke; +} + +.sketch-reference-images image { + cursor: move; + image-rendering: auto; + transition: opacity 100ms ease; +} + +.sketch-reference-images image:hover { + filter: saturate(1.08) contrast(1.03); +} + +.sketch-image-selection-box { + fill: none; + stroke: #009fe3; + stroke-width: 1.7; + stroke-dasharray: 5 3; + vector-effect: non-scaling-stroke; +} + +.sketch-image-resize-handle { + fill: #ffffff; + stroke: #0b75a3; + stroke-width: 1.5; + vector-effect: non-scaling-stroke; +} + +.sketch-image-resize-handle:hover { + fill: #ffb24b; + stroke: #9d4d00; +} + +.sketch-image-resize-handle.handle-nw, +.sketch-image-resize-handle.handle-se { + cursor: nwse-resize; +} + +.sketch-image-resize-handle.handle-ne, +.sketch-image-resize-handle.handle-sw { + cursor: nesw-resize; +} + +.sketch-image-resize-handle.handle-n, +.sketch-image-resize-handle.handle-s { + cursor: ns-resize; +} + +.sketch-image-resize-handle.handle-e, +.sketch-image-resize-handle.handle-w { + cursor: ew-resize; +} + +.sketch-image-dimension rect { + fill: rgba(255, 255, 255, 0.97); + stroke: rgba(127, 151, 168, 0.9); + stroke-width: 1; + vector-effect: non-scaling-stroke; + filter: drop-shadow(0 1px 2px rgba(25, 55, 76, 0.15)); +} + +.sketch-image-dimension text { + fill: #173b5a; + font-weight: 700; + text-anchor: middle; +} + +.sketch-profile-fills path { + fill: rgba(98, 148, 214, 0.2); + fill-rule: evenodd; + stroke: none; +} + +.sketch-segments path { + fill: none; + stroke: #173f60; + stroke-width: 2.5; + vector-effect: non-scaling-stroke; + pointer-events: stroke; + cursor: pointer; +} + +.sketch-segments path:hover, +.sketch-segments path.selected { + stroke: #ff8a00; + stroke-width: 4; +} + +.sketch-preview-line { + stroke: #169fce; + stroke-width: 2; + stroke-dasharray: 6 5; + vector-effect: non-scaling-stroke; +} + +.sketch-drag-handles line, +.sketch-curve-handles line { + stroke: #f08036; + stroke-width: 1.5; + vector-effect: non-scaling-stroke; +} + +.sketch-drag-handles circle, +.sketch-curve-handles circle { + fill: #ffffff; + stroke: #f08036; + stroke-width: 2; + vector-effect: non-scaling-stroke; + cursor: move; +} + +.sketch-points circle { + fill: #ffffff; + stroke: #143c5c; + stroke-width: 1.4; + vector-effect: non-scaling-stroke; + cursor: pointer; +} + +.sketch-points circle:hover, +.sketch-points circle.active { + fill: #71d7f0; + stroke: #086f98; +} + +.sketch-points circle.selected { + fill: #ffb24b; + stroke: #9d4d00; + stroke-width: 2; +} + +.sketch-cursor-point { + fill: #169fce; + stroke: #ffffff; + stroke-width: 1.5; + vector-effect: non-scaling-stroke; +} + +.sketch-segment-dimensions rect { + fill: rgba(255, 255, 255, 0.94); + stroke: rgba(220, 229, 235, 0.86); + stroke-width: 1; + vector-effect: non-scaling-stroke; +} + +.sketch-segment-dimensions text { + fill: #16283a; + font-weight: 500; + text-anchor: middle; +} + +.sketch-segment-dimensions.preview rect { + fill: rgba(255, 255, 255, 0.94); + stroke: rgba(220, 229, 235, 0.86); +} + +.sketch-segment-dimensions.preview text { + fill: #16283a; +} + +.sketch-measurement > line { + stroke: #d56100; + stroke-width: 2; + stroke-dasharray: 5 4; + vector-effect: non-scaling-stroke; + pointer-events: none; +} + +.sketch-measurement-pill { + cursor: pointer; +} + +.sketch-measurement-pill rect { + fill: rgba(255, 255, 255, 0.94); + stroke: rgba(220, 229, 235, 0.86); + stroke-width: 1; + vector-effect: non-scaling-stroke; +} + +.sketch-measurement-pill text { + fill: #16283a; + font-weight: 500; + text-anchor: middle; + pointer-events: none; +} + +.sketch-measurement-pill:hover rect { + fill: rgba(255, 255, 255, 0.98); + stroke: rgba(0, 159, 227, 0.85); +} + +.sketch-measurement-pill text.remove { + fill: #607589; +} + +.sketch-grid-settings { + padding: 4px 7px; + background: rgba(248, 251, 252, 0.92); + border: 1px solid #d6e2e9; + border-radius: 3px; +} + +.sketch-point-actions { + position: absolute; + bottom: 12px; + left: 50%; + z-index: 9; + display: flex; + gap: 5px; + padding: 5px; + background: rgba(255, 255, 255, 0.94); + border: 1px solid #cad9e3; + border-radius: 22px; + box-shadow: 0 3px 12px rgba(31, 55, 73, 0.16); + transform: translateX(-50%); +} + +.sketch-point-actions button { + display: inline-flex; + min-width: 62px; + height: 35px; + padding: 0 9px; + align-items: center; + justify-content: center; + gap: 4px; + color: #435d72; + background: transparent; + border: 1px solid transparent; + border-radius: 17px; + cursor: pointer; + font-size: 10px; + font-weight: 800; +} + +.sketch-point-actions button:hover { + color: #126b8e; + background: #e6f5fb; + border-color: #b9dce9; +} + +.sketch-point-actions svg { + width: 17px; + height: 17px; +} + +.sketch-image-inspector .shape-inspector-header strong { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.sketch-image-inspector .inspector-header-icon.danger:hover { + color: #c3262e; + background: #fff0f1; +} + +.sketch-image-preview-card { + display: grid; + place-items: center; + gap: 8px; + margin: 10px; + padding: 14px; + color: #6a7e90; + background: rgba(255, 255, 255, 0.98); + border-radius: 8px; + font-size: 12px; + font-weight: 750; +} + +.sketch-image-preview-card img { + display: block; + width: 100%; + height: 112px; + object-fit: contain; + background: + linear-gradient(45deg, #eef2f5 25%, transparent 25%), + linear-gradient(-45deg, #eef2f5 25%, transparent 25%), + linear-gradient(45deg, transparent 75%, #eef2f5 75%), + linear-gradient(-45deg, transparent 75%, #eef2f5 75%); + background-position: 0 0, 0 6px, 6px -6px, -6px 0; + background-size: 12px 12px; + border: 1px solid #d5e0e7; + border-radius: 4px; +} + +.sketch-image-inspector .property-card-header.static { + cursor: default; +} + +.sketch-image-inspector .property-card-header.static:hover { + color: #31465d; +} + +.sketch-image-range-row { + display: flex; + align-items: center; + gap: 7px; +} + +.sketch-image-number-input, +.sketch-image-position-field input { + width: 100%; + height: 31px; + padding: 0 10px; + color: #526174; + font: 700 14px/1 var(--font-ui); + background: #ffffff; + border: 1px solid #cbd6e1; + border-radius: 999px; + outline: 0; +} + +.sketch-image-number-input:focus, +.sketch-image-position-field input:focus { + border-color: #74bdf0; + box-shadow: 0 0 0 3px rgba(0, 156, 222, 0.14); +} + +.sketch-image-range-row span { + min-width: 26px; + color: #748596; + font-size: 12px; +} + +.sketch-image-range > input[type="range"] { + width: 100%; + height: 12px; + margin: 0; + appearance: none; + background: transparent; + cursor: pointer; +} + +.sketch-image-range > input[type="range"]::-webkit-slider-runnable-track { + height: 4px; + background: linear-gradient(to right, #00a6db 0 var(--slider-pos), #dbe1e7 var(--slider-pos) 100%); + border-radius: 999px; +} + +.sketch-image-range > input[type="range"]::-webkit-slider-thumb { + width: 13px; + height: 13px; + margin-top: -4.5px; + appearance: none; + background: #ffffff; + border: 2px solid #009fd7; + border-radius: 999px; + box-shadow: 0 1px 3px rgba(23, 59, 90, 0.22); +} + +.sketch-image-position-field { + display: grid; + grid-template-columns: 82px minmax(0, 1fr); + align-items: center; + gap: 9px; + color: #637286; + font-size: 14px; + font-weight: 650; +} + +.sketch-image-aspect-toggle { + display: flex; + min-height: 36px; + align-items: center; + justify-content: center; + gap: 7px; + color: #53697c; + background: #f7fafc; + border: 1px solid #d1dde5; + border-radius: 5px; + cursor: pointer; + font-size: 12px; + font-weight: 850; +} + +.sketch-image-aspect-toggle.active { + color: #0879a5; + background: #eaf8fc; + border-color: #90cee2; +} + .view-cube { position: absolute; top: 22px; @@ -1591,7 +2446,7 @@ button { text-transform: uppercase; filter: drop-shadow(0 2px 3px rgba(45, 64, 82, 0.14)); opacity: 0.9; - pointer-events: none; + pointer-events: auto; } .view-cube-inner { @@ -1613,10 +2468,25 @@ button { height: 58px; background: rgba(255, 255, 255, 0.9); border: 2px solid #cfd7df; + padding: 0; + color: inherit; + font: inherit; + cursor: pointer; + appearance: none; backface-visibility: hidden; box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.68); } +.cube-face:hover, +.cube-face:focus-visible { + color: #486379; + border-color: #8fb4ca; + outline: none; + box-shadow: + inset 0 0 0 1px rgba(255, 255, 255, 0.72), + 0 0 0 2px rgba(80, 168, 212, 0.18); +} + .cube-top { transform: rotateX(-90deg) translateZ(29px); background: rgba(248, 250, 252, 0.94); @@ -2442,6 +3312,31 @@ button { opacity: 0.55; } +.shape-inspector .edit-sketch-button { + display: block; + width: calc(100% - 20px); + height: 38px; + margin: 0 10px 12px; + color: #28516d; + background: #ffffff; + border: 1px solid #bfd2df; + border-radius: 5px; + cursor: pointer; + font-size: 13px; + font-weight: 900; +} + +.shape-inspector .edit-sketch-button:hover:not(:disabled) { + color: #0d7198; + background: #eaf7fb; + border-color: #8ecbdf; +} + +.shape-inspector .edit-sketch-button:disabled { + opacity: 0.45; + cursor: default; +} + .property-card { margin: 0 10px 10px; padding: 0 14px 18px; @@ -3047,7 +3942,7 @@ button { position: relative; z-index: 10; width: 276px; - height: calc(100vh - 76px); + height: calc(100vh - var(--editor-toolbar-height)); flex: 0 0 276px; overflow: hidden; background: var(--panel); @@ -3467,7 +4362,8 @@ button { } @media (max-width: 980px) { - .secondary-toolbar { + .toolbar-mode-content.geometry, + .toolbar-mode-content.sketch { overflow-x: auto; overflow-y: hidden; } @@ -3488,7 +4384,7 @@ button { .shape-menu-dropdown { position: fixed; - top: 76px; + top: var(--editor-toolbar-height); left: 10px; width: min(264px, calc(100vw - 20px)); } diff --git a/apps/web/src/components/SketchForgeEditor.tsx b/apps/web/src/components/SketchForgeEditor.tsx index b51be2f..c496b16 100644 --- a/apps/web/src/components/SketchForgeEditor.tsx +++ b/apps/web/src/components/SketchForgeEditor.tsx @@ -1,12 +1,13 @@ "use client"; -import { Download, X } from "lucide-react"; +import { Box, Check, Download, Eraser, ImagePlus, ListPlus, MousePointer2, PencilLine, Ruler, Spline, Waves, X } from "lucide-react"; import type manifoldModule from "manifold-3d"; import type { ManifoldToplevel } from "manifold-3d"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { ADDITION, Brush, Evaluator, HOLLOW_INTERSECTION, HOLLOW_SUBTRACTION, INTERSECTION, SUBTRACTION, type CSGOperation } from "three-bvh-csg"; import * as THREE from "three"; import { TextGeometry } from "three/examples/jsm/geometries/TextGeometry.js"; +import { RoundedBoxGeometry } from "three/examples/jsm/geometries/RoundedBoxGeometry.js"; import { FontLoader, type Font, type FontData } from "three/examples/jsm/loaders/FontLoader.js"; import { SVGLoader } from "three/examples/jsm/loaders/SVGLoader.js"; import droidMonoFontJson from "three/examples/fonts/droid/droid_sans_mono_regular.typeface.json"; @@ -19,6 +20,7 @@ import { manifoldModuleSource } from "@/generated/manifoldModuleSource"; import { manifoldWasmBase64 } from "@/generated/manifoldWasmBase64"; import { ToolbarAlignIcon, + ToolbarChamferIcon, ToolbarCaretDownIcon, ToolbarCopyIcon, ToolbarDuplicateIcon, @@ -29,6 +31,7 @@ import { ToolbarHomeIcon, ToolbarImportIcon, ToolbarIntersectionIcon, + ToolbarFilletIcon, ToolbarMirrorIcon, ToolbarPasteIcon, ToolbarRedoIcon, @@ -42,6 +45,8 @@ import { ToolbarWorkplaneIcon, } from "./icons"; import { WorkplaneViewport } from "./WorkplaneViewport"; +import { SketchWorkspace, type SketchMeasurement, type SketchSelection, type SketchTool } from "./SketchWorkspace"; +import { EdgeModifierPanel } from "./workplane/EdgeModifierPanel"; import { canonicalizeShape, cleanNearZero, @@ -50,6 +55,8 @@ import { mirroredAxisCount, mirrorSign, normalizeDegrees, + preservesEdgeTreatmentSize, + resizedImportedMeshPositions, serializeShapesForSync, shapeDepth, shapeWidth, @@ -59,16 +66,35 @@ import { createLocalId } from "@/lib/localIds"; import { projectExportFileName } from "@/lib/exportNames"; import { makeShapeFromAsset, sceneShape, toolbarShapeAssets, type ToolbarShapeAsset } from "@/lib/shapeCatalog"; import { importedShapeFromStl, importExtensionSupported } from "@/lib/stlImport"; -import type { AlignAxis, AlignHandleStatus, AlignTarget, GridSize, ShapeAsset, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge"; +import type { CadModifierDisplayEdge, CadModifierEdge, CadModifierKind, CadModifierMeshPart, CadModifierQuality, CadModifierWorkerRequest, CadModifierWorkerResponse } from "@/lib/cadModifierTypes"; +import type { AlignAxis, AlignHandleStatus, AlignTarget, GridSize, ShapeAsset, SketchImage, SketchPoint, SketchProfile, SketchSegment, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge"; export { importedShapeFromStl }; type TopPanel = "import" | "export" | "tips" | "profile" | "settings" | null; type ExportFormat = "stl" | "obj"; +type ToolbarMode = "geometry" | "sketch"; type Vec3 = [number, number, number]; type MeshData = { name: string; vertices: Vec3[]; faces: [number, number, number][] }; type Cuboid = { minX: number; maxX: number; minY: number; maxY: number; minZ: number; maxZ: number }; type ShapeUpdatePatch = Partial & { bakeTransform?: boolean }; +type WithoutRequestId = T extends unknown ? Omit : never; +type CadModifierWorkerPayload = WithoutRequestId; +type EdgeModifierSession = { + kind: CadModifierKind; + edges: CadModifierEdge[]; + selectedEdgeIds: number[]; + amount: number; + sharpAngle: number; + chamferAngle: number; + quality: CadModifierQuality; + tangentChain: boolean; + preserveEdgeSize: boolean; + busy: boolean; + prepared: boolean; + error: string | null; + preview: WorkplaneShape | null; +}; type ManifoldSolid = ReturnType; type DownloadResult = { mode: "browser" } | { mode: "folder"; path: string }; type GroupBuildResult = { @@ -106,6 +132,7 @@ type BooleanAutomationResult = { const DOWNLOAD_MODE_STORAGE_KEY = "sketchForge.downloadMode"; const DOWNLOAD_FOLDER_STORAGE_KEY = "sketchForge.downloadFolder"; const SHARED_CLIPBOARD_STORAGE_KEY = "sketchForge.clipboard"; +const SYSTEM_CLIPBOARD_PREFIX = "SKETCHFORGE3D/1\n"; const STATIC_EXPORT_BUILD = process.env.NEXT_PUBLIC_STATIC_EXPORT === "true"; declare global { @@ -122,6 +149,7 @@ const MIN_SHAPE_DIMENSION = 0.01; const MODEL_DIMENSION_PRECISION = 3; const IMPORTED_EXACT_BOOLEAN_TRIANGLE_LIMIT = 150000; const COPLANAR_BOOLEAN_RESCUE_DEGREES = 0.02; +const NORMAL_SELECTION_CAD_EDGE_MIN_ANGLE = 60; const svgLoader = new SVGLoader(); const booleanFontLoader = new FontLoader(); const booleanTextFonts: Record = { @@ -135,6 +163,208 @@ const booleanTextFonts: Record = { }; let manifoldRuntimePromise: Promise | null = null; +function emptySketchProfile(): SketchProfile { + return { points: [], segments: [], images: [] }; +} + +function cloneSketchProfile(profile: SketchProfile): SketchProfile { + return { + points: profile.points.map((point) => ({ + ...point, + handleIn: point.handleIn ? { ...point.handleIn } : undefined, + handleOut: point.handleOut ? { ...point.handleOut } : undefined, + })), + segments: profile.segments.map((segment) => ({ ...segment })), + images: (profile.images ?? []).map((image) => ({ ...image })), + }; +} + +type OrderedSketchStep = { segment: SketchProfile["segments"][number]; from: SketchPoint; to: SketchPoint }; +type OrderedSketchPath = { points: SketchPoint[]; steps: OrderedSketchStep[]; closed: boolean }; + +function orderedSketchPaths(profile: SketchProfile): OrderedSketchPath[] { + const pointById = new Map(profile.points.map((point) => [point.id, point])); + const adjacency = new Map>(); + profile.points.forEach((point) => adjacency.set(point.id, [])); + const validSegments = profile.segments.filter((segment) => { + if (!pointById.has(segment.startId) || !pointById.has(segment.endId) || segment.startId === segment.endId) return; + adjacency.get(segment.startId)?.push({ pointId: segment.endId, segment }); + adjacency.get(segment.endId)?.push({ pointId: segment.startId, segment }); + return true; + }); + const unvisited = new Set(validSegments.map((segment) => segment.id)); + const paths: OrderedSketchPath[] = []; + while (unvisited.size > 0) { + const seedId = unvisited.values().next().value as string | undefined; + const seed = validSegments.find((segment) => segment.id === seedId); + if (!seed) break; + const componentIds = new Set(); + const queue = [seed.startId, seed.endId]; + while (queue.length > 0) { + const id = queue.pop(); + if (!id || componentIds.has(id)) continue; + componentIds.add(id); + adjacency.get(id)?.forEach((entry) => queue.push(entry.pointId)); + } + const startId = [...componentIds].find((id) => (adjacency.get(id)?.filter((entry) => unvisited.has(entry.segment.id)).length ?? 0) === 1) ?? seed.startId; + const first = pointById.get(startId); + if (!first) { + unvisited.delete(seed.id); + continue; + } + const points = [first]; + const steps: OrderedSketchStep[] = []; + let currentId = startId; + for (let guard = 0; guard <= validSegments.length; guard += 1) { + const edge = adjacency.get(currentId)?.find((entry) => unvisited.has(entry.segment.id)); + if (!edge) break; + const from = pointById.get(currentId); + const to = pointById.get(edge.pointId); + if (!from || !to) break; + unvisited.delete(edge.segment.id); + steps.push({ segment: edge.segment, from, to }); + currentId = to.id; + if (currentId === startId) break; + points.push(to); + } + paths.push({ points, steps, closed: currentId === startId && steps.length >= 3 }); + } + return paths; +} + +function withSmoothSketchHandles(profile: SketchProfile) { + const next = cloneSketchProfile(profile); + const points = new Map(next.points.map((point) => [point.id, point])); + orderedSketchPaths(next).forEach((path) => { + path.points.forEach((sourcePoint, index) => { + const point = points.get(sourcePoint.id); + if (!point) return; + const previous = path.closed ? path.points[(index - 1 + path.points.length) % path.points.length] : path.points[Math.max(0, index - 1)]; + const following = path.closed ? path.points[(index + 1) % path.points.length] : path.points[Math.min(path.points.length - 1, index + 1)]; + const tangentX = (following.x - previous.x) / 6; + const tangentZ = (following.z - previous.z) / 6; + point.handleIn = { x: point.x - tangentX, z: point.z - tangentZ }; + point.handleOut = { x: point.x + tangentX, z: point.z + tangentZ }; + point.mode = "smooth"; + }); + }); + return next; +} + +function pointInSketchPolygon(point: THREE.Vector2, polygon: THREE.Vector2[]) { + let inside = false; + for (let index = 0, previous = polygon.length - 1; index < polygon.length; previous = index, index += 1) { + const currentPoint = polygon[index]; + const previousPoint = polygon[previous]; + const crosses = currentPoint.y > point.y !== previousPoint.y > point.y; + if (crosses && point.x < ((previousPoint.x - currentPoint.x) * (point.y - currentPoint.y)) / (previousPoint.y - currentPoint.y) + currentPoint.x) { + inside = !inside; + } + } + return inside; +} + +function shapeFromSketchProfile(profile: SketchProfile, height: number, existing?: WorkplaneShape | null) { + const closedPaths = orderedSketchPaths(profile).filter((path) => path.closed); + if (closedPaths.length === 0) return null; + const profilePoints = closedPaths.flatMap((path) => path.points); + const minX = Math.min(...profilePoints.map((point) => point.x)); + const maxX = Math.max(...profilePoints.map((point) => point.x)); + const minZ = Math.min(...profilePoints.map((point) => point.z)); + const maxZ = Math.max(...profilePoints.map((point) => point.z)); + const centerX = (minX + maxX) / 2; + const centerZ = (minZ + maxZ) / 2; + const width = Math.max(0.01, maxX - minX); + const depth = Math.max(0.01, maxZ - minZ); + const safeHeight = Math.max(0.01, height); + const outlineRecords = closedPaths.map((path) => { + const outline = new THREE.Shape(); + const first = path.points[0]; + outline.moveTo(first.x - centerX, -(first.z - centerZ)); + path.steps.forEach(({ segment, from, to }) => { + const forward = segment.startId === from.id; + const control1 = forward ? from.handleOut : from.handleIn; + const control2 = forward ? to.handleIn : to.handleOut; + if (segment.kind !== "line" && control1 && control2) { + outline.bezierCurveTo( + control1.x - centerX, + -(control1.z - centerZ), + control2.x - centerX, + -(control2.z - centerZ), + to.x - centerX, + -(to.z - centerZ), + ); + } else { + outline.lineTo(to.x - centerX, -(to.z - centerZ)); + } + }); + outline.closePath(); + const polygon = outline.extractPoints(16).shape; + return { outline, polygon, area: Math.abs(THREE.ShapeUtils.area(polygon)) }; + }); + const sortedOutlines = [...outlineRecords].sort((a, b) => b.area - a.area); + const outlines: THREE.Shape[] = []; + sortedOutlines.forEach((record) => { + const sample = record.polygon[0]; + const parent = sample + ? sortedOutlines + .filter((candidate) => candidate !== record && candidate.area > record.area && pointInSketchPolygon(sample, candidate.polygon)) + .sort((a, b) => a.area - b.area)[0] + : undefined; + if (parent) parent.outline.holes.push(record.outline); + else outlines.push(record.outline); + }); + const hasCurves = profile.segments.some((segment) => segment.kind === "bezier" || segment.kind === "smooth"); + const longestHandle = profile.points.reduce((longest, point) => Math.max( + longest, + point.handleIn ? Math.hypot(point.handleIn.x - point.x, point.handleIn.z - point.z) : 0, + point.handleOut ? Math.hypot(point.handleOut.x - point.x, point.handleOut.z - point.z) : 0, + ), 0); + const curveScale = Math.max(width, depth, longestHandle * 2); + const curveSegments = hasCurves ? Math.min(256, Math.max(32, Math.ceil(curveScale * 1.25))) : 1; + const geometry = new THREE.ExtrudeGeometry(outlines, { depth: safeHeight, bevelEnabled: false, steps: 1, curveSegments }); + geometry.rotateX(-Math.PI / 2); + geometry.computeVertexNormals(); + geometry.computeBoundingBox(); + const geometryBox = geometry.boundingBox; + const meshWidth = Math.max(0.01, geometryBox ? geometryBox.max.x - geometryBox.min.x : width); + const meshDepth = Math.max(0.01, geometryBox ? geometryBox.max.z - geometryBox.min.z : depth); + const meshCenterX = centerX + (geometryBox ? (geometryBox.min.x + geometryBox.max.x) / 2 : 0); + const meshCenterZ = centerZ + (geometryBox ? (geometryBox.min.z + geometryBox.max.z) / 2 : 0); + const meshGeometry = geometry.index ? geometry.toNonIndexed() : geometry; + const position = meshGeometry.getAttribute("position"); + const normal = meshGeometry.getAttribute("normal"); + const positions = Array.from(position.array as ArrayLike); + const normals = normal ? Array.from(normal.array as ArrayLike) : undefined; + if (meshGeometry !== geometry) meshGeometry.dispose(); + geometry.dispose(); + return canonicalizeShape({ + id: existing?.id ?? createLocalId("sketch-extrusion"), + name: existing?.name ?? "Sketch extrusion", + kind: "mesh", + color: existing?.color ?? "#d41721", + hole: existing?.hole, + x: meshCenterX, + z: meshCenterZ, + elevation: 0, + size: Math.max(meshWidth, meshDepth), + width: meshWidth, + depth: meshDepth, + height: safeHeight, + rotation: 0, + importedMesh: { + positions, + normals, + baseWidth: meshWidth, + baseDepth: meshDepth, + baseHeight: safeHeight, + triangleCount: Math.floor(positions.length / 9), + sourceFormat: "json", + }, + sketchProfile: cloneSketchProfile(profile), + } satisfies WorkplaneShape); +} + function cleanModelDimension(value: number) { return Math.max(MIN_SHAPE_DIMENSION, Number(value.toFixed(MODEL_DIMENSION_PRECISION))); } @@ -147,12 +377,9 @@ function meshYawDegrees(shape: WorkplaneShape) { return isRoundPrimitive && isCircular ? 0 : shape.rotation; } -function readSharedClipboard() { - if (typeof window === "undefined") { - return []; - } +function parseClipboardShapes(serialized: string) { try { - const parsed = JSON.parse(window.localStorage.getItem(SHARED_CLIPBOARD_STORAGE_KEY) ?? "[]"); + const parsed = JSON.parse(serialized); if (!Array.isArray(parsed)) { return []; } @@ -168,11 +395,68 @@ function readSharedClipboard() { } } +function readSharedClipboard() { + if (typeof window === "undefined") { + return []; + } + return parseClipboardShapes(window.localStorage.getItem(SHARED_CLIPBOARD_STORAGE_KEY) ?? "[]"); +} + +async function readSystemClipboard() { + if (typeof navigator === "undefined" || !navigator.clipboard?.readText) { + return []; + } + try { + const value = await navigator.clipboard.readText(); + return value.startsWith(SYSTEM_CLIPBOARD_PREFIX) + ? parseClipboardShapes(value.slice(SYSTEM_CLIPBOARD_PREFIX.length)) + : []; + } catch { + return []; + } +} + +function copyTextWithSelectionFallback(value: string) { + if (typeof document === "undefined" || typeof document.execCommand !== "function") { + return; + } + const previousFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null; + const textarea = document.createElement("textarea"); + textarea.value = value; + textarea.readOnly = true; + textarea.setAttribute("aria-hidden", "true"); + textarea.style.position = "fixed"; + textarea.style.left = "-10000px"; + textarea.style.top = "0"; + textarea.style.opacity = "0"; + document.body.appendChild(textarea); + textarea.select(); + try { + document.execCommand("copy"); + } catch { + // The modern Clipboard API below may still succeed. + } + textarea.remove(); + previousFocus?.focus({ preventScroll: true }); +} + function writeSharedClipboard(shapes: WorkplaneShape[]) { if (typeof window === "undefined") { return; } - window.localStorage.setItem(SHARED_CLIPBOARD_STORAGE_KEY, serializeShapesForSync(shapes)); + const serialized = serializeShapesForSync(shapes); + try { + window.localStorage.setItem(SHARED_CLIPBOARD_STORAGE_KEY, serialized); + } catch { + // The system clipboard can still carry large models if local storage is full. + } + const systemPayload = `${SYSTEM_CLIPBOARD_PREFIX}${serialized}`; + copyTextWithSelectionFallback(systemPayload); + if (navigator.clipboard?.writeText) { + void navigator.clipboard.writeText(systemPayload).catch(() => { + // Same-origin tabs still have the local-storage fallback. + }); + } } function base64ToUint8Array(value: string) { @@ -465,6 +749,54 @@ function automationNormalGroupedObject(overrides: Partial = {}) return group ? { ...group, id: "normal-group", name: "Normal grouped object", ...overrides } : null; } +function automationSelectionOutlineRegressionShape() { + const geometries: THREE.BufferGeometry[] = [ + new RoundedBoxGeometry(30, 20, 20, 8, 4).translate(-15, 10, 0), + new THREE.BoxGeometry(16, 20, 20).translate(18, 10, 0), + ]; + const positions: number[] = []; + const normals: number[] = []; + + geometries.forEach((geometry) => { + const nonIndexed = geometry.index ? geometry.toNonIndexed() : geometry; + nonIndexed.computeVertexNormals(); + positions.push(...Array.from(nonIndexed.getAttribute("position").array as ArrayLike)); + normals.push(...Array.from(nonIndexed.getAttribute("normal").array as ArrayLike)); + if (nonIndexed !== geometry) { + nonIndexed.dispose(); + } + geometry.dispose(); + }); + + return canonicalizeShape( + sceneShape({ + id: "selection-outline-regression", + name: "Selection outline regression", + kind: "mesh", + color: "#d41721", + x: 0, + z: 0, + width: 56, + depth: 20, + height: 20, + size: 56, + importedMesh: { + positions, + normals, + baseWidth: 56, + baseDepth: 20, + baseHeight: 20, + triangleCount: Math.floor(positions.length / 9), + sourceFormat: "json", + }, + groupedShapes: [ + sceneShape({ id: "rounded-child", name: "Rounded child", kind: "box", color: "#d41721", x: -15, width: 30, depth: 20, height: 20, radius: 4 }), + sceneShape({ id: "box-child", name: "Box child", kind: "box", color: "#d41721", x: 18, width: 16, depth: 20, height: 20 }), + ], + }), + ); +} + function booleanAutomationDynamicScene(caseId: string): { label: string; shapes: WorkplaneShape[] } | null { const requestedKeys = Object.keys(booleanAutomationShapeConfigs).filter((key) => key !== "cube" && key !== "cylinder"); const allNormalKeys = Object.keys(booleanAutomationShapeConfigs); @@ -542,6 +874,29 @@ function booleanAutomationDynamicScene(caseId: string): { label: string; shapes: function booleanAutomationScene(caseId: string): { label: string; shapes: WorkplaneShape[] } | null { const rotatedHole = () => automationHoleBox({ rotation: 32 }); + if (caseId === "selection-outline-regression") { + return { + label: "segmented rounded mesh selection outline", + shapes: [automationSelectionOutlineRegressionShape()], + }; + } + if (caseId === "locked-align-pair") { + return { + label: "locked alignment reference pair", + shapes: [ + sceneShape({ id: "locked-anchor", name: "Locked cube", kind: "box", color: "#d41721", x: 24, z: 10, width: 20, depth: 20, height: 20, locked: true }), + sceneShape({ id: "moving-cube", name: "Moving cube", kind: "box", color: "#ef7f1a", x: -24, z: -18, width: 12, depth: 12, height: 12 }), + ], + }; + } + if (caseId === "normal-group") { + const group = groupedShape([ + sceneShape({ id: "modifier-base", name: "Base", kind: "box", color: "#d41721", width: 54, depth: 38, height: 7 }), + sceneShape({ id: "modifier-upright", name: "Upright", kind: "box", color: "#d41721", x: 8, width: 14, depth: 14, height: 40, elevation: 4 }), + sceneShape({ id: "modifier-rail", name: "Rail", kind: "box", color: "#d41721", x: -7, z: 5, width: 32, depth: 10, height: 13, elevation: 4 }), + ]); + return group ? { label: "overlapping normal solid group", shapes: [group] } : null; + } if (caseId === "straight-hole-stl-group") { const group = automationNormalGroupedObject(); return group @@ -704,6 +1059,303 @@ function sanitizeName(name: string) { return name.replace(/[^a-z0-9_-]+/gi, "_") || "shape"; } +function meshDataToCadTransfer(mesh: MeshData) { + const positions = new Float32Array(mesh.vertices.length * 3); + mesh.vertices.forEach((vertex, index) => positions.set(vertex, index * 3)); + const indices = new Uint32Array(mesh.faces.length * 3); + mesh.faces.forEach((face, index) => indices.set(face, index * 3)); + return { positions, indices }; +} + +function cadBrepTransformForShape(shape: WorkplaneShape) { + const frame = shape.cadBrepFrame; + if (!frame) return undefined; + const oldCenter = new THREE.Vector3(frame.x, frame.elevation + frame.height / 2, frame.z); + const currentCenter = new THREE.Vector3(shape.x, (shape.elevation ?? 0) + shape.height / 2, shape.z); + const rotation = new THREE.Quaternion().setFromEuler(new THREE.Euler( + THREE.MathUtils.degToRad(shape.rotationX ?? 0), + THREE.MathUtils.degToRad(shape.rotation ?? 0), + THREE.MathUtils.degToRad(shape.rotationZ ?? 0), + "XYZ", + )); + const scale = new THREE.Vector3( + shapeWidth(shape) / Math.max(0.001, frame.width) * mirrorSign(shape.mirrorX), + shape.height / Math.max(0.001, frame.height) * mirrorSign(shape.mirrorY), + shapeDepth(shape) / Math.max(0.001, frame.depth) * mirrorSign(shape.mirrorZ), + ); + const matrix = new THREE.Matrix4() + .compose(currentCenter, rotation, scale) + .multiply(new THREE.Matrix4().makeTranslation(-oldCenter.x, -oldCenter.y, -oldCenter.z)); + const elements = matrix.elements; + const result = [ + elements[0], elements[4], elements[8], elements[12], + elements[1], elements[5], elements[9], elements[13], + elements[2], elements[6], elements[10], elements[14], + ]; + const identity = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0]; + return result.every((value, index) => Math.abs(value - identity[index]) < 1e-9) ? undefined : result; +} + +function shapeFromCadMesh( + source: WorkplaneShape, + positions: Float32Array, + normals: Float32Array, + indices: Uint32Array, + brep: string, +): WorkplaneShape | null { + if (positions.length < 9 || indices.length < 3) return null; + let minX = Number.POSITIVE_INFINITY; + let minY = Number.POSITIVE_INFINITY; + let minZ = Number.POSITIVE_INFINITY; + let maxX = Number.NEGATIVE_INFINITY; + let maxY = Number.NEGATIVE_INFINITY; + let maxZ = Number.NEGATIVE_INFINITY; + for (let index = 0; index < positions.length; index += 3) { + minX = Math.min(minX, positions[index]); + minY = Math.min(minY, positions[index + 1]); + minZ = Math.min(minZ, positions[index + 2]); + maxX = Math.max(maxX, positions[index]); + maxY = Math.max(maxY, positions[index + 1]); + maxZ = Math.max(maxZ, positions[index + 2]); + } + if (![minX, minY, minZ, maxX, maxY, maxZ].every(Number.isFinite)) return null; + const centerX = (minX + maxX) / 2; + const centerZ = (minZ + maxZ) / 2; + const rawWidth = Math.max(MIN_SHAPE_DIMENSION, maxX - minX); + const rawHeight = Math.max(MIN_SHAPE_DIMENSION, maxY - minY); + const rawDepth = Math.max(MIN_SHAPE_DIMENSION, maxZ - minZ); + const flattenedPositions: number[] = []; + const flattenedNormals: number[] = []; + for (let index = 0; index < indices.length; index += 1) { + const vertex = indices[index] * 3; + flattenedPositions.push(positions[vertex] - centerX, positions[vertex + 1] - minY, positions[vertex + 2] - centerZ); + if (normals.length >= vertex + 3) flattenedNormals.push(normals[vertex], normals[vertex + 1], normals[vertex + 2]); + } + const width = cleanModelDimension(rawWidth); + const height = cleanModelDimension(rawHeight); + const depth = cleanModelDimension(rawDepth); + return canonicalizeShape({ + ...source, + kind: "mesh", + x: cleanNearZero(centerX, 0.0005), + z: cleanNearZero(centerZ, 0.0005), + elevation: cleanNearZero(minY, 0.0005), + width, + depth, + height, + size: Math.max(width, depth), + rotation: 0, + rotationX: 0, + rotationZ: 0, + mirrorX: undefined, + mirrorY: undefined, + mirrorZ: undefined, + radius: undefined, + importedMesh: { + positions: flattenedPositions, + normals: flattenedNormals.length === flattenedPositions.length ? flattenedNormals : undefined, + baseWidth: rawWidth, + baseDepth: rawDepth, + baseHeight: rawHeight, + triangleCount: Math.floor(indices.length / 3), + sourceFormat: "json", + }, + imagePlate: undefined, + cadBrep: brep, + cadBrepFrame: { + x: cleanNearZero(centerX, 0.0005), + z: cleanNearZero(centerZ, 0.0005), + elevation: cleanNearZero(minY, 0.0005), + width, + depth, + height, + }, + }); +} + +function cadEdgeEndpoint(edge: CadModifierEdge, end: "start" | "end") { + const offset = end === "start" ? 0 : edge.points.length - 3; + return new THREE.Vector3(edge.points[offset], edge.points[offset + 1], edge.points[offset + 2]); +} + +function cadEdgeTangentAt(edge: CadModifierEdge, endpoint: THREE.Vector3) { + const start = cadEdgeEndpoint(edge, "start"); + const end = cadEdgeEndpoint(edge, "end"); + if (endpoint.distanceToSquared(start) <= endpoint.distanceToSquared(end)) { + const next = new THREE.Vector3(edge.points[3], edge.points[4], edge.points[5]); + return next.sub(start).normalize(); + } + const offset = Math.max(0, edge.points.length - 6); + const previous = new THREE.Vector3(edge.points[offset], edge.points[offset + 1], edge.points[offset + 2]); + return previous.sub(end).normalize(); +} + +function tangentCadEdgeChain(edges: CadModifierEdge[], startId: number, allowedIds: Set) { + const edgeById = new Map(edges.map((edge) => [edge.id, edge])); + const selected = new Set([startId]); + const queue = [startId]; + const tolerance = 0.025; + while (queue.length > 0) { + const id = queue.shift() as number; + const edge = edgeById.get(id); + if (!edge) continue; + const endpoints = [cadEdgeEndpoint(edge, "start"), cadEdgeEndpoint(edge, "end")]; + edges.forEach((candidate) => { + if (selected.has(candidate.id) || !allowedIds.has(candidate.id)) return; + const candidateEndpoints = [cadEdgeEndpoint(candidate, "start"), cadEdgeEndpoint(candidate, "end")]; + const shared = endpoints.find((point) => candidateEndpoints.some((other) => point.distanceTo(other) <= tolerance)); + if (!shared) return; + const a = cadEdgeTangentAt(edge, shared); + const b = cadEdgeTangentAt(candidate, shared); + const deviation = (Math.acos(Math.max(-1, Math.min(1, Math.abs(a.dot(b))))) * 180) / Math.PI; + if (deviation <= 16) { + selected.add(candidate.id); + queue.push(candidate.id); + } + }); + } + return [...selected]; +} + +function cadDisplayEdgesAfterTreatment(shape: WorkplaneShape, session: EdgeModifierSession) { + const removed = new Set(session.selectedEdgeIds); + const elevation = shape.elevation ?? 0; + return session.edges + .filter((edge) => { + const effectiveAngle = Math.min(edge.angle, 180 - edge.angle); + return edge.manifold + && !edge.boundary + && effectiveAngle + 1e-3 >= Math.max(session.sharpAngle, NORMAL_SELECTION_CAD_EDGE_MIN_ANGLE) + && !removed.has(edge.id); + }) + .map((edge) => ({ + points: edge.points.map((value, index) => { + if (index % 3 === 0) return value - shape.x; + if (index % 3 === 1) return value - elevation; + return value - shape.z; + }), + })); +} + +function cadDisplayEdgesForShape(shape: WorkplaneShape, edges: CadModifierDisplayEdge[]) { + const elevation = shape.elevation ?? 0; + return edges + .filter((edge) => edge.points.length >= 6) + .map((edge) => ({ + points: edge.points.map((value, index) => { + if (index % 3 === 0) return value - shape.x; + if (index % 3 === 1) return value - elevation; + return value - shape.z; + }), + })); +} + +function cloneWorkplaneShapeSnapshot(shape: WorkplaneShape): WorkplaneShape { + return JSON.parse(JSON.stringify(canonicalizeShape(shape))) as WorkplaneShape; +} + +function edgeTreatmentLabel(feature: NonNullable[number]) { + const size = `${Number(feature.amount.toFixed(2))} mm`; + return `${feature.kind === "fillet" ? "fillet" : "chamfer"} (${size}, ${feature.edgeCount} edge${feature.edgeCount === 1 ? "" : "s"})`; +} + +function edgeTreatmentFeatureCount(shape: WorkplaneShape): number { + return (shape.edgeTreatments?.length ?? 0) + (shape.groupedShapes?.reduce((total, child) => total + edgeTreatmentFeatureCount(child), 0) ?? 0); +} + +function reversibleEdgeTreatmentCount(shape: WorkplaneShape): number { + return (shape.edgeTreatmentHistory?.length ?? 0) + (shape.groupedShapes?.reduce((total, child) => total + reversibleEdgeTreatmentCount(child), 0) ?? 0); +} + +function latestEdgeTreatmentTimestamp(shape: WorkplaneShape): number { + const own = shape.edgeTreatmentHistory?.reduce((latest, entry) => Math.max(latest, entry.createdAt), Number.NEGATIVE_INFINITY) ?? Number.NEGATIVE_INFINITY; + const child = shape.groupedShapes?.reduce((latest, entry) => Math.max(latest, latestEdgeTreatmentTimestamp(entry)), Number.NEGATIVE_INFINITY) ?? Number.NEGATIVE_INFINITY; + return Math.max(own, child); +} + +function latestOwnEdgeTreatmentEntry(shape: WorkplaneShape) { + return (shape.edgeTreatmentHistory ?? []).reduce[number] | null>( + (latest, entry) => (!latest || entry.createdAt >= latest.createdAt ? entry : latest), + null, + ); +} + +function restoreOwnLastEdgeTreatment(shape: WorkplaneShape, entry: NonNullable[number]) { + const before = cloneWorkplaneShapeSnapshot(entry.before); + return canonicalizeShape({ + ...before, + id: shape.id, + name: shape.name, + color: shape.color, + hole: shape.hole || undefined, + x: shape.x, + z: shape.z, + elevation: shape.elevation, + width: shapeWidth(shape), + depth: shapeDepth(shape), + height: shape.height, + size: shape.size, + rotation: shape.rotation, + rotationX: shape.rotationX, + rotationZ: shape.rotationZ, + mirrorX: shape.mirrorX, + mirrorY: shape.mirrorY, + mirrorZ: shape.mirrorZ, + locked: shape.locked, + hidden: shape.hidden, + }); +} + +async function restoreLastEdgeTreatmentInShape(shape: WorkplaneShape): Promise<{ shape: WorkplaneShape; label: string } | null> { + const ownEntry = latestOwnEdgeTreatmentEntry(shape); + const childCandidates = (shape.groupedShapes ?? []) + .map((child, index) => ({ index, createdAt: latestEdgeTreatmentTimestamp(child) })) + .filter((entry) => Number.isFinite(entry.createdAt)); + const latestChild = childCandidates.reduce<{ index: number; createdAt: number } | null>( + (latest, entry) => (!latest || entry.createdAt > latest.createdAt ? entry : latest), + null, + ); + + if (ownEntry && (!latestChild || ownEntry.createdAt >= latestChild.createdAt)) { + return { + shape: restoreOwnLastEdgeTreatment(shape, ownEntry), + label: edgeTreatmentLabel(ownEntry.feature), + }; + } + + if (!latestChild || !shape.groupedShapes?.length) { + return null; + } + + const restoredChildren = restoreGroupedChildren(shape); + const child = restoredChildren[latestChild.index]; + if (!child) { + return null; + } + const restoredChild = await restoreLastEdgeTreatmentInShape(child); + if (!restoredChild) { + return null; + } + + restoredChildren[latestChild.index] = restoredChild.shape; + const rebuilt = await buildGroupedShapeFromSelection(restoredChildren); + if (!rebuilt.group) { + return null; + } + + return { + shape: canonicalizeShape({ + ...rebuilt.group, + id: shape.id, + name: shape.name, + hole: shape.hole || rebuilt.group.hole, + locked: shape.locked, + hidden: shape.hidden, + }), + label: restoredChild.label, + }; +} + function transformMesh(mesh: MeshData, shape: WorkplaneShape): MeshData { const centerY = shape.height / 2; const matrix = new THREE.Matrix4().makeRotationFromEuler( @@ -1077,7 +1729,9 @@ function geometryMeshForShape(shape: WorkplaneShape): MeshData | null { switch (shape.kind) { case "box": - geometry = new THREE.BoxGeometry(width, height, depth); + geometry = shape.radius && shape.radius > 0 + ? new RoundedBoxGeometry(width, height, depth, Math.max(1, shape.steps ?? 10), shape.radius) + : new THREE.BoxGeometry(width, height, depth); break; case "cylinder": geometry = new THREE.CylinderGeometry(1, 1, height, shape.sides ?? 96, shape.segments ?? 1); @@ -1185,12 +1839,10 @@ function importedMeshForShape(shape: WorkplaneShape): MeshData { return transformMesh(boxMesh(shape), shape); } - const sx = shape.width / Math.max(0.001, mesh.baseWidth); - const sy = shape.height / Math.max(0.001, mesh.baseHeight); - const sz = shape.depth / Math.max(0.001, mesh.baseDepth); + const resizedPositions = resizedImportedMeshPositions(shape); const vertices: Vec3[] = []; - for (let i = 0; i < mesh.positions.length; i += 3) { - vertices.push([mesh.positions[i] * sx, mesh.positions[i + 1] * sy, mesh.positions[i + 2] * sz]); + for (let i = 0; i < resizedPositions.length; i += 3) { + vertices.push([resizedPositions[i], resizedPositions[i + 1], resizedPositions[i + 2]]); } const faces: [number, number, number][] = []; @@ -1730,6 +2382,11 @@ function alignedShapesForSelection( return { nextShapes, moved }; } +function effectiveAlignmentAnchorId(selection: WorkplaneShape[], requestedAnchorId: string | null) { + return selection.find((shape) => shape.locked)?.id + ?? (requestedAnchorId && selection.some((shape) => shape.id === requestedAnchorId) ? requestedAnchorId : null); +} + function mirrorAxisLabel(axis: AlignAxis) { return axis === "x" ? "left-right" : axis === "z" ? "front-back" : "top-bottom"; } @@ -2895,16 +3552,14 @@ function primitiveManifoldForShape(runtime: ManifoldToplevel, shape: WorkplaneSh ); } - if (shape.kind === "cylinder" || shape.kind === "cone" || shape.kind === "pyramid") { - const sides = shape.kind === "pyramid" ? 4 : shape.sides ?? 96; + if (shape.kind === "cylinder" || shape.kind === "cone") { + const sides = shape.sides ?? 96; const topRadiusScale = shape.kind === "cone" ? shape.baseRadius ? (shape.topRadius ?? 0) / shape.baseRadius : 0 - : shape.kind === "pyramid" - ? 0 - : 1; + : 1; return transformedPrimitiveManifold( runtime, runtime.Manifold.cylinder(1, 1, topRadiusScale, sides, true), @@ -3962,6 +4617,11 @@ function debugShapeSummary(shape: WorkplaneShape): Record { mirrorZ: Boolean(shape.mirrorZ), importedTriangles: shape.importedMesh?.triangleCount ?? 0, imagePlate: shape.imagePlate ? `${shape.imagePlate.pixelWidth}x${shape.imagePlate.pixelHeight}` : null, + edgeTreatments: shape.edgeTreatments ?? [], + cadDisplayEdgeCount: shape.cadDisplayEdges?.length ?? null, + cadDisplayEdgesVersion: shape.cadDisplayEdgesVersion ?? null, + edgeResizeMode: shape.edgeResizeMode ?? "scale", + cadBrepLength: shape.cadBrep?.length ?? 0, groupedCount: shape.groupedShapes?.length ?? 0, children: shape.groupedShapes?.map(debugShapeSummary) ?? [], }; @@ -3975,6 +4635,10 @@ function compactShapeSummary(shape: WorkplaneShape, index: number) { `${index}:${shape.kind}${shape.hole ? "H" : "S"}${shape.importedMesh ? "I" : ""}${shape.imagePlate ? "P" : ""}`, `g${shape.groupedShapes?.length ?? 0}`, `tri${shape.importedMesh?.triangleCount ?? 0}`, + `edge${shape.edgeTreatments?.map((feature) => `${feature.kind}:${feature.amount}:${feature.edgeCount}:${feature.chamferAngle ?? ""}`).join("|") ?? ""}`, + `viewEdges${shape.cadDisplayEdges?.length ?? "auto"}v${shape.cadDisplayEdgesVersion ?? 0}`, + `edgeResize${shape.edgeResizeMode ?? "scale"}`, + `brep${shape.cadBrep?.length ?? 0}`, `p${Number(shape.x.toFixed(2))},${Number(shape.z.toFixed(2))},${Number((shape.elevation ?? 0).toFixed(2))}`, `d${Number(shapeWidth(shape).toFixed(2))}x${Number(shapeDepth(shape).toFixed(2))}x${Number(shape.height.toFixed(2))}`, `r${Number((shape.rotationX ?? 0).toFixed(1))},${Number(shape.rotation.toFixed(1))},${Number((shape.rotationZ ?? 0).toFixed(1))}`, @@ -3993,6 +4657,21 @@ function projectShapesFingerprint(shapes: WorkplaneShape[]) { `clr${shape.color}`, `txt${shape.text ?? ""}`, `mesh${shape.importedMesh?.positions.length ?? 0}:${shape.importedMesh?.normals?.length ?? 0}`, + `sketch${shape.sketchProfile ? JSON.stringify({ + points: shape.sketchProfile.points, + segments: shape.sketchProfile.segments, + images: (shape.sketchProfile.images ?? []).map((image) => ({ + id: image.id, + name: image.name, + x: image.x, + z: image.z, + width: image.width, + depth: image.depth, + opacity: image.opacity, + lockAspect: image.lockAspect, + sourceLength: image.dataUrl.length, + })), + }) : ""}`, ].join(","), ) .join(";"); @@ -4024,6 +4703,7 @@ export function SketchForgeEditor({ const [shapes, setShapes] = useState(() => initialShapes.map(canonicalizeShape)); const [selectedIds, setSelectedIds] = useState([]); const [clipboard, setClipboard] = useState([]); + const [systemClipboardSupported, setSystemClipboardSupported] = useState(false); const [history, setHistory] = useState([[]]); const [historyIndex, setHistoryIndex] = useState(0); const [placementElevation, setPlacementElevation] = useState(0); @@ -4038,6 +4718,7 @@ export function SketchForgeEditor({ const [activeMode, setActiveMode] = useState("3D Design"); const [notice, setNotice] = useState("Ready"); const fileInputRef = useRef(null); + const sketchImageInputRef = useRef(null); const booleanAutomationRunRef = useRef(null); const projectHydratingRef = useRef(false); const projectInteractionActiveRef = useRef(false); @@ -4053,6 +4734,89 @@ export function SketchForgeEditor({ const interactionHistoryChangedRef = useRef(false); const interactionHistoryTimerRef = useRef(null); const [projectInteractionActive, setProjectInteractionActive] = useState(false); + const [toolbarMode, setToolbarMode] = useState("geometry"); + const [sketchActive, setSketchActive] = useState(false); + const [sketchTool, setSketchTool] = useState("line"); + const [sketchProfile, setSketchProfile] = useState(() => emptySketchProfile()); + const [sketchHistory, setSketchHistory] = useState([emptySketchProfile()]); + const [sketchHistoryIndex, setSketchHistoryIndex] = useState(0); + const [sketchActivePointId, setSketchActivePointId] = useState(null); + const [sketchSelection, setSketchSelection] = useState(null); + const [sketchMeasureStart, setSketchMeasureStart] = useState(null); + const [sketchMeasurement, setSketchMeasurement] = useState(null); + const [editingSketchShapeId, setEditingSketchShapeId] = useState(null); + const [edgeModifier, setEdgeModifier] = useState(null); + const cadModifierWorkerRef = useRef(null); + const cadModifierRequestRef = useRef(0); + const cadModifierPrepareRef = useRef(0); + const cadModifierLatestPreviewRef = useRef(0); + const cadModifierBaseShapeRef = useRef(null); + const cadModifierBaseFingerprintRef = useRef(""); + + useEffect(() => { + const worker = new Worker(new URL("../workers/cadModifier.worker.ts", import.meta.url), { type: "module" }); + cadModifierWorkerRef.current = worker; + worker.onmessage = (event: MessageEvent) => { + const message = event.data; + if (message.type === "ready") { + if (message.requestId !== cadModifierPrepareRef.current) return; + setEdgeModifier((current) => current ? { + ...current, + edges: message.edges, + selectedEdgeIds: [], + busy: false, + prepared: true, + error: message.selectableEdgeIds.length ? null : "No sharp manifold edges were found at this threshold", + } : current); + if (message.selectableEdgeIds.length) setNotice("Select highlighted edges, then adjust the preview"); + return; + } + if (message.type === "preview") { + if (message.requestId !== cadModifierLatestPreviewRef.current) return; + const base = cadModifierBaseShapeRef.current; + const rawPreview = base ? shapeFromCadMesh(base, message.positions, message.normals, message.indices, message.brep) : null; + const preview = rawPreview ? { + ...rawPreview, + cadDisplayEdges: cadDisplayEdgesForShape(rawPreview, message.displayEdges), + cadDisplayEdgesVersion: 2 as const, + } : null; + setEdgeModifier((current) => current ? { + ...current, + preview, + busy: false, + error: preview ? null : "The CAD kernel returned an empty edge treatment", + } : current); + if (preview) setNotice("Edge treatment preview ready"); + return; + } + if (message.type === "error") { + if (message.requestId < cadModifierLatestPreviewRef.current) return; + setEdgeModifier((current) => current ? { ...current, busy: false, preview: null, error: message.message } : current); + setNotice("Edge treatment needs adjustment"); + } + }; + worker.onerror = () => { + setEdgeModifier((current) => current ? { ...current, busy: false, preview: null, error: "The CAD worker could not start" } : current); + }; + return () => { + worker.terminate(); + cadModifierWorkerRef.current = null; + }; + }, []); + + const invalidateCadModifierSession = useCallback(() => { + const wasActive = cadModifierBaseShapeRef.current !== null; + if (!wasActive) return false; + const requestId = cadModifierRequestRef.current + 1; + cadModifierRequestRef.current = requestId; + cadModifierLatestPreviewRef.current = requestId; + cadModifierPrepareRef.current = requestId; + cadModifierWorkerRef.current?.postMessage({ type: "dispose", requestId } satisfies CadModifierWorkerRequest); + cadModifierBaseShapeRef.current = null; + cadModifierBaseFingerprintRef.current = ""; + setEdgeModifier(null); + return true; + }, []); useEffect(() => { const warmBooleanRuntime = () => { @@ -4089,6 +4853,7 @@ export function SketchForgeEditor({ }, []); useEffect(() => { + setSystemClipboardSupported(Boolean(navigator.clipboard)); setClipboard(readSharedClipboard()); const onStorage = (event: StorageEvent) => { if (event.key === SHARED_CLIPBOARD_STORAGE_KEY) { @@ -4110,17 +4875,47 @@ export function SketchForgeEditor({ const selectedShapes = useMemo(() => shapes.filter((shape) => selectedIds.includes(shape.id)), [selectedIds, shapes]); const selectedShape = selectedShapes.at(-1) ?? null; const hasSelection = selectedShapes.length > 0; + const modifierAvailableEdgeIds = useMemo( + () => edgeModifier ? edgeModifier.edges.filter((edge) => edge.manifold && !edge.boundary && edge.angle + 1e-3 >= edgeModifier.sharpAngle).map((edge) => edge.id) : [], + [edgeModifier?.edges, edgeModifier?.sharpAngle], + ); + const edgeModifierMaxAmount = useMemo(() => { + const source = cadModifierBaseShapeRef.current ?? selectedShape; + if (!source) return 10; + const smallestDimension = Math.min(shapeWidth(source), shapeDepth(source), source.height); + return Math.max(0.05, smallestDimension * (edgeModifier?.kind === "chamfer" ? 0.99 : 0.5)); + }, [edgeModifier, selectedShape]); + const selectedEdgeFeatureCount = useMemo(() => selectedShape ? edgeTreatmentFeatureCount(selectedShape) : 0, [selectedShape]); + const selectedReversibleEdgeFeatureCount = useMemo(() => selectedShape ? reversibleEdgeTreatmentCount(selectedShape) : 0, [selectedShape]); + const toggleModifierEdge = useCallback((id: number, singleEdge = false) => { + setEdgeModifier((current) => { + if (!current) return current; + const allowed = new Set(current.edges.filter((edge) => edge.boundary || edge.angle + 1e-3 >= current.sharpAngle).map((edge) => edge.id)); + if (!allowed.has(id)) return current; + const ids = current.tangentChain && !singleEdge ? tangentCadEdgeChain(current.edges, id, allowed) : [id]; + const next = new Set(current.selectedEdgeIds); + const remove = ids.every((edgeId) => next.has(edgeId)); + ids.forEach((edgeId) => remove ? next.delete(edgeId) : next.add(edgeId)); + return { ...current, selectedEdgeIds: [...next], preview: null, busy: next.size > 0, error: next.size ? null : "Select at least one highlighted edge" }; + }); + }, []); const exportableShapeCount = useMemo(() => (hasSelection ? selectedShapes : shapes).filter((shape) => !shape.hole).length, [hasSelection, selectedShapes, shapes]); const exportScopeLabel = hasSelection ? "selected" : "total"; - const alignHandleStatuses = useMemo(() => (alignMode ? alignmentStatuses(selectedShapes, alignAnchorId) : []), [alignAnchorId, alignMode, selectedShapes]); + const effectiveAlignAnchorId = useMemo( + () => effectiveAlignmentAnchorId(selectedShapes, alignAnchorId), + [alignAnchorId, selectedShapes], + ); + const alignHandleStatuses = useMemo(() => (alignMode ? alignmentStatuses(selectedShapes, effectiveAlignAnchorId) : []), [alignMode, effectiveAlignAnchorId, selectedShapes]); const viewportShapes = useMemo( () => - alignMode && alignPreview - ? alignedShapesForSelection(shapes, selectedIds, selectedShapes, alignAnchorId, alignPreview.axis, alignPreview.target).nextShapes + edgeModifier?.preview && cadModifierBaseShapeRef.current + ? shapes.map((shape) => shape.id === cadModifierBaseShapeRef.current?.id ? edgeModifier.preview as WorkplaneShape : shape) + : alignMode && alignPreview + ? alignedShapesForSelection(shapes, selectedIds, selectedShapes, effectiveAlignAnchorId, alignPreview.axis, alignPreview.target).nextShapes : mirrorMode && mirrorPreviewAxis ? mirroredShapesForSelection(shapes, selectedIds, selectedShapes, mirrorPreviewAxis).nextShapes : shapes, - [alignAnchorId, alignMode, alignPreview, mirrorMode, mirrorPreviewAxis, selectedIds, selectedShapes, shapes], + [alignMode, alignPreview, edgeModifier?.preview, effectiveAlignAnchorId, mirrorMode, mirrorPreviewAxis, selectedIds, selectedShapes, shapes], ); const debugState = useMemo( () => @@ -4315,6 +5110,420 @@ export function SketchForgeEditor({ [historyIndex, selectedIds, syncProjectShapes], ); + const removeLastEdgeTreatment = useCallback(async () => { + if (!selectedShape) { + setNotice("Select a shape with an edge feature first"); + return; + } + if (selectedShape.locked) { + setNotice("Unlock the shape before removing an edge feature"); + return; + } + const restored = await restoreLastEdgeTreatmentInShape(selectedShape); + if (!restored) { + setNotice(selectedEdgeFeatureCount > 0 ? "This edge feature has no stored undo history" : "No edge feature to remove"); + return; + } + invalidateCadModifierSession(); + commitShapes( + shapes.map((shape) => shape.id === selectedShape.id ? restored.shape : shape), + restored.shape.id, + `Removed ${restored.label}`, + ); + setNotice(`Removed ${restored.label}`); + }, [commitShapes, invalidateCadModifierSession, selectedEdgeFeatureCount, selectedShape, shapes]); + + const commitSketchProfile = useCallback( + (next: SketchProfile, message?: string) => { + const snapshot = cloneSketchProfile(next); + setSketchProfile(snapshot); + setSketchHistory((current) => { + const trimmed = current.slice(0, sketchHistoryIndex + 1); + return [...trimmed, cloneSketchProfile(snapshot)]; + }); + setSketchHistoryIndex(sketchHistoryIndex + 1); + if (message) setNotice(message); + }, + [sketchHistoryIndex], + ); + + const beginSketch = useCallback((profile?: SketchProfile, editingId: string | null = null) => { + const initial = cloneSketchProfile(profile ?? emptySketchProfile()); + setToolbarMode("sketch"); + setSketchActive(true); + setSketchTool(profile?.segments.length ? "select" : "line"); + setSketchProfile(initial); + setSketchHistory([cloneSketchProfile(initial)]); + setSketchHistoryIndex(0); + setSketchActivePointId(null); + setSketchSelection(null); + setSketchMeasureStart(null); + setSketchMeasurement(null); + setEditingSketchShapeId(editingId); + setNotice(editingId ? "Editing sketch profile" : "Sketch started: place the first point"); + }, []); + + const beginSketchEdit = useCallback(() => { + if (selectedShapes.length !== 1 || !selectedShape?.sketchProfile) { + setNotice("Select one shape created from a sketch to edit it"); + return; + } + beginSketch(selectedShape.sketchProfile, selectedShape.id); + }, [beginSketch, selectedShape, selectedShapes.length]); + + const cancelSketch = useCallback(() => { + setSketchActive(false); + setSketchActivePointId(null); + setSketchSelection(null); + setSketchMeasureStart(null); + setSketchMeasurement(null); + setEditingSketchShapeId(null); + setNotice("Sketch cancelled"); + }, []); + + const sketchUndo = useCallback(() => { + if (sketchHistoryIndex <= 0) { + setNotice("Nothing to undo in this sketch"); + return; + } + const nextIndex = sketchHistoryIndex - 1; + setSketchHistoryIndex(nextIndex); + setSketchProfile(cloneSketchProfile(sketchHistory[nextIndex] ?? emptySketchProfile())); + setSketchActivePointId(null); + setSketchSelection(null); + setNotice("Sketch undo"); + }, [sketchHistory, sketchHistoryIndex]); + + const sketchRedo = useCallback(() => { + if (sketchHistoryIndex >= sketchHistory.length - 1) { + setNotice("Nothing to redo in this sketch"); + return; + } + const nextIndex = sketchHistoryIndex + 1; + setSketchHistoryIndex(nextIndex); + setSketchProfile(cloneSketchProfile(sketchHistory[nextIndex] ?? emptySketchProfile())); + setSketchActivePointId(null); + setSketchSelection(null); + setNotice("Sketch redo"); + }, [sketchHistory, sketchHistoryIndex]); + + const setActiveSketchTool = useCallback((tool: SketchTool) => { + setSketchTool(tool); + setSketchActivePointId(null); + setSketchSelection(null); + if (tool !== "measure") setSketchMeasureStart(null); + const messages: Record = { + line: "Line: click points to draw straight segments", + bezier: "Bézier: click and drag points to pull curve handles", + smooth: "Smooth curve: click points to build a flowing path", + select: "Select: edit sketch geometry or place and scale reference images", + refine: "Refine: click a segment to add a point, or a point to remove it", + erase: "Erase: click a point or segment to remove it", + measure: "Measure: choose two points", + }; + setNotice(messages[tool]); + }, []); + + const measureSketchPoint = useCallback( + (point: SketchPoint) => { + if (!sketchMeasureStart) { + setSketchMeasureStart({ ...point }); + setSketchMeasurement(null); + setNotice("Choose the second measurement point"); + return; + } + const measurement = { start: { ...sketchMeasureStart }, end: { ...point } }; + setSketchMeasurement(measurement); + setSketchMeasureStart(null); + setNotice(`Measured ${Number(Math.hypot(measurement.end.x - measurement.start.x, measurement.end.z - measurement.start.z).toFixed(2))} mm`); + }, + [sketchMeasureStart], + ); + + const clearSketchMeasurement = useCallback(() => { + setSketchMeasureStart(null); + setSketchMeasurement(null); + setNotice("Sketch measurement removed"); + }, []); + + const connectSketchPoint = useCallback( + (pointId: string, profile = sketchProfile) => { + if (!["line", "bezier", "smooth"].includes(sketchTool)) return profile; + const curveKind = sketchTool as NonNullable; + if (!sketchActivePointId) { + setSketchActivePointId(pointId); + setSketchSelection({ kind: "point", id: pointId }); + return profile; + } + if (sketchActivePointId === pointId) return profile; + const duplicate = profile.segments.some( + (segment) => + (segment.startId === sketchActivePointId && segment.endId === pointId) || + (segment.startId === pointId && segment.endId === sketchActivePointId), + ); + const next = duplicate + ? profile + : { + ...profile, + segments: [...profile.segments, { id: createLocalId("sketch-segment"), startId: sketchActivePointId, endId: pointId, kind: curveKind }], + }; + const smoothed = sketchTool === "smooth" ? withSmoothSketchHandles(next) : next; + const closed = orderedSketchPaths(smoothed).some((path) => path.closed && path.steps.some((step) => step.segment.startId === sketchActivePointId || step.segment.endId === sketchActivePointId)); + if (!duplicate) commitSketchProfile(smoothed, closed ? "Profile closed—edit the path or finish the sketch" : "Sketch segment added"); + setSketchActivePointId(closed ? null : pointId); + setSketchSelection({ kind: "point", id: pointId }); + if (closed) setSketchTool("select"); + return smoothed; + }, + [commitSketchProfile, sketchActivePointId, sketchProfile, sketchTool], + ); + + const addSketchPlanePoint = useCallback( + (position: { x: number; z: number }, handles?: { handleIn: { x: number; z: number }; handleOut: { x: number; z: number } }) => { + if (sketchTool === "measure") { + measureSketchPoint({ id: "measure", ...position }); + return; + } + if (!["line", "bezier", "smooth"].includes(sketchTool)) return; + const curveKind = sketchTool as NonNullable; + const existing = sketchProfile.points.find((point) => Math.hypot(point.x - position.x, point.z - position.z) < 0.0001); + if (existing) { + connectSketchPoint(existing.id); + return; + } + const point: SketchPoint = { + id: createLocalId("sketch-point"), + ...position, + ...(handles ?? {}), + mode: sketchTool === "line" ? "corner" : sketchTool === "smooth" ? "smooth" : handles ? "smooth" : "corner", + }; + const next: SketchProfile = { ...sketchProfile, points: [...sketchProfile.points, point] }; + if (sketchActivePointId) { + next.segments = [...next.segments, { id: createLocalId("sketch-segment"), startId: sketchActivePointId, endId: point.id, kind: curveKind }]; + } + const prepared = sketchTool === "smooth" ? withSmoothSketchHandles(next) : next; + commitSketchProfile(prepared, sketchActivePointId ? "Sketch point and segment added" : "Sketch point added"); + setSketchActivePointId(point.id); + setSketchSelection({ kind: "point", id: point.id }); + }, + [commitSketchProfile, connectSketchPoint, measureSketchPoint, sketchActivePointId, sketchProfile, sketchTool], + ); + + const pressSketchPoint = useCallback( + (id: string) => { + const point = sketchProfile.points.find((entry) => entry.id === id); + if (!point) return; + if (sketchTool === "measure") { + measureSketchPoint(point); + setSketchSelection({ kind: "point", id }); + return; + } + if (sketchTool === "select") { + setSketchSelection({ kind: "point", id }); + setSketchActivePointId(null); + return; + } + connectSketchPoint(id); + }, + [connectSketchPoint, measureSketchPoint, sketchProfile.points, sketchTool], + ); + + const deleteSketchPoint = useCallback( + (id: string) => { + const connected = sketchProfile.segments.filter((segment) => segment.startId === id || segment.endId === id); + const neighboringIds = connected.map((segment) => segment.startId === id ? segment.endId : segment.startId); + const remainingSegments = sketchProfile.segments.filter((segment) => segment.startId !== id && segment.endId !== id); + if (neighboringIds.length === 2 && neighboringIds[0] !== neighboringIds[1]) { + const duplicate = remainingSegments.some((segment) => + (segment.startId === neighboringIds[0] && segment.endId === neighboringIds[1]) || + (segment.startId === neighboringIds[1] && segment.endId === neighboringIds[0]), + ); + if (!duplicate) { + remainingSegments.push({ + id: createLocalId("sketch-segment"), + startId: neighboringIds[0], + endId: neighboringIds[1], + kind: connected.every((segment) => segment.kind === "line") ? "line" : connected.some((segment) => segment.kind === "smooth") ? "smooth" : "bezier", + }); + } + } + const next = { + ...sketchProfile, + points: sketchProfile.points.filter((point) => point.id !== id), + segments: remainingSegments, + }; + commitSketchProfile(next.segments.some((segment) => segment.kind === "smooth") ? withSmoothSketchHandles(next) : next, "Sketch point removed"); + if (sketchActivePointId === id) setSketchActivePointId(null); + setSketchSelection(null); + }, + [commitSketchProfile, sketchActivePointId, sketchProfile], + ); + + const deleteSketchSegment = useCallback( + (id: string) => { + commitSketchProfile({ ...sketchProfile, segments: sketchProfile.segments.filter((segment) => segment.id !== id) }, "Sketch line removed"); + setSketchActivePointId(null); + setSketchSelection(null); + }, + [commitSketchProfile, sketchProfile], + ); + + const updateSketchImage = useCallback((id: string, patch: Partial, message = "Sketch image updated") => { + const image = (sketchProfile.images ?? []).find((entry) => entry.id === id); + if (!image) return; + commitSketchProfile({ + ...sketchProfile, + images: (sketchProfile.images ?? []).map((entry) => entry.id === id ? { ...entry, ...patch } : entry), + }, message); + setSketchSelection({ kind: "image", id }); + setSketchActivePointId(null); + }, [commitSketchProfile, sketchProfile]); + + const deleteSketchImage = useCallback((id: string) => { + if (!(sketchProfile.images ?? []).some((image) => image.id === id)) return; + commitSketchProfile({ + ...sketchProfile, + images: (sketchProfile.images ?? []).filter((image) => image.id !== id), + }, "Sketch image removed"); + setSketchSelection(null); + }, [commitSketchProfile, sketchProfile]); + + const addSketchImageFile = useCallback(async (file: File) => { + if (!sketchActive || sketchTool !== "select") { + setNotice("Choose Select before adding a sketch image"); + return; + } + if (!file.type.startsWith("image/")) { + setNotice("Choose a PNG, JPG, WebP, GIF, or other image file"); + return; + } + try { + const prepared = await prepareImportedImage(file); + const dimensions = imagePlateDimensions(prepared.pixelWidth, prepared.pixelHeight); + const image: SketchImage = { + id: createLocalId("sketch-image"), + name: file.name.replace(/\.[^.]+$/, "") || "Sketch image", + ...prepared, + x: 0, + z: 0, + width: dimensions.width, + depth: dimensions.depth, + opacity: 0.55, + lockAspect: true, + }; + commitSketchProfile({ ...sketchProfile, images: [...(sketchProfile.images ?? []), image] }, `Added ${file.name} to the sketch`); + setSketchSelection({ kind: "image", id: image.id }); + setSketchActivePointId(null); + } catch (error) { + setNotice(error instanceof Error ? error.message : "The sketch image could not be added"); + } + }, [commitSketchProfile, sketchActive, sketchProfile, sketchTool]); + + const deleteSelectedSketchEntity = useCallback(() => { + if (!sketchSelection) { + setNotice("Select a sketch point or segment to remove it"); + return; + } + if (sketchSelection.kind === "point") deleteSketchPoint(sketchSelection.id); + else if (sketchSelection.kind === "segment") deleteSketchSegment(sketchSelection.id); + else if (sketchSelection.kind === "image") deleteSketchImage(sketchSelection.id); + else { + const pointIds = new Set(sketchSelection.pointIds); + const segmentIds = new Set(sketchSelection.segmentIds); + const imageIds = new Set(sketchSelection.imageIds ?? []); + commitSketchProfile({ + ...sketchProfile, + points: sketchProfile.points.filter((point) => !pointIds.has(point.id)), + segments: sketchProfile.segments.filter((segment) => !segmentIds.has(segment.id) && !pointIds.has(segment.startId) && !pointIds.has(segment.endId)), + images: (sketchProfile.images ?? []).filter((image) => !imageIds.has(image.id)), + }, "Selected sketch geometry removed"); + setSketchActivePointId(null); + setSketchSelection(null); + } + }, [commitSketchProfile, deleteSketchImage, deleteSketchPoint, deleteSketchSegment, sketchProfile, sketchSelection]); + + const moveSketchPoint = useCallback((id: string, position: { x: number; z: number }) => { + const current = sketchProfile.points.find((point) => point.id === id); + if (!current) return; + const deltaX = position.x - current.x; + const deltaZ = position.z - current.z; + const next = { + ...sketchProfile, + points: sketchProfile.points.map((point) => point.id === id ? { + ...point, + ...position, + handleIn: point.handleIn ? { x: point.handleIn.x + deltaX, z: point.handleIn.z + deltaZ } : undefined, + handleOut: point.handleOut ? { x: point.handleOut.x + deltaX, z: point.handleOut.z + deltaZ } : undefined, + } : point), + }; + commitSketchProfile(next, "Sketch point moved"); + }, [commitSketchProfile, sketchProfile]); + + const moveSketchHandle = useCallback((id: string, handle: "in" | "out", position: { x: number; z: number }) => { + const next = cloneSketchProfile(sketchProfile); + const point = next.points.find((entry) => entry.id === id); + if (!point) return; + if (handle === "in") point.handleIn = { ...position }; + else point.handleOut = { ...position }; + if (point.mode === "smooth") { + const opposite = { x: point.x * 2 - position.x, z: point.z * 2 - position.z }; + if (handle === "in") point.handleOut = opposite; + else point.handleIn = opposite; + } + commitSketchProfile(next, "Curve handle adjusted"); + }, [commitSketchProfile, sketchProfile]); + + const setSketchPointMode = useCallback((id: string, mode: "corner" | "smooth" | "split") => { + let next = cloneSketchProfile(sketchProfile); + const point = next.points.find((entry) => entry.id === id); + if (!point) return; + point.mode = mode; + if (mode === "corner") { + point.handleIn = undefined; + point.handleOut = undefined; + next.segments = next.segments.map((segment) => segment.startId === id || segment.endId === id ? { ...segment, kind: "line" } : segment); + } else { + next.segments = next.segments.map((segment) => segment.startId === id || segment.endId === id ? { ...segment, kind: "bezier" } : segment); + if (!point.handleIn || !point.handleOut) next = withSmoothSketchHandles(next); + const updated = next.points.find((entry) => entry.id === id); + if (updated) updated.mode = mode; + } + commitSketchProfile(next, mode === "corner" ? "Made corner" : mode === "smooth" ? "Made smooth" : "Curve handles split"); + }, [commitSketchProfile, sketchProfile]); + + const insertSketchPoint = useCallback((segmentId: string, position: { x: number; z: number }) => { + const segment = sketchProfile.segments.find((entry) => entry.id === segmentId); + if (!segment) return; + const point: SketchPoint = { id: createLocalId("sketch-point"), ...position, mode: segment.kind === "line" ? "corner" : "smooth" }; + let next: SketchProfile = { + ...sketchProfile, + points: [...sketchProfile.points, point], + segments: sketchProfile.segments.flatMap((entry) => entry.id === segmentId ? [ + { ...entry, id: createLocalId("sketch-segment"), endId: point.id }, + { ...entry, id: createLocalId("sketch-segment"), startId: point.id }, + ] : [entry]), + }; + if (segment.kind === "smooth") next = withSmoothSketchHandles(next); + commitSketchProfile(next, "Point added to path"); + setSketchSelection({ kind: "point", id: point.id }); + setSketchTool("select"); + }, [commitSketchProfile, sketchProfile]); + + const finishSketch = useCallback(() => { + const existing = editingSketchShapeId ? shapes.find((shape) => shape.id === editingSketchShapeId) ?? null : null; + const height = existing?.height ?? 10; + const extruded = shapeFromSketchProfile(sketchProfile, height, existing); + if (!extruded) { + setNotice("Close at least one profile before finishing the sketch"); + return; + } + const nextShapes = existing ? shapes.map((shape) => (shape.id === existing.id ? extruded : shape)) : [...shapes, extruded]; + commitShapes(nextShapes, extruded.id, existing ? "Sketch updated" : "Sketch created at 10 mm height"); + setSketchActive(false); + setEditingSketchShapeId(null); + setToolbarMode("geometry"); + }, [commitShapes, editingSketchShapeId, shapes, sketchProfile]); + useEffect(() => { if (!projectId) { lastProjectIdRef.current = null; @@ -4464,15 +5673,16 @@ export function SketchForgeEditor({ setNotice(`Copied ${selectedShapes.length} shape${selectedShapes.length === 1 ? "" : "s"}`); }, [hasSelection, selectedShapes]); - const pasteShape = useCallback(() => { + const pasteShape = useCallback(async () => { + const systemClipboard = await readSystemClipboard(); const sharedClipboard = readSharedClipboard(); - const sourceClipboard = sharedClipboard.length > 0 ? sharedClipboard : clipboard; + const sourceClipboard = systemClipboard.length > 0 ? systemClipboard : sharedClipboard.length > 0 ? sharedClipboard : clipboard; if (sourceClipboard.length === 0) { - setNotice("Clipboard is empty"); + setNotice("SketchForge clipboard is empty"); return; } - if (sharedClipboard.length > 0 && serializeShapesForSync(sharedClipboard) !== serializeShapesForSync(clipboard)) { - setClipboard(sharedClipboard); + if (serializeShapesForSync(sourceClipboard) !== serializeShapesForSync(clipboard)) { + setClipboard(sourceClipboard); } const pasted = sourceClipboard.map((shape) => ({ ...shape, @@ -4480,34 +5690,42 @@ export function SketchForgeEditor({ x: Math.min(110, shape.x + 12), z: Math.min(110, shape.z + 12), })); - commitShapes([...shapes, ...pasted], pasted.map((shape) => shape.id), `Pasted ${pasted.length} shape${pasted.length === 1 ? "" : "s"}`); - }, [clipboard, commitShapes, shapes]); + commitShapes([...shapesRef.current, ...pasted], pasted.map((shape) => shape.id), `Pasted ${pasted.length} shape${pasted.length === 1 ? "" : "s"}`); + }, [clipboard, commitShapes]); const undo = useCallback(() => { + const modifierCancelled = invalidateCadModifierSession(); if (historyIndex <= 0) { - setNotice("Nothing to undo"); + setNotice(modifierCancelled ? "Edge modifier cancelled" : "Nothing to undo"); return; } const nextIndex = historyIndex - 1; const nextShapes = (history[nextIndex] ?? []).map(canonicalizeShape); + historyIndexRef.current = nextIndex; + shapesRef.current = nextShapes; setHistoryIndex(nextIndex); setShapes(nextShapes); setSelectedIds((current) => current.filter((id) => nextShapes.some((shape) => shape.id === id))); - setNotice("Undo"); - }, [history, historyIndex]); + syncProjectShapes(nextShapes); + setNotice(modifierCancelled ? "Edge modifier cancelled · Undo" : "Undo"); + }, [history, historyIndex, invalidateCadModifierSession, syncProjectShapes]); const redo = useCallback(() => { if (historyIndex >= history.length - 1) { setNotice("Nothing to redo"); return; } + const modifierCancelled = invalidateCadModifierSession(); const nextIndex = historyIndex + 1; const nextShapes = (history[nextIndex] ?? []).map(canonicalizeShape); + historyIndexRef.current = nextIndex; + shapesRef.current = nextShapes; setHistoryIndex(nextIndex); setShapes(nextShapes); setSelectedIds((current) => current.filter((id) => nextShapes.some((shape) => shape.id === id))); - setNotice("Redo"); - }, [history, historyIndex]); + syncProjectShapes(nextShapes); + setNotice(modifierCancelled ? "Edge modifier cancelled · Redo" : "Redo"); + }, [history, historyIndex, invalidateCadModifierSession, syncProjectShapes]); const toggleAlignMode = useCallback(() => { if (selectedShapes.length < 2) { @@ -4532,11 +5750,16 @@ export function SketchForgeEditor({ return; } const shape = shapes.find((entry) => entry.id === id); + const lockedAnchor = selectedShapes.find((entry) => entry.locked); + if (lockedAnchor && lockedAnchor.id !== id) { + setNotice(`Align anchor: ${lockedAnchor.name} (locked)`); + return; + } setAlignAnchorId(id); setAlignPreview(null); setNotice(shape ? `Align anchor: ${shape.name}` : "Align anchor set"); }, - [selectedIds, shapes], + [selectedIds, selectedShapes, shapes], ); const alignSelectionTo = useCallback( @@ -4546,7 +5769,7 @@ export function SketchForgeEditor({ return; } - const { nextShapes, moved } = alignedShapesForSelection(shapes, selectedIds, selectedShapes, alignAnchorId, axis, target); + const { nextShapes, moved } = alignedShapesForSelection(shapes, selectedIds, selectedShapes, effectiveAlignAnchorId, axis, target); setAlignPreview(null); if (moved === 0) { @@ -4556,7 +5779,7 @@ export function SketchForgeEditor({ commitShapes(nextShapes, selectedIds, `Aligned ${moved} shape${moved === 1 ? "" : "s"} ${alignmentLabel(axis, target)}`); }, - [alignAnchorId, commitShapes, selectedIds, selectedShapes, shapes], + [commitShapes, effectiveAlignAnchorId, selectedIds, selectedShapes, shapes], ); const previewAlignSelection = useCallback((axis: AlignAxis, target: AlignTarget) => { @@ -4610,6 +5833,163 @@ export function SketchForgeEditor({ setMirrorPreviewAxis(null); }, []); + const postCadModifierRequest = useCallback((request: CadModifierWorkerPayload, transfer: Transferable[] = []) => { + const requestId = cadModifierRequestRef.current + 1; + cadModifierRequestRef.current = requestId; + cadModifierWorkerRef.current?.postMessage({ ...request, requestId } as CadModifierWorkerRequest, transfer); + return requestId; + }, []); + + const cancelEdgeModifier = useCallback(() => { + invalidateCadModifierSession(); + setNotice("Edge modifier cancelled"); + }, [invalidateCadModifierSession]); + + const startEdgeModifier = useCallback((kind: CadModifierKind) => { + if (selectedShapes.length !== 1 || !selectedShape || selectedShape.locked || selectedShape.hole) { + setNotice(`Select one unlocked solid to ${kind}`); + return; + } + const hasAppliedEdgeTreatment = Boolean(selectedShape.importedMesh && selectedShape.edgeTreatments?.length); + const sourceParts = selectedShape.groupedShapes?.length && !hasAppliedEdgeTreatment ? restoreGroupedChildren(selectedShape) : [selectedShape]; + const partInputs: Array<{ shape: WorkplaneShape; mesh?: MeshData; brep?: string; brepTransform?: number[] }> = sourceParts.map((shape) => { + const frame = shape.cadBrepFrame; + const preserveNeedsRetessellation = preservesEdgeTreatmentSize(shape) && Boolean(frame) && ( + Math.abs(shapeWidth(shape) - (frame?.width ?? shapeWidth(shape))) > 1e-6 || + Math.abs(shapeDepth(shape) - (frame?.depth ?? shapeDepth(shape))) > 1e-6 || + Math.abs(shape.height - (frame?.height ?? shape.height)) > 1e-6 + ); + return shape.cadBrep && frame && !preserveNeedsRetessellation + ? { shape, brep: shape.cadBrep, brepTransform: cadBrepTransformForShape(shape) } + : { shape, mesh: meshForShape(shape) }; + }); + const triangleCount = partInputs.reduce((total, part) => total + (part.mesh?.faces.length ?? 0), 0); + if (triangleCount === 0 && partInputs.every((part) => !part.brep)) { + setNotice("The selected object has no printable surface"); + return; + } + if (triangleCount > 180_000) { + setNotice("This mesh is too dense for interactive edge treatment. Simplify it below 180,000 triangles first."); + return; + } + const amount = Math.max(0.05, Math.min(1, shapeWidth(selectedShape) / 6, shapeDepth(selectedShape) / 6, selectedShape.height / 6)); + cadModifierBaseShapeRef.current = selectedShape; + cadModifierBaseFingerprintRef.current = projectShapesFingerprint([selectedShape]); + setAlignMode(false); + setMirrorMode(false); + setEdgeModifier({ + kind, + edges: [], + selectedEdgeIds: [], + amount, + sharpAngle: 25, + chamferAngle: 45, + quality: "standard", + tangentChain: true, + preserveEdgeSize: selectedShape.edgeResizeMode === "preserve", + busy: true, + prepared: false, + error: null, + preview: null, + }); + setNotice(`Preparing ${kind} edges in the CAD worker`); + const parts: CadModifierMeshPart[] = partInputs.map((part) => part.brep + ? { brep: part.brep, brepTransform: part.brepTransform, hole: Boolean(part.shape.hole) } + : { ...meshDataToCadTransfer(part.mesh as MeshData), hole: Boolean(part.shape.hole) }); + cadModifierPrepareRef.current = postCadModifierRequest({ + type: "prepare", + parts, + sharpAngle: 25, + }, parts.flatMap((part) => part.positions && part.indices ? [part.positions.buffer, part.indices.buffer] : [])); + }, [postCadModifierRequest, selectedShape, selectedShapes.length]); + + useEffect(() => { + const base = cadModifierBaseShapeRef.current; + if (!edgeModifier || !base) return; + const current = shapes.find((shape) => shape.id === base.id); + if (current && projectShapesFingerprint([current]) === cadModifierBaseFingerprintRef.current) return; + invalidateCadModifierSession(); + setNotice("Edge modifier cancelled because the object changed"); + }, [edgeModifier, invalidateCadModifierSession, shapes]); + + const applyEdgeModifier = useCallback(() => { + const base = cadModifierBaseShapeRef.current; + if (!edgeModifier?.preview || !base) { + setNotice("Wait for a valid edge preview before applying"); + return; + } + const label = edgeModifier.kind === "fillet" ? "Filleted" : "Chamfered"; + const feature = { + kind: edgeModifier.kind, + amount: edgeModifier.amount, + edgeCount: edgeModifier.selectedEdgeIds.length, + ...(edgeModifier.kind === "chamfer" ? { chamferAngle: edgeModifier.chamferAngle } : {}), + } satisfies NonNullable[number]; + const modifiedShape: WorkplaneShape = { + ...edgeModifier.preview, + edgeResizeMode: edgeModifier.preserveEdgeSize ? "preserve" : "scale", + cadDisplayEdges: edgeModifier.preview.cadDisplayEdges?.length + ? edgeModifier.preview.cadDisplayEdges + : cadDisplayEdgesAfterTreatment(edgeModifier.preview, edgeModifier), + cadDisplayEdgesVersion: 2, + edgeTreatments: [ + ...(base.edgeTreatments ?? []), + { + ...feature, + }, + ], + edgeTreatmentHistory: [ + ...(base.edgeTreatmentHistory ?? []), + { + id: createLocalId("edge-history"), + createdAt: Date.now(), + feature, + before: cloneWorkplaneShapeSnapshot(base), + }, + ], + }; + commitShapes( + shapes.map((shape) => shape.id === base.id ? modifiedShape : shape), + base.id, + `${label} ${edgeModifier.selectedEdgeIds.length} edge${edgeModifier.selectedEdgeIds.length === 1 ? "" : "s"}`, + ); + invalidateCadModifierSession(); + }, [commitShapes, edgeModifier, invalidateCadModifierSession, shapes]); + + useEffect(() => { + if (!edgeModifier) return; + const onKeyDown = (event: KeyboardEvent) => { + if (event.key === "Escape") { + event.preventDefault(); + cancelEdgeModifier(); + } else if (event.key === "Enter" && edgeModifier.preview && !edgeModifier.busy && !edgeModifier.error) { + event.preventDefault(); + applyEdgeModifier(); + } + }; + window.addEventListener("keydown", onKeyDown); + return () => window.removeEventListener("keydown", onKeyDown); + }, [applyEdgeModifier, cancelEdgeModifier, edgeModifier]); + + useEffect(() => { + if (!edgeModifier?.prepared || edgeModifier.selectedEdgeIds.length === 0) return; + const worker = cadModifierWorkerRef.current; + if (!worker) return; + const timer = window.setTimeout(() => { + const requestId = postCadModifierRequest({ + type: "preview", + kind: edgeModifier.kind, + edgeIds: edgeModifier.selectedEdgeIds, + amount: edgeModifier.amount, + quality: edgeModifier.quality, + chamferAngle: edgeModifier.chamferAngle, + }); + cadModifierLatestPreviewRef.current = requestId; + setEdgeModifier((current) => current ? { ...current, busy: true, error: null } : current); + }, 120); + return () => window.clearTimeout(timer); + }, [edgeModifier?.amount, edgeModifier?.chamferAngle, edgeModifier?.kind, edgeModifier?.prepared, edgeModifier?.quality, edgeModifier?.selectedEdgeIds, postCadModifierRequest]); + const snapSelected = useCallback(() => { if (!hasSelection) { setNotice("Select a shape first"); @@ -4768,8 +6148,12 @@ export function SketchForgeEditor({ return; } - const groupable = selectedShapes.filter((shape) => !shape.locked); - const result = await buildGroupedShapeFromSelection(groupable); + if (selectedShapes.some((shape) => shape.locked)) { + setNotice("Unlock every selected shape before grouping"); + return; + } + + const result = await buildGroupedShapeFromSelection(selectedShapes); const { group } = result; if (!group) { if (result.consumed) { @@ -5139,6 +6523,28 @@ export function SketchForgeEditor({ const key = event.key.toLowerCase(); const shortcut = event.ctrlKey || event.metaKey; + if (sketchActive && toolbarMode === "sketch") { + if (event.key === "Escape") { + event.preventDefault(); + setSketchActivePointId(null); + setSketchSelection(null); + setNotice("Current sketch chain cleared"); + } else if (event.key === "Delete" || event.key === "Backspace") { + event.preventDefault(); + if (sketchSelection) deleteSelectedSketchEntity(); + else if (sketchMeasurement) clearSketchMeasurement(); + else deleteSelectedSketchEntity(); + } else if (shortcut && key === "z") { + event.preventDefault(); + if (event.shiftKey) sketchRedo(); + else sketchUndo(); + } else if (shortcut && key === "y") { + event.preventDefault(); + sketchRedo(); + } + return; + } + if (event.key === "Escape") { setSelectedIds([]); setNotice("Selection cleared"); @@ -5265,9 +6671,11 @@ export function SketchForgeEditor({ return () => window.removeEventListener("keydown", handleKeyDown); }, [ commitShapes, + clearSketchMeasurement, copySelected, cutSelected, deleteSelected, + deleteSelectedSketchEntity, duplicateSelected, dropSelectedToWorkplane, groupSelected, @@ -5276,12 +6684,18 @@ export function SketchForgeEditor({ pasteShape, raiseSelected, redo, + sketchActive, + sketchRedo, + sketchMeasurement, + sketchSelection, + sketchUndo, setSelectionHoleMode, showHidden, toggleAlignMode, toggleHidden, toggleMirrorMode, toggleLocked, + toolbarMode, undo, ungroupSelected, ]); @@ -5289,24 +6703,53 @@ export function SketchForgeEditor({ return (
0} + toolbarMode={toolbarMode} + onToolbarModeChange={(mode) => { + setToolbarMode(mode); + setTopPanel(null); + setMenuOpen(false); + }} + canUndo={historyIndex > 0 || Boolean(edgeModifier)} canRedo={historyIndex < history.length - 1} - canGroup={selectedShapes.length > 1} + canGroup={selectedShapes.length > 1 && selectedShapes.every((shape) => !shape.locked)} canIntersect={selectedShapes.some((shape) => !shape.locked && !shape.hole) && selectedShapes.some((shape) => !shape.locked && Boolean(shape.hole))} canUngroup={selectedShapes.some((shape) => Boolean(shape.groupedShapes?.length))} - hasClipboard={clipboard.length > 0} + hasClipboard={clipboard.length > 0 || systemClipboardSupported} hasSelection={hasSelection} alignMode={alignMode} canAlign={selectedShapes.length > 1} + canEdgeModify={selectedShapes.length === 1 && Boolean(selectedShape && !selectedShape.locked && !selectedShape.hole)} + edgeModifierKind={edgeModifier?.kind ?? null} mirrorMode={mirrorMode} + sketchActive={sketchActive} + sketchTool={sketchTool} + sketchCanUndo={sketchHistoryIndex > 0} + sketchCanRedo={sketchHistoryIndex < sketchHistory.length - 1} + canEditSketch={selectedShapes.length === 1 && Boolean(selectedShape?.sketchProfile)} + onStartSketch={() => beginSketch()} + onEditSketch={beginSketchEdit} + onSketchTool={setActiveSketchTool} + onSketchImage={() => { + if (sketchTool !== "select") { + setNotice("Choose Select before adding a sketch image"); + return; + } + sketchImageInputRef.current?.click(); + }} + onSketchUndo={sketchUndo} + onSketchRedo={sketchRedo} + onSketchFinish={finishSketch} + onSketchCancel={cancelSketch} onHome={onHome} onAlign={toggleAlignMode} + onChamfer={() => edgeModifier?.kind === "chamfer" ? cancelEdgeModifier() : startEdgeModifier("chamfer")} onCopy={copySelected} onDelete={deleteSelected} onDuplicate={duplicateSelected} onDropToWorkplane={dropSelectedToWorkplane} onGroup={groupSelected} onIntersect={intersectSelected} + onFillet={() => edgeModifier?.kind === "fillet" ? cancelEdgeModifier() : startEdgeModifier("fillet")} onMirror={toggleMirrorMode} onPaste={pasteShape} onRedo={redo} @@ -5331,11 +6774,49 @@ export function SketchForgeEditor({ }} />
- shape.id !== editingSketchShapeId)} + tool={sketchTool} + activePointId={sketchActivePointId} + selected={sketchSelection} + measurement={sketchMeasurement} + initialSnap={initialSnap} + initialWorkspace={initialWorkspace} + onPlanePoint={addSketchPlanePoint} + onPointPress={pressSketchPoint} + onSelectSegment={(id) => { + setSketchSelection({ kind: "segment", id }); + setSketchActivePointId(null); + }} + onSelectMany={(pointIds, segmentIds, imageIds) => { + setSketchSelection(pointIds.length || segmentIds.length || imageIds.length ? { kind: "multiple", pointIds, segmentIds, imageIds } : null); + setSketchActivePointId(null); + const count = pointIds.length + segmentIds.length + imageIds.length; + setNotice(count ? `Selected ${count} sketch item${count === 1 ? "" : "s"}` : "Sketch selection cleared"); + }} + onSelectImage={(id) => { + setSketchSelection({ kind: "image", id }); + setSketchActivePointId(null); + setNotice("Sketch image selected"); + }} + onUpdateImage={updateSketchImage} + onDeleteImage={deleteSketchImage} + onDeletePoint={deleteSketchPoint} + onDeleteSegment={deleteSketchSegment} + onMovePoint={moveSketchPoint} + onMoveHandle={moveSketchHandle} + onInsertPoint={insertSketchPoint} + onSetPointMode={setSketchPointMode} + onClearMeasurement={clearSketchMeasurement} + /> + ) : ( + + modifierActive={Boolean(edgeModifier)} + modifierPreviewActive={Boolean(edgeModifier?.preview)} + modifierEdges={edgeModifier?.edges.filter((edge) => modifierAvailableEdgeIds.includes(edge.id)) ?? []} + selectedModifierEdgeIds={edgeModifier?.selectedEdgeIds ?? []} + onModifierEdgeToggle={toggleModifierEdge} + /> + )}
+ {edgeModifier ? ( + setEdgeModifier((current) => current ? { ...current, amount: Math.max(0.05, Math.min(edgeModifierMaxAmount, value)), preview: null, busy: true, error: null } : current)} + onChamferAngleChange={(value) => setEdgeModifier((current) => current ? { ...current, chamferAngle: Math.max(5, Math.min(85, value)), preview: null, busy: true, error: null } : current)} + onQualityChange={(quality) => setEdgeModifier((current) => current ? { ...current, quality, preview: null, busy: true, error: null } : current)} + onSharpAngleChange={(sharpAngle) => setEdgeModifier((current) => { + if (!current) return current; + const nextAngle = Math.max(1, Math.min(120, sharpAngle)); + const availableIds = new Set(current.edges + .filter((edge) => edge.manifold && !edge.boundary && edge.angle + 1e-3 >= nextAngle) + .map((edge) => edge.id)); + const selectedEdgeIds = current.selectedEdgeIds.filter((edgeId) => availableIds.has(edgeId)); + return { + ...current, + sharpAngle: nextAngle, + selectedEdgeIds, + preview: null, + busy: selectedEdgeIds.length > 0, + error: availableIds.size === 0 ? "No sharp edges match this threshold" : selectedEdgeIds.length ? null : "Select at least one highlighted edge", + }; + })} + onTangentChainChange={(tangentChain) => setEdgeModifier((current) => current ? { ...current, tangentChain } : current)} + onPreserveEdgeSizeChange={(preserveEdgeSize) => setEdgeModifier((current) => current ? { ...current, preserveEdgeSize } : current)} + onSelectAll={() => setEdgeModifier((current) => current ? { ...current, selectedEdgeIds: modifierAvailableEdgeIds, preview: null, busy: modifierAvailableEdgeIds.length > 0, error: modifierAvailableEdgeIds.length ? null : current.error } : current)} + onClear={() => setEdgeModifier((current) => current ? { ...current, selectedEdgeIds: [], preview: null, busy: false, error: "Select at least one highlighted edge" } : current)} + onRemoveLastFeature={removeLastEdgeTreatment} + onApply={applyEdgeModifier} + onCancel={cancelEdgeModifier} + /> + ) : null} {topPanel ? ( ) : null} + { + const file = event.currentTarget.files?.[0]; + if (file) void addSketchImageFile(file); + event.currentTarget.value = ""; + }} + /> void; alignMode: boolean; canAlign: boolean; + canEdgeModify: boolean; + edgeModifierKind: CadModifierKind | null; canGroup: boolean; canIntersect: boolean; canRedo: boolean; @@ -5440,14 +7008,29 @@ function SecondaryToolbar({ hasClipboard: boolean; hasSelection: boolean; mirrorMode: boolean; + sketchActive: boolean; + sketchTool: SketchTool; + sketchCanUndo: boolean; + sketchCanRedo: boolean; + canEditSketch: boolean; + onStartSketch: () => void; + onEditSketch: () => void; + onSketchTool: (tool: SketchTool) => void; + onSketchImage: () => void; + onSketchUndo: () => void; + onSketchRedo: () => void; + onSketchFinish: () => void; + onSketchCancel: () => void; onHome?: () => void; onAlign: () => void; + onChamfer: () => void; onCopy: () => void; onDelete: () => void; onDuplicate: () => void; onDropToWorkplane: () => void; onGroup: () => void; onIntersect: () => void; + onFillet: () => void; onMirror: () => void; onPaste: () => void; onRedo: () => void; @@ -5464,6 +7047,11 @@ function SecondaryToolbar({ const [shapesOpen, setShapesOpen] = useState(false); const touchShapeStartRef = useRef<{ id: string; x: number; y: number } | null>(null); const suppressNextShapeClickRef = useRef(false); + const selectToolbarMode = (mode: "geometry" | "sketch") => { + setShapesOpen(false); + onTopPanel(null); + onToolbarModeChange(mode); + }; const addShapeFromMenu = (shape: ShapeAsset) => { onAddShape(shape); setShapesOpen(false); @@ -5485,6 +7073,8 @@ function SecondaryToolbar({ { label: "Align", icon: ToolbarAlignIcon, action: onAlign, enabled: canAlign, active: alignMode }, { label: "Mirror", icon: ToolbarMirrorIcon, action: onMirror, enabled: hasSelection, active: mirrorMode }, { label: "Snap to grid", icon: ToolbarSnapGridIcon, action: onSnap, enabled: hasSelection }, + { label: "Chamfer", icon: ToolbarChamferIcon, action: onChamfer, enabled: canEdgeModify, active: edgeModifierKind === "chamfer" }, + { label: "Fillet", icon: ToolbarFilletIcon, action: onFillet, enabled: canEdgeModify, active: edgeModifierKind === "fillet" }, { label: "Workplane", icon: ToolbarWorkplaneIcon, action: onWorkplaneTool, enabled: true, active: workplaneMode }, { label: "Drop to workplane", icon: ToolbarDropToWorkplaneIcon, action: onDropToWorkplane, enabled: hasSelection }, ]; @@ -5500,6 +7090,9 @@ function SecondaryToolbar({ return (
+
+ {toolbarMode === "geometry" ? ( + <> {onHome ? (
@@ -5617,11 +7210,11 @@ function SecondaryToolbar({
Modify
-
{rightTools.slice(5, 8).map(renderToolButton)}
+
{rightTools.slice(5, 10).map(renderToolButton)}
Arrange
-
{rightTools.slice(8).map(renderToolButton)}
+
{rightTools.slice(10).map(renderToolButton)}
@@ -5637,6 +7230,121 @@ function SecondaryToolbar({
+
+ + ) : ( +
+ {sketchActive ? ( + <> +
+
Draw
+
+ + + +
+
+
+
Select
+
+ + + + +
+
+
+
History
+
+ + +
+
+
+
Inspect
+
+ +
+
+
+
+
Finish
+
+ + +
+
+ + ) : ( +
+
Create
+
+ + +
+
+ )} +
+ )} +
+
+ +
); diff --git a/apps/web/src/components/SketchWorkspace.tsx b/apps/web/src/components/SketchWorkspace.tsx new file mode 100644 index 0000000..be06064 --- /dev/null +++ b/apps/web/src/components/SketchWorkspace.tsx @@ -0,0 +1,866 @@ +"use client"; + +import { ChevronUp, CornerDownRight, Home, Link, Link2Off, Minus, Plus, Split, Trash2, Waves } from "lucide-react"; +import { useEffect, useMemo, useRef, useState, type CSSProperties, type PointerEvent as ReactPointerEvent, type WheelEvent as ReactWheelEvent } from "react"; +import { SnapGridControl } from "@/components/workplane/ShapeInspector"; +import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings } from "@/lib/workplaneSettings"; +import type { GridSize, SketchImage, SketchPoint, SketchProfile, SketchSegment, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge"; + +export type SketchTool = "line" | "bezier" | "smooth" | "select" | "refine" | "erase" | "measure"; +export type SketchSelection = + | { kind: "point"; id: string } + | { kind: "segment"; id: string } + | { kind: "image"; id: string } + | { kind: "multiple"; pointIds: string[]; segmentIds: string[]; imageIds?: string[] } + | null; +export type SketchMeasurement = { start: SketchPoint; end: SketchPoint } | null; + +type SketchWorkspaceProps = { + profile: SketchProfile; + referenceShapes: WorkplaneShape[]; + tool: SketchTool; + activePointId: string | null; + selected: SketchSelection; + measurement: SketchMeasurement; + initialSnap?: GridSize; + initialWorkspace?: WorkplaneWorkspaceSettings; + onPlanePoint: (point: { x: number; z: number }, handles?: { handleIn: { x: number; z: number }; handleOut: { x: number; z: number } }) => void; + onPointPress: (id: string) => void; + onSelectSegment: (id: string) => void; + onSelectMany: (pointIds: string[], segmentIds: string[], imageIds: string[]) => void; + onSelectImage: (id: string) => void; + onUpdateImage: (id: string, patch: Partial, message?: string) => void; + onDeleteImage: (id: string) => void; + onDeletePoint: (id: string) => void; + onDeleteSegment: (id: string) => void; + onMovePoint: (id: string, point: { x: number; z: number }) => void; + onMoveHandle: (id: string, handle: "in" | "out", point: { x: number; z: number }) => void; + onInsertPoint: (segmentId: string, point: { x: number; z: number }) => void; + onSetPointMode: (id: string, mode: "corner" | "smooth" | "split") => void; + onClearMeasurement: () => void; +}; + +type PathStep = { segment: SketchSegment; from: SketchPoint; to: SketchPoint }; +type DisplayPath = { id: string; points: SketchPoint[]; steps: PathStep[]; closed: boolean }; +type PointerAction = + | { kind: "bezier"; pointerId: number; origin: { x: number; z: number }; current: { x: number; z: number } } + | { kind: "move-point"; pointerId: number; pointId: string; current: { x: number; z: number } } + | { kind: "move-handle"; pointerId: number; pointId: string; handle: "in" | "out"; current: { x: number; z: number } } + | { kind: "pan"; pointerId: number; clientX: number; clientY: number } + | { kind: "marquee"; pointerId: number; origin: { x: number; z: number }; current: { x: number; z: number } } + | { kind: "move-image"; pointerId: number; imageId: string; origin: { x: number; z: number }; current: { x: number; z: number }; start: SketchImage } + | { kind: "resize-image"; pointerId: number; imageId: string; handle: ResizeHandle; current: { x: number; z: number }; start: SketchImage }; + +type ResizeHandle = "nw" | "n" | "ne" | "e" | "se" | "s" | "sw" | "w"; + +function snapStep(size: GridSize) { + if (size === "Off") return 0; + if (size === "Brick") return 8; + return Number.parseFloat(size) || 1; +} + +function snapValue(value: number, step: number) { + return step > 0 ? Math.round(value / step) * step : value; +} + +function clamp(value: number, min: number, max: number) { + return Math.min(max, Math.max(min, value)); +} + +function resizeSketchImage(start: SketchImage, handle: ResizeHandle, point: { x: number; z: number }): Partial { + const minimum = 0.5; + const startsWest = handle.includes("w"); + const startsEast = handle.includes("e"); + const startsNorth = handle.includes("n"); + const startsSouth = handle.includes("s"); + const minX = start.x - start.width / 2; + const maxX = start.x + start.width / 2; + const minZ = start.z - start.depth / 2; + const maxZ = start.z + start.depth / 2; + const aspect = start.width / Math.max(minimum, start.depth); + + if (start.lockAspect !== false) { + if ((startsWest || startsEast) && (startsNorth || startsSouth)) { + const fixedX = startsWest ? maxX : minX; + const fixedZ = startsNorth ? maxZ : minZ; + const widthScale = Math.abs(point.x - fixedX) / Math.max(minimum, start.width); + const depthScale = Math.abs(point.z - fixedZ) / Math.max(minimum, start.depth); + const scale = Math.max(minimum / Math.min(start.width, start.depth), widthScale, depthScale); + const width = Math.max(minimum, start.width * scale); + const depth = Math.max(minimum, start.depth * scale); + const xDirection = startsWest ? -1 : 1; + const zDirection = startsNorth ? -1 : 1; + return { width, depth, x: fixedX + xDirection * width / 2, z: fixedZ + zDirection * depth / 2 }; + } + if (startsWest || startsEast) { + const fixedX = startsWest ? maxX : minX; + const width = Math.max(minimum, Math.abs(point.x - fixedX)); + return { width, depth: Math.max(minimum, width / aspect), x: fixedX + (startsWest ? -1 : 1) * width / 2 }; + } + const fixedZ = startsNorth ? maxZ : minZ; + const depth = Math.max(minimum, Math.abs(point.z - fixedZ)); + return { depth, width: Math.max(minimum, depth * aspect), z: fixedZ + (startsNorth ? -1 : 1) * depth / 2 }; + } + + let nextMinX = minX; + let nextMaxX = maxX; + let nextMinZ = minZ; + let nextMaxZ = maxZ; + if (startsWest) nextMinX = Math.min(point.x, maxX - minimum); + if (startsEast) nextMaxX = Math.max(point.x, minX + minimum); + if (startsNorth) nextMinZ = Math.min(point.z, maxZ - minimum); + if (startsSouth) nextMaxZ = Math.max(point.z, minZ + minimum); + return { + x: (nextMinX + nextMaxX) / 2, + z: (nextMinZ + nextMaxZ) / 2, + width: nextMaxX - nextMinX, + depth: nextMaxZ - nextMinZ, + }; +} + +function formatDimension(value: number, accuracy: 1 | 2 | 3) { + const threshold = 0.5 * 10 ** -accuracy; + return (Math.abs(value) < threshold ? 0 : value).toFixed(accuracy); +} + +function cubicPoint(start: SketchPoint, first: { x: number; z: number }, second: { x: number; z: number }, end: SketchPoint, amount: number) { + const inverse = 1 - amount; + return { + x: inverse ** 3 * start.x + 3 * inverse ** 2 * amount * first.x + 3 * inverse * amount ** 2 * second.x + amount ** 3 * end.x, + z: inverse ** 3 * start.z + 3 * inverse ** 2 * amount * first.z + 3 * inverse * amount ** 2 * second.z + amount ** 3 * end.z, + }; +} + +function segmentDimension(segment: SketchSegment, pointById: Map) { + const start = pointById.get(segment.startId); + const end = pointById.get(segment.endId); + if (!start || !end) return null; + const first = start.handleOut; + const second = end.handleIn; + if (segment.kind === "line" || !first || !second) { + return { + length: Math.hypot(end.x - start.x, end.z - start.z), + midpoint: { x: (start.x + end.x) / 2, z: (start.z + end.z) / 2 }, + }; + } + let length = 0; + let previous = start; + for (let index = 1; index <= 32; index += 1) { + const point = cubicPoint(start, first, second, end, index / 32); + length += Math.hypot(point.x - previous.x, point.z - previous.z); + previous = { ...point, id: "curve-sample" }; + } + return { length, midpoint: cubicPoint(start, first, second, end, 0.5) }; +} + +function orderedPaths(profile: SketchProfile): DisplayPath[] { + const pointById = new Map(profile.points.map((point) => [point.id, point])); + const adjacency = new Map>(); + profile.points.forEach((point) => adjacency.set(point.id, [])); + const valid = profile.segments.filter((segment) => { + if (!pointById.has(segment.startId) || !pointById.has(segment.endId)) return false; + adjacency.get(segment.startId)?.push({ pointId: segment.endId, segment }); + adjacency.get(segment.endId)?.push({ pointId: segment.startId, segment }); + return true; + }); + const unvisited = new Set(valid.map((segment) => segment.id)); + const paths: DisplayPath[] = []; + while (unvisited.size > 0) { + const seedId = unvisited.values().next().value as string; + const seed = valid.find((segment) => segment.id === seedId); + if (!seed) break; + const component = new Set(); + const queue = [seed.startId, seed.endId]; + while (queue.length) { + const id = queue.pop(); + if (!id || component.has(id)) continue; + component.add(id); + adjacency.get(id)?.forEach((edge) => queue.push(edge.pointId)); + } + const startId = [...component].find((id) => (adjacency.get(id)?.filter((edge) => unvisited.has(edge.segment.id)).length ?? 0) === 1) ?? seed.startId; + const first = pointById.get(startId); + if (!first) break; + const points = [first]; + const steps: PathStep[] = []; + let currentId = startId; + for (let guard = 0; guard <= valid.length; guard += 1) { + const edge = adjacency.get(currentId)?.find((candidate) => unvisited.has(candidate.segment.id)); + if (!edge) break; + const from = pointById.get(currentId); + const to = pointById.get(edge.pointId); + if (!from || !to) break; + unvisited.delete(edge.segment.id); + steps.push({ segment: edge.segment, from, to }); + currentId = to.id; + if (currentId === startId) break; + points.push(to); + } + paths.push({ id: seed.id, points, steps, closed: currentId === startId && steps.length >= 3 }); + } + return paths; +} + +function curveControls(step: PathStep) { + const forward = step.segment.startId === step.from.id; + return { + first: forward ? step.from.handleOut : step.from.handleIn, + second: forward ? step.to.handleIn : step.to.handleOut, + }; +} + +function pathData(path: DisplayPath) { + const first = path.points[0]; + if (!first) return ""; + const commands = [`M ${first.x} ${first.z}`]; + path.steps.forEach((step) => { + const controls = curveControls(step); + if (step.segment.kind !== "line" && controls.first && controls.second) { + commands.push(`C ${controls.first.x} ${controls.first.z} ${controls.second.x} ${controls.second.z} ${step.to.x} ${step.to.z}`); + } else { + commands.push(`L ${step.to.x} ${step.to.z}`); + } + }); + if (path.closed) commands.push("Z"); + return commands.join(" "); +} + +function segmentData(segment: SketchSegment, pointById: Map) { + const from = pointById.get(segment.startId); + const to = pointById.get(segment.endId); + if (!from || !to) return ""; + const step = { segment, from, to }; + const controls = curveControls(step); + return segment.kind !== "line" && controls.first && controls.second + ? `M ${from.x} ${from.z} C ${controls.first.x} ${controls.first.z} ${controls.second.x} ${controls.second.z} ${to.x} ${to.z}` + : `M ${from.x} ${from.z} L ${to.x} ${to.z}`; +} + +function isRoundReference(shape: WorkplaneShape) { + return ["cylinder", "sphere", "cone", "torus", "tube", "ring", "halfSphere"].includes(shape.kind); +} + +export function SketchWorkspace({ + profile, + referenceShapes, + tool, + activePointId, + selected, + measurement, + initialSnap, + initialWorkspace, + onPlanePoint, + onPointPress, + onSelectSegment, + onSelectMany, + onSelectImage, + onUpdateImage, + onDeleteImage, + onDeletePoint, + onDeleteSegment, + onMovePoint, + onMoveHandle, + onInsertPoint, + onSetPointMode, + onClearMeasurement, +}: SketchWorkspaceProps) { + const workspace = useMemo(() => normalizeWorkspaceSettings(initialWorkspace, DEFAULT_WORKPLANE_WORKSPACE), [initialWorkspace]); + const [snap, setSnap] = useState(() => normalizeSnapGrid(initialSnap, DEFAULT_SNAP_GRID)); + const [snapOpen, setSnapOpen] = useState(false); + const [zoom, setZoom] = useState(1); + const [pan, setPan] = useState({ x: 0, z: 0 }); + const [hover, setHover] = useState<{ x: number; z: number } | null>(null); + const [pointerAction, setPointerAction] = useState(null); + const svgRef = useRef(null); + const width = workspace.width / zoom; + const depth = workspace.depth / zoom; + const displayProfile = useMemo(() => { + if (pointerAction?.kind === "move-point") { + const source = profile.points.find((point) => point.id === pointerAction.pointId); + if (!source) return profile; + const deltaX = pointerAction.current.x - source.x; + const deltaZ = pointerAction.current.z - source.z; + return { + ...profile, + points: profile.points.map((point) => point.id === source.id ? { + ...point, + ...pointerAction.current, + handleIn: point.handleIn ? { x: point.handleIn.x + deltaX, z: point.handleIn.z + deltaZ } : undefined, + handleOut: point.handleOut ? { x: point.handleOut.x + deltaX, z: point.handleOut.z + deltaZ } : undefined, + } : point), + }; + } + if (pointerAction?.kind === "move-handle") { + return { + ...profile, + points: profile.points.map((point) => { + if (point.id !== pointerAction.pointId) return point; + const next = { ...point, handleIn: point.handleIn ? { ...point.handleIn } : undefined, handleOut: point.handleOut ? { ...point.handleOut } : undefined }; + if (pointerAction.handle === "in") next.handleIn = { ...pointerAction.current }; + else next.handleOut = { ...pointerAction.current }; + if (point.mode === "smooth") { + const opposite = { x: point.x * 2 - pointerAction.current.x, z: point.z * 2 - pointerAction.current.z }; + if (pointerAction.handle === "in") next.handleOut = opposite; + else next.handleIn = opposite; + } + return next; + }), + }; + } + return profile; + }, [pointerAction, profile]); + const displayImages = useMemo(() => { + const images = profile.images ?? []; + if (pointerAction?.kind === "move-image") { + const deltaX = pointerAction.current.x - pointerAction.origin.x; + const deltaZ = pointerAction.current.z - pointerAction.origin.z; + return images.map((image) => image.id === pointerAction.imageId ? { ...image, x: pointerAction.start.x + deltaX, z: pointerAction.start.z + deltaZ } : image); + } + if (pointerAction?.kind === "resize-image") { + return images.map((image) => image.id === pointerAction.imageId ? { ...image, ...resizeSketchImage(pointerAction.start, pointerAction.handle, pointerAction.current) } : image); + } + return images; + }, [pointerAction, profile.images]); + const pointById = useMemo(() => new Map(displayProfile.points.map((point) => [point.id, point])), [displayProfile.points]); + const paths = useMemo(() => orderedPaths(displayProfile), [displayProfile]); + const activePoint = activePointId ? pointById.get(activePointId) ?? null : null; + const selectedPoint = selected?.kind === "point" ? pointById.get(selected.id) ?? null : null; + const selectedImage = selected?.kind === "image" ? displayImages.find((image) => image.id === selected.id) ?? null : null; + const isPointSelected = (id: string) => selected?.kind === "point" ? selected.id === id : selected?.kind === "multiple" ? selected.pointIds.includes(id) : false; + const isSegmentSelected = (id: string) => selected?.kind === "segment" ? selected.id === id : selected?.kind === "multiple" ? selected.segmentIds.includes(id) : false; + const gridStep = clamp(workspace.gridBlockSize, 1, 200); + const verticalLines = useMemo(() => { + const lines: number[] = []; + const start = Math.ceil((-workspace.width / 2) / gridStep) * gridStep; + for (let x = start; x <= workspace.width / 2 + 0.0001; x += gridStep) lines.push(Number(x.toFixed(6))); + return lines; + }, [gridStep, workspace.width]); + const horizontalLines = useMemo(() => { + const lines: number[] = []; + const start = Math.ceil((-workspace.depth / 2) / gridStep) * gridStep; + for (let z = start; z <= workspace.depth / 2 + 0.0001; z += gridStep) lines.push(Number(z.toFixed(6))); + return lines; + }, [gridStep, workspace.depth]); + + const pointFromEvent = (event: { clientX: number; clientY: number }) => { + const svg = svgRef.current; + const matrix = svg?.getScreenCTM(); + if (!svg || !matrix) return null; + const screenPoint = svg.createSVGPoint(); + screenPoint.x = event.clientX; + screenPoint.y = event.clientY; + const local = screenPoint.matrixTransform(matrix.inverse()); + const step = snapStep(snap); + return { + x: clamp(snapValue(local.x, step), -workspace.width / 2, workspace.width / 2), + z: clamp(snapValue(local.y, step), -workspace.depth / 2, workspace.depth / 2), + }; + }; + + const beginPan = (event: ReactPointerEvent) => { + event.preventDefault(); + event.stopPropagation(); + svgRef.current?.setPointerCapture(event.pointerId); + setPointerAction({ kind: "pan", pointerId: event.pointerId, clientX: event.clientX, clientY: event.clientY }); + }; + + const handlePlanePointerDown = (event: ReactPointerEvent) => { + if (event.button === 1) { + beginPan(event); + return; + } + if (event.button !== 0 || (event.target !== event.currentTarget && (event.target as Element).closest("[data-sketch-entity]"))) return; + const point = pointFromEvent(event); + if (!point) return; + event.preventDefault(); + if (tool === "bezier") { + event.currentTarget.setPointerCapture(event.pointerId); + setPointerAction({ kind: "bezier", pointerId: event.pointerId, origin: point, current: point }); + } else if (tool === "select") { + event.currentTarget.setPointerCapture(event.pointerId); + setPointerAction({ kind: "marquee", pointerId: event.pointerId, origin: point, current: point }); + } else if (tool === "line" || tool === "smooth" || tool === "measure") { + onPlanePoint(point); + } + }; + + const handlePointerMove = (event: ReactPointerEvent) => { + if (pointerAction?.kind === "pan") { + const matrix = svgRef.current?.getScreenCTM(); + const scaleX = matrix ? Math.max(0.0001, Math.hypot(matrix.a, matrix.b)) : 1; + const scaleY = matrix ? Math.max(0.0001, Math.hypot(matrix.c, matrix.d)) : 1; + const deltaX = event.clientX - pointerAction.clientX; + const deltaY = event.clientY - pointerAction.clientY; + setPan((current) => ({ + x: clamp(current.x - deltaX / scaleX, -workspace.width / 2, workspace.width / 2), + z: clamp(current.z - deltaY / scaleY, -workspace.depth / 2, workspace.depth / 2), + })); + setPointerAction({ ...pointerAction, clientX: event.clientX, clientY: event.clientY }); + return; + } + const point = pointFromEvent(event); + setHover(point); + if (point && pointerAction) setPointerAction({ ...pointerAction, current: point }); + }; + + const finishPointerAction = (event: ReactPointerEvent) => { + const action = pointerAction; + if (!action || action.pointerId !== event.pointerId) return; + if (event.currentTarget.hasPointerCapture(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId); + if (action.kind === "pan") { + setPointerAction(null); + return; + } + if (action.kind === "marquee") { + const minX = Math.min(action.origin.x, action.current.x); + const maxX = Math.max(action.origin.x, action.current.x); + const minZ = Math.min(action.origin.z, action.current.z); + const maxZ = Math.max(action.origin.z, action.current.z); + const contains = (point: { x: number; z: number }) => point.x >= minX && point.x <= maxX && point.z >= minZ && point.z <= maxZ; + const pointIds = profile.points.filter(contains).map((point) => point.id); + const segmentIds = profile.segments.filter((segment) => { + const start = pointById.get(segment.startId); + const end = pointById.get(segment.endId); + return Boolean(start && end && (contains(start) || contains(end) || contains({ x: (start.x + end.x) / 2, z: (start.z + end.z) / 2 }))); + }).map((segment) => segment.id); + const imageIds = (profile.images ?? []).filter((image) => { + const imageMinX = image.x - image.width / 2; + const imageMaxX = image.x + image.width / 2; + const imageMinZ = image.z - image.depth / 2; + const imageMaxZ = image.z + image.depth / 2; + return imageMaxX >= minX && imageMinX <= maxX && imageMaxZ >= minZ && imageMinZ <= maxZ; + }).map((image) => image.id); + onSelectMany(pointIds, segmentIds, imageIds); + setPointerAction(null); + return; + } + if (action.kind === "bezier") { + const dx = action.current.x - action.origin.x; + const dz = action.current.z - action.origin.z; + onPlanePoint(action.origin, { + handleIn: { x: action.origin.x - dx, z: action.origin.z - dz }, + handleOut: { x: action.origin.x + dx, z: action.origin.z + dz }, + }); + } else if (action.kind === "move-point") { + onMovePoint(action.pointId, action.current); + } else if (action.kind === "move-handle") { + onMoveHandle(action.pointId, action.handle, action.current); + } else if (action.kind === "move-image") { + onUpdateImage(action.imageId, { + x: action.start.x + action.current.x - action.origin.x, + z: action.start.z + action.current.z - action.origin.z, + }, "Sketch image moved"); + } else if (action.kind === "resize-image") { + onUpdateImage(action.imageId, resizeSketchImage(action.start, action.handle, action.current), "Sketch image resized"); + } + setPointerAction(null); + }; + + const handleWheel = (event: ReactWheelEvent) => { + event.preventDefault(); + setZoom((current) => clamp(current * (event.deltaY > 0 ? 0.88 : 1.14), 0.75, 6)); + }; + + const beginEntityDrag = (event: ReactPointerEvent, action: PointerAction) => { + if (event.button !== 0) return; + event.preventDefault(); + event.stopPropagation(); + svgRef.current?.setPointerCapture(event.pointerId); + setPointerAction(action); + }; + + const measurementLength = measurement ? Math.hypot(measurement.end.x - measurement.start.x, measurement.end.z - measurement.start.z) : 0; + const measurementLabel = formatDimension(measurementLength, workspace.accuracy); + const previewLength = activePoint && hover ? Math.hypot(hover.x - activePoint.x, hover.z - activePoint.z) : 0; + const previewLabel = formatDimension(previewLength, workspace.accuracy); + const pillScale = 1 / zoom; + const selectedImageBounds = selectedImage ? { + minX: selectedImage.x - selectedImage.width / 2, + maxX: selectedImage.x + selectedImage.width / 2, + minZ: selectedImage.z - selectedImage.depth / 2, + maxZ: selectedImage.z + selectedImage.depth / 2, + } : null; + const imageResizeHandles: Array<{ id: ResizeHandle; x: number; z: number }> = selectedImage && selectedImageBounds ? [ + { id: "nw", x: selectedImageBounds.minX, z: selectedImageBounds.minZ }, + { id: "n", x: selectedImage.x, z: selectedImageBounds.minZ }, + { id: "ne", x: selectedImageBounds.maxX, z: selectedImageBounds.minZ }, + { id: "e", x: selectedImageBounds.maxX, z: selectedImage.z }, + { id: "se", x: selectedImageBounds.maxX, z: selectedImageBounds.maxZ }, + { id: "s", x: selectedImage.x, z: selectedImageBounds.maxZ }, + { id: "sw", x: selectedImageBounds.minX, z: selectedImageBounds.maxZ }, + { id: "w", x: selectedImageBounds.minX, z: selectedImage.z }, + ] : []; + + return ( +
+
Sketch view
+
+ + + +
+
+ setPointerAction(null)} + onPointerLeave={() => !pointerAction && setHover(null)} + onWheel={handleWheel} + > + + {workspace.showGrid ? ( + + {verticalLines.map((x, index) => )} + {horizontalLines.map((z, index) => )} + + ) : null} + + {displayImages.map((image) => ( + { + event.preventDefault(); + event.stopPropagation(); + if (event.button === 1) { + beginPan(event); + return; + } + if (event.button !== 0 || tool !== "select") return; + const point = pointFromEvent(event); + if (!point) return; + onSelectImage(image.id); + beginEntityDrag(event, { + kind: "move-image", + pointerId: event.pointerId, + imageId: image.id, + origin: point, + current: point, + start: { ...image }, + }); + }} + /> + ))} + + + {referenceShapes.filter((shape) => !shape.hidden).map((shape) => ( + + {isRoundReference(shape) ? ( + + ) : ( + + )} + + ))} + + + {pointerAction?.kind === "marquee" ? ( + + ) : null} + + {paths.some((path) => path.closed) ? path.closed).map(pathData).join(" ")} /> : null} + + + {displayProfile.segments.map((segment) => ( + { + const point = pointFromEvent(event); + event.preventDefault(); + event.stopPropagation(); + if (event.button === 1) beginPan(event); + else if (tool === "erase") onDeleteSegment(segment.id); + else if (event.button === 0 && tool === "refine" && point) onInsertPoint(segment.id, point); + else if (event.button === 0) onSelectSegment(segment.id); + }} + /> + ))} + + + {displayProfile.segments.map((segment) => { + const dimension = segmentDimension(segment, pointById); + if (!dimension) return null; + const label = formatDimension(dimension.length, workspace.accuracy); + const pillWidth = Math.max(7.2, label.length * 1.2 + 2.4) * pillScale; + const pillHeight = 4.2 * pillScale; + return ( + + + {label} + + ); + })} + + {activePoint && hover && ["line", "bezier", "smooth"].includes(tool) ? : null} + {activePoint && hover && ["line", "bezier", "smooth"].includes(tool) ? ( + + + {previewLabel} + + ) : null} + {pointerAction?.kind === "bezier" ? ( + + + + + ) : null} + {measurement ? ( + + + { + event.preventDefault(); + event.stopPropagation(); + onClearMeasurement(); + }} + > + + {measurementLabel} + × + + + ) : null} + {selectedPoint && tool === "select" ? ( + + {selectedPoint.handleIn ? <> event.button === 1 ? beginPan(event) : beginEntityDrag(event, { kind: "move-handle", pointerId: event.pointerId, pointId: selectedPoint.id, handle: "in", current: selectedPoint.handleIn! })} /> : null} + {selectedPoint.handleOut ? <> event.button === 1 ? beginPan(event) : beginEntityDrag(event, { kind: "move-handle", pointerId: event.pointerId, pointId: selectedPoint.id, handle: "out", current: selectedPoint.handleOut! })} /> : null} + + ) : null} + + {displayProfile.points.map((point) => ( + { + event.preventDefault(); + event.stopPropagation(); + if (event.button === 1) { + beginPan(event); + } else if (tool === "erase" || tool === "refine") { + onDeletePoint(point.id); + } else if (event.button === 0 && tool === "select") { + onPointPress(point.id); + beginEntityDrag(event, { kind: "move-point", pointerId: event.pointerId, pointId: point.id, current: { x: point.x, z: point.z } }); + } else if (event.button === 0) { + onPointPress(point.id); + } + }} + /> + ))} + + {selectedImage && selectedImageBounds && tool === "select" ? ( + + + + + {formatDimension(selectedImage.width, workspace.accuracy)} + + + + {formatDimension(selectedImage.depth, workspace.accuracy)} + + {imageResizeHandles.map((handle) => ( + { + if (event.button === 1) { + beginPan(event); + return; + } + if (event.button !== 0) return; + const point = pointFromEvent(event); + if (!point) return; + beginEntityDrag(event, { + kind: "resize-image", + pointerId: event.pointerId, + imageId: selectedImage.id, + handle: handle.id, + current: point, + start: { ...selectedImage }, + }); + }} + /> + ))} + + ) : null} + {hover && ["line", "bezier", "smooth", "measure"].includes(tool) ? : null} + +
+ {selectedImage && tool === "select" ? ( + onSelectMany([], [], [])} + onUpdate={(patch, message) => onUpdateImage(selectedImage.id, patch, message)} + onDelete={() => onDeleteImage(selectedImage.id)} + /> + ) : null} + {selectedPoint && tool === "select" ? ( +
+ + + +
+ ) : null} +
+ +
+
+ ); +} + +function SketchImageInspector({ + image, + accuracy, + onClose, + onUpdate, + onDelete, +}: { + image: SketchImage; + accuracy: 1 | 2 | 3; + onClose: () => void; + onUpdate: (patch: Partial, message?: string) => void; + onDelete: () => void; +}) { + const aspect = image.width / Math.max(0.5, image.depth); + const updateWidth = (width: number) => onUpdate({ + width, + ...(image.lockAspect !== false ? { depth: Math.max(0.5, width / aspect) } : {}), + }, "Sketch image width updated"); + const updateDepth = (depth: number) => onUpdate({ + depth, + ...(image.lockAspect !== false ? { width: Math.max(0.5, depth * aspect) } : {}), + }, "Sketch image height updated"); + + return ( + + ); +} + +function SketchImageRange({ + label, + value, + min, + max, + accuracy, + suffix = "mm", + onChange, +}: { + label: string; + value: number; + min: number; + max: number; + accuracy: 1 | 2 | 3; + suffix?: string; + onChange: (value: number) => void; +}) { + const safeValue = clamp(Number.isFinite(value) ? value : min, min, max); + const [draft, setDraft] = useState(formatDimension(safeValue, accuracy)); + useEffect(() => setDraft(formatDimension(safeValue, accuracy)), [accuracy, safeValue]); + const commit = () => { + const parsed = Number(draft); + onChange(clamp(Number.isFinite(parsed) ? parsed : safeValue, min, max)); + }; + const position = ((safeValue - min) / Math.max(0.001, max - min)) * 100; + return ( + + ); +} diff --git a/apps/web/src/components/WorkplaneViewport.tsx b/apps/web/src/components/WorkplaneViewport.tsx index b68f6cb..639ed5d 100644 --- a/apps/web/src/components/WorkplaneViewport.tsx +++ b/apps/web/src/components/WorkplaneViewport.tsx @@ -18,7 +18,7 @@ import { AlignOverlay, MirrorOverlay, type AlignOverlayState, type MirrorOverlay import { ShapeInspector, SnapGridControl, type ShapeInspectorUpdateOptions } from "@/components/workplane/ShapeInspector"; import { WorkspaceSettingsModal } from "@/components/workplane/WorkspaceSettingsModal"; import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint } from "@/lib/workplaneSettings"; -import { cleanNearZero, cleanRotationDegrees, fallbackSolidColor, mirroredAxisCount, mirrorSign, proportionalResizeScale, resizedShapeSize, shapeDepth, shapeWidth } from "@/lib/workplaneShapes"; +import { cleanNearZero, cleanRotationDegrees, fallbackSolidColor, mirroredAxisCount, mirrorSign, preservesEdgeTreatmentSize, proportionalResizeScale, resizedImportedCoordinates, resizedImportedMeshPositions, resizedShapeSize, shapeDepth, shapeWidth } from "@/lib/workplaneShapes"; import { TransformOverlay, getElevationMeasureKey, @@ -35,6 +35,7 @@ import { type TransformOverlayState, } from "@/components/workplane/TransformOverlay"; import type { AlignAxis, AlignHandleStatus, AlignTarget, GridSize, MeasurementAccuracy, ShapeAsset, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge"; +import type { CadModifierEdge } from "@/lib/cadModifierTypes"; const WORKPLANE_WIDTH = 200; const WORKPLANE_DEPTH = 140; @@ -84,8 +85,10 @@ const importedGeometryCache = new WeakMap< NonNullable, { geometry: THREE.BufferGeometry; edges: Map } >(); +const preservedImportedGeometryCache = new WeakMap(); const imageTextureLoader = new THREE.TextureLoader(); const IMPORTED_SELECTED_EDGE_TRIANGLE_LIMIT = 40000; +const NORMAL_IMPORTED_SELECTION_EDGE_ANGLE = 60; function parseDroppedShapeAsset(raw: string): ShapeAsset | null { try { @@ -142,12 +145,19 @@ type WorkplaneViewportProps = { onSelectShape: (id: string | string[] | null, mode?: "replace" | "toggle") => void; onSetPlacementElevation: (elevation: number, source: "shape" | "base") => void; onInteractionActiveChange?: (active: boolean) => void; + onEditSketch?: () => void; onUpdateShape: (id: string, patch: ShapeUpdatePatch) => void; onWorkspaceSettingsChange?: (settings: { workspace: WorkplaneWorkspaceSettings; snap: GridSize }) => void; onWorkplaneModeChange: (active: boolean) => void; + modifierActive?: boolean; + modifierPreviewActive?: boolean; + modifierEdges?: CadModifierEdge[]; + selectedModifierEdgeIds?: number[]; + onModifierEdgeToggle?: (id: number, singleEdge: boolean) => void; }; type WorkspaceSettings = WorkplaneWorkspaceSettings; +type ViewCubeFace = "top" | "bottom" | "front" | "back" | "right" | "left"; function readSavedWorkspaceDefault(key: string | null) { if (!key || typeof window === "undefined") { @@ -178,6 +188,7 @@ type ThreeState = { workplaneLayer: THREE.Group; shapeLayer: THREE.Group; helperLayer: THREE.Group; + modifierLayer: THREE.Group; raycaster: THREE.Raycaster; pointer: THREE.Vector2; dragPlane: THREE.Plane; @@ -1100,9 +1111,15 @@ export function WorkplaneViewport({ onSelectShape, onSetPlacementElevation, onInteractionActiveChange, + onEditSketch, onUpdateShape, onWorkspaceSettingsChange, onWorkplaneModeChange, + modifierActive = false, + modifierPreviewActive = false, + modifierEdges = [], + selectedModifierEdgeIds = [], + onModifierEdgeToggle, }: WorkplaneViewportProps) { const [snapOpen, setSnapOpen] = useState(false); const [snap, setSnap] = useState(() => normalizeSnapGrid(initialSnap, DEFAULT_SNAP_GRID)); @@ -1151,6 +1168,8 @@ export function WorkplaneViewport({ const alignAnchorIdRef = useRef(alignAnchorId); const alignHandlesRef = useRef(alignHandles); const mirrorModeRef = useRef(mirrorMode); + const modifierActiveRef = useRef(modifierActive); + const modifierPreviewActiveRef = useRef(modifierPreviewActive); const selectedIdsKeyRef = useRef(selectedIds.join("|")); const perfRef = useRef({ fps: 0, @@ -1161,6 +1180,14 @@ export function WorkplaneViewport({ }); const selectedShape = useMemo(() => (selectedIds.length === 1 ? shapes.find((shape) => shape.id === selectedIds[0]) ?? null : null), [selectedIds, shapes]); + const renderSelectionIds = useCallback( + (ids = selectedIdsRef.current) => (modifierActiveRef.current && !modifierPreviewActiveRef.current ? [] : ids), + [], + ); + + useEffect(() => { + rebuildModifierEdges(threeRef.current, modifierEdges, selectedModifierEdgeIds, modifierPreviewActive); + }, [modifierEdges, modifierPreviewActive, selectedModifierEdgeIds]); const placementElevationRef = useRef(placementElevation); const workplaneModeRef = useRef(workplaneMode); @@ -1231,7 +1258,7 @@ export function WorkplaneViewport({ useEffect(() => { shapesRef.current = shapes; - rebuildShapes(threeRef.current, shapes, selectedIdsRef.current, !transformRef.current && !dragRef.current); + rebuildShapes(threeRef.current, shapes, renderSelectionIds(), !transformRef.current && !dragRef.current); if (threeRef.current) { syncTransformOverlay( threeRef.current, @@ -1278,7 +1305,7 @@ export function WorkplaneViewport({ setActiveTransformKind(null); } selectedIdsRef.current = selectedIds; - rebuildShapes(threeRef.current, shapesRef.current, selectedIds, !transformRef.current && !dragRef.current); + rebuildShapes(threeRef.current, shapesRef.current, renderSelectionIds(selectedIds), !transformRef.current && !dragRef.current); if (threeRef.current) { syncTransformOverlay( threeRef.current, @@ -1295,6 +1322,18 @@ export function WorkplaneViewport({ } }, [selectedIds]); + useEffect(() => { + modifierActiveRef.current = modifierActive; + rebuildShapes(threeRef.current, shapesRef.current, renderSelectionIds(), !transformRef.current && !dragRef.current); + if (threeRef.current) threeRef.current.needsRender = true; + }, [modifierActive, renderSelectionIds]); + + useEffect(() => { + modifierPreviewActiveRef.current = modifierPreviewActive; + rebuildShapes(threeRef.current, shapesRef.current, renderSelectionIds(), !transformRef.current && !dragRef.current); + if (threeRef.current) threeRef.current.needsRender = true; + }, [modifierPreviewActive, renderSelectionIds]); + useEffect(() => { alignModeRef.current = alignMode; alignAnchorIdRef.current = alignAnchorId; @@ -1374,7 +1413,7 @@ export function WorkplaneViewport({ }; perfRef.current.lastSample = performance.now(); resetCamera(state); - rebuildShapes(state, shapesRef.current, selectedIdsRef.current); + rebuildShapes(state, shapesRef.current, renderSelectionIds()); const animate = () => { state.animationId = window.requestAnimationFrame(animate); @@ -1438,6 +1477,7 @@ export function WorkplaneViewport({ disposeChildren(state.workplaneLayer); disposeChildren(state.shapeLayer); disposeChildren(state.helperLayer); + disposeChildren(state.modifierLayer); state.renderer.dispose(); host.replaceChildren(); if (window.sketchforgeCaptureCanvas) { @@ -1695,6 +1735,9 @@ export function WorkplaneViewport({ const beginTransform = useCallback( (kind: TransformHandleKind, handleKey: string, event: ReactPointerEvent) => { + if (kind === "rotate" && event.button !== 0) { + return; + } const ids = selectedIdsRef.current; const frame = selectionFrameForShapes(shapesRef.current, ids); const shape = frame?.singleShape ?? shapesRef.current.find((entry) => entry.id === ids[0]); @@ -2153,6 +2196,19 @@ export function WorkplaneViewport({ return nearestId; }, []); + const pickModifierEdge = useCallback((clientX: number, clientY: number) => { + const state = threeRef.current; + if (!state) return null; + const rect = state.renderer.domElement.getBoundingClientRect(); + state.pointer.x = ((clientX - rect.left) / rect.width) * 2 - 1; + state.pointer.y = -((clientY - rect.top) / rect.height) * 2 + 1; + state.raycaster.setFromCamera(state.pointer, state.camera); + const hit = state.raycaster + .intersectObjects(state.modifierLayer.children, true) + .find((entry) => typeof entry.object.userData.modifierEdgeId === "number"); + return hit ? hit.object.userData.modifierEdgeId as number : null; + }, []); + const pickTransformHandle = useCallback((clientX: number, clientY: number) => { const state = threeRef.current; if (!state || selectedIdsRef.current.length !== 1) { @@ -2189,6 +2245,13 @@ export function WorkplaneViewport({ } const rect = state.renderer.domElement.getBoundingClientRect(); + if (modifierActive) { + event.preventDefault(); + const edgeId = pickModifierEdge(event.clientX, event.clientY); + if (edgeId !== null) onModifierEdgeToggle?.(edgeId, event.shiftKey); + return; + } + if (rulerModeRef.current) { event.preventDefault(); const candidate = resolveRulerCandidate(event.clientX, event.clientY); @@ -2413,11 +2476,14 @@ export function WorkplaneViewport({ onInteractionActiveChange?.(true); }, [ + modifierActive, onAlignAnchorChange, onInteractionActiveChange, + onModifierEdgeToggle, onSelectShape, onSetPlacementElevation, onWorkplaneModeChange, + pickModifierEdge, pickShape, pickTransformHandle, resolveRulerCandidate, @@ -2640,6 +2706,15 @@ export function WorkplaneViewport({ } }, []); + const setViewCubeFace = useCallback((face: ViewCubeFace) => { + const state = threeRef.current; + if (!state) { + return; + } + setCameraToViewFace(state, face); + syncViewCube(state, viewCubeRef.current); + }, []); + const zoomCamera = useCallback((scale: number) => { const state = threeRef.current; if (!state) { @@ -2745,14 +2820,14 @@ export function WorkplaneViewport({ return (
-