diff --git a/config/mime.json b/config/mime.json index df46627a..739e1b58 100644 --- a/config/mime.json +++ b/config/mime.json @@ -24,6 +24,7 @@ "crw": "image/x-canon-crw", "css": "text/css", "csv": "text/csv", + "dae": "model/vnd.collada+xml", "dbf": "application/dbf", "dcm": "image/dicom", "dcr": "image/x-kodak-dcr", @@ -54,7 +55,8 @@ "geojson": "application/geo+json", "gif": "image/gif", "gltf": "model/gltf+json", - "glb": "model/gtlt-binary", + "glb": "model/gltf-binary", + "gpx": "application/gpx+xml", "gz": "application/x-gzip", "heic": "image/heic", "heif": "image/heic", diff --git a/docker/Dockerfile b/docker/Dockerfile index cab811c1..42756eb6 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -1,74 +1,48 @@ # STEP1: CLONE THE CODE -FROM alpine:latest as builder_prepare +FROM alpine/git as builder_prepare WORKDIR /home/ ARG GIT_REPO=https://github.com/mickael-kerjean/filestash -ARG GIT_REF=master -RUN apk add --no-cache git && \ - git init filestash && \ - git -C filestash remote add origin ${GIT_REPO} && \ - git -C filestash fetch --depth 1 origin ${GIT_REF} && \ - git -C filestash checkout FETCH_HEAD +ARG GIT_BRANCH=master +RUN git clone --depth 1 --single-branch --branch ${GIT_BRANCH} ${GIT_REPO} -# STEP2: BUILD THE FRONTEND +# STEP2: BUILD FRONTEND FROM node:18-alpine AS builder_frontend -WORKDIR /home/ -COPY --from=builder_prepare /home/filestash/ ./ +WORKDIR /home/filestash/ +COPY --from=builder_prepare /home/filestash . RUN apk add make git gzip brotli && \ npm install --legacy-peer-deps && \ make build_frontend && \ cd public && make compress -# STEP3: BUILD THE BACKEND +# STEP3: BUILD BACKEND FROM golang:1.23-bookworm AS builder_backend -WORKDIR /home/ -COPY --from=builder_frontend /home/ ./ +WORKDIR /home/filestash/ +COPY --from=builder_frontend /home/filestash/ . RUN apt-get update > /dev/null && \ - apt-get install -y libvips-dev curl make > /dev/null 2>&1 && \ - apt-get install -y libjpeg-dev libtiff-dev libpng-dev libwebp-dev libraw-dev libheif-dev libgif-dev && \ + apt-get install -y curl make > /dev/null 2>&1 && \ + apt-get install -y libjpeg-dev libtiff-dev libpng-dev libwebp-dev libraw-dev libheif-dev libgif-dev libvips-dev > /dev/null 2>&1 && \ make build_init && \ make build_backend && \ mkdir -p ./dist/data/state/config/ && \ cp config/config.json ./dist/data/state/config/config.json -# STEP4: Create the prod image from the build +# STEP4: BUILD PLUGINS +FROM emscripten/emsdk AS builder_final +WORKDIR /home/filestash/ +COPY --from=builder_backend /home/filestash/ . +RUN mkdir -p /home/filestash/dist/data/state/plugins && \ + cd /home/filestash/server/plugin/plg_application_dev/ && make && \ + cd /home/filestash/server/plugin/plg_application_3d/ && make + +# STEP5: BUILD PROD IMAGE FROM debian:stable-slim MAINTAINER mickael@kerjean.me -COPY --from=builder_backend /home/dist/ /app/ -WORKDIR "/app" +WORKDIR /app/ +COPY --from=builder_final /home/filestash/dist/ . RUN apt-get update > /dev/null && \ apt-get install -y --no-install-recommends apt-utils && \ - apt-get install -y curl emacs-nox ffmpeg zip poppler-utils > /dev/null && \ - # org-mode: html export - curl https://raw.githubusercontent.com/mickael-kerjean/filestash/master/server/.assets/emacs/htmlize.el > /usr/share/emacs/site-lisp/htmlize.el && \ - # org-mode: markdown export - curl https://raw.githubusercontent.com/mickael-kerjean/filestash/master/server/.assets/emacs/ox-gfm.el > /usr/share/emacs/site-lisp/ox-gfm.el && \ - # org-mode: pdf export (with a light latex distribution) - cd && apt-get install -y wget perl > /dev/null && \ - export CTAN_REPO="http://mirror.las.iastate.edu/tex-archive/systems/texlive/tlnet" && \ - curl -sL "https://yihui.name/gh/tinytex/tools/install-unx.sh" | sh && \ - mv ~/.TinyTeX /usr/share/tinytex && \ - /usr/share/tinytex/bin/$(uname -m)-linux/tlmgr install wasy && \ - /usr/share/tinytex/bin/$(uname -m)-linux/tlmgr install ulem && \ - /usr/share/tinytex/bin/$(uname -m)-linux/tlmgr install marvosym && \ - /usr/share/tinytex/bin/$(uname -m)-linux/tlmgr install wasysym && \ - /usr/share/tinytex/bin/$(uname -m)-linux/tlmgr install xcolor && \ - /usr/share/tinytex/bin/$(uname -m)-linux/tlmgr install listings && \ - /usr/share/tinytex/bin/$(uname -m)-linux/tlmgr install parskip && \ - /usr/share/tinytex/bin/$(uname -m)-linux/tlmgr install float && \ - /usr/share/tinytex/bin/$(uname -m)-linux/tlmgr install wrapfig && \ - /usr/share/tinytex/bin/$(uname -m)-linux/tlmgr install sectsty && \ - /usr/share/tinytex/bin/$(uname -m)-linux/tlmgr install capt-of && \ - /usr/share/tinytex/bin/$(uname -m)-linux/tlmgr install epstopdf-pkg && \ - /usr/share/tinytex/bin/$(uname -m)-linux/tlmgr install cm-super && \ - ln -s /usr/share/tinytex/bin/$(uname -m)-linux/pdflatex /usr/local/bin/pdflatex && \ - apt-get purge -y --auto-remove perl wget && \ - # Cleanup - find /usr/share/ -name 'doc' | xargs rm -rf && \ - find /usr/share/emacs -name '*.pbm' | xargs rm -f && \ - find /usr/share/emacs -name '*.png' | xargs rm -f && \ - find /usr/share/emacs -name '*.xpm' | xargs rm -f - -RUN useradd filestash && \ + apt-get install -y curl ffmpeg libjpeg-dev libtiff-dev libpng-dev libwebp-dev libraw-dev libheif-dev libgif-dev && \ + useradd filestash && \ chown -R filestash:filestash /app/ && \ find /app/data/ -type d -exec chmod 770 {} \; && \ find /app/data/ -type f -exec chmod 760 {} \; && \ diff --git a/public/assets/boot/ctrl_boot_frontoffice.js b/public/assets/boot/ctrl_boot_frontoffice.js index 7bc5ccd2..fd417c16 100644 --- a/public/assets/boot/ctrl_boot_frontoffice.js +++ b/public/assets/boot/ctrl_boot_frontoffice.js @@ -2,28 +2,27 @@ import { toHref } from "../lib/skeleton/router.js"; import { loadJS } from "../helpers/loader.js"; import { init as setup_translation } from "../locales/index.js"; import { init as setup_config } from "../model/config.js"; +import { init as setup_plugin } from "../model/plugin.js"; import { init as setup_chromecast } from "../model/chromecast.js"; import { report } from "../helpers/log.js"; import { $error } from "./common.js"; export default async function main() { try { - await Promise.all([ // procedure with no outside dependencies - setup_config(), + await Promise.all([ + setup_config().then(() => Promise.all([ + setup_chromecast(), + setup_title(), + verify_origin(), + ])), setup_translation(), setup_xdg_open(), setup_device(), setup_blue_death_screen(), setup_history(), setup_polyfill(), + setup_plugin(), ]); - - await Promise.all([ // procedure with dependency on config - setup_chromecast(), - setup_title(), - verify_origin(), - ]); - window.dispatchEvent(new window.Event("pagechange")); } catch (err) { console.error(err); diff --git a/public/assets/helpers/loader_wasm.js b/public/assets/helpers/loader_wasm.js index 768f2712..8a859c53 100644 --- a/public/assets/helpers/loader_wasm.js +++ b/public/assets/helpers/loader_wasm.js @@ -1,4 +1,4 @@ -export default async function(baseURL, path) { +export default async function(baseURL, path, opts = {}) { const wasi = new Wasi(); const wasm = await WebAssembly.instantiateStreaming( fetch(new URL(path, baseURL)), { @@ -8,6 +8,7 @@ export default async function(baseURL, path) { env: { ...wasi, ...syscalls, + ...javascripts, }, }, ); @@ -17,28 +18,40 @@ export default async function(baseURL, path) { const FS = {}; let nextFd = 0; -writeFS(new Uint8Array(), 0); // stdin -writeFS(new Uint8Array(), 1); // stdout -writeFS(new Uint8Array(), 2); // stderr +writeFS(new Uint8Array(0), "/dev/stdin"); +writeFS(new Uint8Array(1024*8), "/dev/stdout"); +writeFS(new Uint8Array(1024*8), "/dev/stderr"); if (nextFd !== 3) throw new Error("Unexpected next fd"); -export function writeFS(buffer, fd) { - if (fd === undefined) fd = nextFd; - else if (!(buffer instanceof Uint8Array)) throw new Error("can only write Uint8Array"); - - FS[fd] = { +export function writeFS(buffer, path = "") { + if (!(buffer instanceof Uint8Array)) throw new Error("can only write Uint8Array"); + FS[nextFd] = { buffer, position: 0, + path, }; nextFd += 1; return nextFd - 1; } export function readFS(fd) { - if (fd < 3) throw new Error("cannot read from stdin, stdout or stderr"); const file = FS[fd]; if (!file) throw new Error("file does not exist"); - return file.buffer; + + let end = file.buffer.length; + while (end > 0 && file.buffer[end - 1] === 0) end--; + return file.buffer.subarray(0, end); +} + +function getFile(path) { + const allFds = Object.keys(FS); + for (let i=allFds.length - 1; i>0; i--) { + if (FS[allFds[i]].path === path) { + console.log(`fileopen fd=${i} path=${path}`); + return FS[allFds[i]]; + } + } + throw new Error("cannot get file"); } export const syscalls = { @@ -55,6 +68,64 @@ export const syscalls = { } return 0; }, + __syscall_unlinkat: (fd) => { + console.log(`Stubbed __syscall_unlinkat called with fd=${fd}`); + return -1; + }, + __syscall_rmdir: (fd) => { + console.log(`Stubbed __syscall_rmdir called with fd=${fd}`); + return -1; + }, + __syscall_fstat64: (pathPtr, bufPtr) => { + console.log(`Stubbed __syscall_stat64 called with pathPtr=${pathPtr}, bufPtr=${bufPtr}`); + return 0; // Return 0 for a successful call + }, + __syscall_newfstatat: (pathPtr, bufPtr) => { + console.log(`Stubbed __syscall_stat64 called with pathPtr=${pathPtr}, bufPtr=${bufPtr}`); + return 0; // Return 0 for a successful call + }, + __syscall_lstat64: () => { + console.log(`Stubbed __syscall_lstat64 called`); + return -1; + }, + __assert_fail: () => { + console.log(`Stubbed __assert_fail called`); + return -1; + }, + __syscall_ftruncate64: () => { + console.log(`Stubbed __syscall_ftruncate64`); + return -1; + }, + __syscall_renameat: () => { + console.log(`Stubbed __syscall_renameat`); + return -1; + }, +}; + +const javascripts = { + _tzset_js: () => { + console.log("Initializing time zone settings (stub)"); + }, + _abort_js: () => { + console.error("WebAssembly module called _abort_js!"); + throw new Error("_abort_js was called"); + }, + _mktime_js: () => { + console.error("WebAssembly module called _abort_js!"); + throw new Error("_abort_js was called"); + }, + _localtime_js: () => { + console.error("WebAssembly module called _localtime_js!"); + throw new Error("_localtime_js was called"); + }, + emscripten_date_now: () => { + console.error("WebAssembly module called emscripten_date_now!"); + throw new Error("_localtime_js was called"); + }, + emscripten_get_now: () => { + console.error("WebAssembly module called emscripten_get_now!"); + throw new Error("_localtime_js was called"); + }, }; export class Wasi { @@ -65,6 +136,16 @@ export class Wasi { this.fd_write = this.fd_write.bind(this); this.fd_seek = this.fd_seek.bind(this); this.fd_close = this.fd_close.bind(this); + + this._emscripten_memcpy_js = this._emscripten_memcpy_js.bind(this); + this.emscripten_resize_heap = this.emscripten_resize_heap.bind(this); + this.environ_sizes_get = this.environ_sizes_get.bind(this); + this.environ_get = this.environ_get.bind(this); + this.clock_time_get = this.clock_time_get.bind(this); + this.__syscall_openat = this.__syscall_openat.bind(this); + this.__syscall_stat64 = this.__syscall_stat64.bind(this); + this.__cxa_throw = this.__cxa_throw.bind(this); + this.random_get = this.random_get.bind(this); } set instance(val) { @@ -72,33 +153,36 @@ export class Wasi { } fd_write(fd, iovs, iovs_len, nwritten) { - if (!FS[fd]) { - console.error(`Invalid fd: ${fd}`); - return -1; - } - let output = FS[fd].buffer; + if (!FS[fd]) throw new Error(`File descriptor ${fd} does not exist.`); + const ioVecArray = new Uint32Array(this.#instance.exports.memory.buffer, iovs, iovs_len * 2); const memory = new Uint8Array(this.#instance.exports.memory.buffer); let totalBytesWritten = 0; - for (let i = 0; i < iovs_len * 2; i += 2) { - const sub = memory.subarray( - (ioVecArray[i] || 0), - (ioVecArray[i] || 0) + (ioVecArray[i+1] || 0), - ); - const tmp = new Uint8Array(output.byteLength + sub.byteLength); - tmp.set(output, 0); - tmp.set(sub, output.byteLength); - output = tmp; - totalBytesWritten += ioVecArray[i+1] || 0; - } - const dataView = new DataView(this.#instance.exports.memory.buffer); - dataView.setUint32(nwritten, totalBytesWritten, true); - FS[fd].buffer = output; - if (fd < 3 && fd >= 0) { - const msg = fd === 1 ? "stdout" : fd === 2 ? "stderr" : "stdxx"; - console.log(msg + ": " + (new TextDecoder()).decode(output)); - FS[fd].buffer = new ArrayBuffer(0); + for (let i = 0; i < iovs_len * 2; i += 2) { + const offset = ioVecArray[i]; + const length = ioVecArray[i + 1]; + while (FS[fd].buffer.byteLength - FS[fd].position < length) { + const newBuffer = new Uint8Array(FS[fd].buffer.byteLength + 1024 * 1024 * 5); + newBuffer.set(FS[fd].buffer, 0); + FS[fd].buffer = newBuffer; + } + FS[fd].buffer.set( + memory.subarray(offset, offset + length), + FS[fd].position + ); + FS[fd].position += length; + totalBytesWritten += length; + } + new DataView(this.#instance.exports.memory.buffer).setUint32( + nwritten, + totalBytesWritten, + true, + ); + if (fd === 1 || fd === 2) { + let msg = fd === 1? "stdout: " : "stderr: "; + msg += new TextDecoder().decode(readFS(fd)); + FS[fd] = { buffer: new Uint8Array(0), position: 0, path: "" }; } return 0; } @@ -130,9 +214,11 @@ export class Wasi { file.position += bytesToRead; totalBytesRead += bytesToRead; } - - const dataView = new DataView(this.#instance.exports.memory.buffer); - dataView.setUint32(nread, totalBytesRead, true); + new DataView(this.#instance.exports.memory.buffer).setUint32( + nread, + totalBytesRead, + true, + ); return 0; } @@ -169,4 +255,126 @@ export class Wasi { } return 0; } + + _emscripten_memcpy_js(dest, src, num) { + const memory = new Uint8Array(this.#instance.exports.memory.buffer); + memory.set(memory.subarray(src, src + num), dest); + return dest; + } + + emscripten_resize_heap() { + console.log("Stubbed emscripten_resize_heap called"); + throw new Error("Heap resize not supported"); + } + + environ_sizes_get() { + console.log(`Stubbed environ_sizes_get called`); + return 0; + } + + environ_get() { + console.log(`Stubbed environ_get called`); + return 0; + } + + clock_time_get() { + console.log(`Stubbed clock_time_get called`); + return -1; + } + + __syscall_openat(dirFd, pathPtr, flags, mode) { + console.debug(`openat called with dirFd=${dirFd}, pathPtr=${pathPtr}, flags=${flags}, mode=${mode}`); + const memory = new Uint8Array(this.#instance.exports.memory.buffer); + let path = ""; + for (let i = pathPtr; memory[i] !== 0; i++) { + path += String.fromCharCode(memory[i]); + } + const allFds = Object.keys(FS); + for (let i=allFds.length - 1; i>0; i--) { + if (FS[allFds[i]].path === path) { + console.log(`fileopen fd=${i} path=${path}`); + return i; + } + } + return -1; + } + + __syscall_stat64(pathPtr, buf) { + console.log(`stat64`); + const memory = new Uint8Array(this.#instance.exports.memory.buffer); + let path = ""; + for (let i = pathPtr; memory[i] !== 0; i++) { + path += String.fromCharCode(memory[i]); + } + const file = getFile(path); + const HEAP32 = new Int32Array(this.#instance.exports.memory.buffer); + const HEAPU32 = new Uint32Array(this.#instance.exports.memory.buffer); + + const tempI64 = [0, 0]; + const tempDouble = 0; + + // Dummy stat data + const stat = { + dev: 1, + ino: 42, + mode: 0o100644, + nlink: 1, + uid: 1000, + gid: 1000, + rdev: 0, + size: file.buffer.byteLength, + blksize: 4096, + blocks: 256, + atime: new Date(), + mtime: new Date(), + ctime: new Date(), + }; + // Fill the buffer + HEAP32[(buf >> 2)] = stat.dev; + HEAP32[((buf + 4) >> 2)] = stat.mode; + HEAPU32[((buf + 8) >> 2)] = stat.nlink; + HEAP32[((buf + 12) >> 2)] = stat.uid; + HEAP32[((buf + 16) >> 2)] = stat.gid; + HEAP32[((buf + 20) >> 2)] = stat.rdev; + HEAP32[((buf + 24) >> 2)] = stat.size & 0xFFFFFFFF; // Lower 32 bits + HEAP32[((buf + 28) >> 2)] = Math.floor(stat.size / 4294967296); // Upper 32 bits + HEAP32[((buf + 32) >> 2)] = stat.blksize; + HEAP32[((buf + 36) >> 2)] = stat.blocks; + + // Write timestamps + const atimeSeconds = Math.floor(stat.atime.getTime() / 1000); + const atimeNanos = (stat.atime.getTime() % 1000) * 1e6; + HEAP32[((buf + 40) >> 2)] = atimeSeconds; + HEAP32[((buf + 44) >> 2)] = 0; // Upper 32 bits of atime + HEAP32[((buf + 48) >> 2)] = atimeNanos; + + const mtimeSeconds = Math.floor(stat.mtime.getTime() / 1000); + const mtimeNanos = (stat.mtime.getTime() % 1000) * 1e6; + HEAP32[((buf + 56) >> 2)] = mtimeSeconds; + HEAP32[((buf + 60) >> 2)] = 0; // Upper 32 bits of mtime + HEAP32[((buf + 64) >> 2)] = mtimeNanos; + + const ctimeSeconds = Math.floor(stat.ctime.getTime() / 1000); + const ctimeNanos = (stat.ctime.getTime() % 1000) * 1e6; + HEAP32[((buf + 72) >> 2)] = ctimeSeconds; + HEAP32[((buf + 76) >> 2)] = 0; // Upper 32 bits of ctime + HEAP32[((buf + 80) >> 2)] = ctimeNanos; + + // Dummy inode + HEAP32[((buf + 88) >> 2)] = stat.ino & 0xFFFFFFFF; // Lower 32 bits + HEAP32[((buf + 92) >> 2)] = Math.floor(stat.ino / 4294967296); // Upper 32 bits + + console.debug(`Stubbed __syscall_stat64 called with pathPtr=${pathPtr}, bufPtr=${buf}`); + return 0; + } + + __cxa_throw(ptr, type, destructor) { + console.error(`Exception thrown at ptr=${ptr}, type=${type}, destructor=${destructor}`); + throw new Error("WebAssembly exception"); + } + + random_get() { + console.log(`Stubbed random_get called`); + return -1; + } } diff --git a/public/assets/lib/vendor/three/3DMLoader.js b/public/assets/lib/vendor/three/3DMLoader.js deleted file mode 100644 index 2c7cd4c2..00000000 --- a/public/assets/lib/vendor/three/3DMLoader.js +++ /dev/null @@ -1,1772 +0,0 @@ -// @ts-nocheck -import { - BufferGeometryLoader, - FileLoader, - Loader, - Object3D, - MeshStandardMaterial, - MeshPhysicalMaterial, - Mesh, - Color, - Points, - PointsMaterial, - Line, - LineBasicMaterial, - Matrix4, - DirectionalLight, - PointLight, - SpotLight, - RectAreaLight, - Sprite, - SpriteMaterial, - CanvasTexture, - LinearFilter, - ClampToEdgeWrapping, - RepeatWrapping, - TextureLoader, - DoubleSide -} from './three.module.js'; - -import { EXRLoader } from './EXRLoader.js'; - -const _taskCache = new WeakMap(); - -class Rhino3dmLoader extends Loader { - - constructor( manager ) { - - super( manager ); - - this.libraryPath = ''; - this.libraryPending = null; - this.libraryBinary = null; - this.libraryConfig = {}; - - this.url = ''; - - this.workerLimit = 4; - this.workerPool = []; - this.workerNextTaskID = 1; - this.workerSourceURL = ''; - this.workerConfig = {}; - - this.materials = []; - this.warnings = []; - - } - - setLibraryPath( path ) { - - this.libraryPath = path; - - return this; - - } - - setWorkerLimit( workerLimit ) { - - this.workerLimit = workerLimit; - - return this; - - } - - load( url, onLoad, onProgress, onError ) { - - const loader = new FileLoader( this.manager ); - - loader.setPath( this.path ); - loader.setResponseType( 'arraybuffer' ); - loader.setRequestHeader( this.requestHeader ); - - this.url = url; - - loader.load( url, ( buffer ) => { - - // Check for an existing task using this buffer. A transferred buffer cannot be transferred - // again from this thread. - if ( _taskCache.has( buffer ) ) { - - const cachedTask = _taskCache.get( buffer ); - - return cachedTask.promise.then( onLoad ).catch( onError ); - - } - - this.decodeObjects( buffer, url ) - .then( result => { - - result.userData.warnings = this.warnings; - onLoad( result ); - - } ) - .catch( e => onError( e ) ); - - }, onProgress, onError ); - - } - - debug() { - - console.log( 'Task load: ', this.workerPool.map( ( worker ) => worker._taskLoad ) ); - - } - - decodeObjects( buffer, url ) { - - let worker; - let taskID; - - const taskCost = buffer.byteLength; - - const objectPending = this._getWorker( taskCost ) - .then( ( _worker ) => { - - worker = _worker; - taskID = this.workerNextTaskID ++; - - return new Promise( ( resolve, reject ) => { - - worker._callbacks[ taskID ] = { resolve, reject }; - - worker.postMessage( { type: 'decode', id: taskID, buffer }, [ buffer ] ); - - // this.debug(); - - } ); - - } ) - .then( ( message ) => this._createGeometry( message.data ) ) - .catch( e => { - - throw e; - - } ); - - // Remove task from the task list. - // Note: replaced '.finally()' with '.catch().then()' block - iOS 11 support (#19416) - objectPending - .catch( () => true ) - .then( () => { - - if ( worker && taskID ) { - - this._releaseTask( worker, taskID ); - - //this.debug(); - - } - - } ); - - // Cache the task result. - _taskCache.set( buffer, { - - url: url, - promise: objectPending - - } ); - - return objectPending; - - } - - parse( data, onLoad, onError ) { - - this.decodeObjects( data, '' ) - .then( result => { - - result.userData.warnings = this.warnings; - onLoad( result ); - - } ) - .catch( e => onError( e ) ); - - } - - _compareMaterials( material ) { - - const mat = {}; - mat.name = material.name; - mat.color = {}; - mat.color.r = material.color.r; - mat.color.g = material.color.g; - mat.color.b = material.color.b; - mat.type = material.type; - - const json = JSON.stringify( mat ); - - for ( let i = 0; i < this.materials.length; i ++ ) { - - const m = this.materials[ i ]; - const _mat = {}; - _mat.name = m.name; - _mat.color = {}; - _mat.color.r = m.color.r; - _mat.color.g = m.color.g; - _mat.color.b = m.color.b; - _mat.type = m.type; - - if ( JSON.stringify( _mat ) === json ) { - - return m; - - } - - } - - this.materials.push( material ); - - return material; - - } - - _createMaterial( material, renderEnvironment ) { - - if ( material === undefined ) { - - return new MeshStandardMaterial( { - color: new Color( 1, 1, 1 ), - metalness: 0.8, - name: Loader.DEFAULT_MATERIAL_NAME, - side: DoubleSide - } ); - - } - - //console.log(material) - - let mat = new MeshPhysicalMaterial( { - - color: new Color( material.diffuseColor.r / 255.0, material.diffuseColor.g / 255.0, material.diffuseColor.b / 255.0 ), - emissive: new Color( material.emissionColor.r, material.emissionColor.g, material.emissionColor.b ), - flatShading: material.disableLighting, - ior: material.indexOfRefraction, - name: material.name, - reflectivity: material.reflectivity, - opacity: 1.0 - material.transparency, - side: DoubleSide, - specularColor: material.specularColor, - transparent: material.transparency > 0 ? true : false - - } ); - - mat.userData.id = material.id; - - if ( material.pbrSupported ) { - - const pbr = material.pbr; - - mat.anisotropy = pbr.anisotropy; - mat.anisotropyRotation = pbr.anisotropicRotation; - mat.color = new Color( pbr.baseColor.r, pbr.baseColor.g, pbr.baseColor.b ); - mat.clearCoat = pbr.clearCoat; - mat.clearCoatRoughness = pbr.clearCoatRoughness; - mat.metalness = pbr.metallic; - mat.transmission = 1 - pbr.opacity; - mat.roughness = pbr.roughness; - mat.sheen = pbr.sheen; - mat.specularIntensity = pbr.specular; - mat.thickness = pbr.subsurface; - - } - - if ( material.pbrSupported && material.pbr.opacity === 0 && material.transparency === 1 ) { - - //some compromises - - mat.opacity = 0.2; - mat.transmission = 1.00; - - } - - const textureLoader = new TextureLoader(); - - for ( let i = 0; i < material.textures.length; i ++ ) { - - const texture = material.textures[ i ]; - - if ( texture.image !== null ) { - - const map = textureLoader.load( texture.image ); - - //console.log(texture.type ) - - switch ( texture.type ) { - - case 'Bump': - - mat.bumpMap = map; - - break; - - case 'Diffuse': - - mat.map = map; - - break; - - case 'Emap': - - mat.envMap = map; - - break; - - case 'Opacity': - - mat.transmissionMap = map; - - break; - - case 'Transparency': - - mat.alphaMap = map; - mat.transparent = true; - - break; - - case 'PBR_Alpha': - - mat.alphaMap = map; - mat.transparent = true; - - break; - - case 'PBR_AmbientOcclusion': - - mat.aoMap = map; - - break; - - case 'PBR_Anisotropic': - - mat.anisotropyMap = map; - - break; - - case 'PBR_BaseColor': - - mat.map = map; - - break; - - case 'PBR_Clearcoat': - - mat.clearcoatMap = map; - - break; - - case 'PBR_ClearcoatBump': - - mat.clearcoatNormalMap = map; - - break; - - case 'PBR_ClearcoatRoughness': - - mat.clearcoatRoughnessMap = map; - - break; - - case 'PBR_Displacement': - - mat.displacementMap = map; - - break; - - case 'PBR_Emission': - - mat.emissiveMap = map; - - break; - - case 'PBR_Metallic': - - mat.metalnessMap = map; - - break; - - case 'PBR_Roughness': - - mat.roughnessMap = map; - - break; - - case 'PBR_Sheen': - - mat.sheenColorMap = map; - - break; - - case 'PBR_Specular': - - mat.specularColorMap = map; - - break; - - case 'PBR_Subsurface': - - mat.thicknessMap = map; - - break; - - default: - - this.warnings.push( { - message: `THREE.3DMLoader: No conversion exists for 3dm ${texture.type}.`, - type: 'no conversion' - } ); - - break; - - } - - map.wrapS = texture.wrapU === 0 ? RepeatWrapping : ClampToEdgeWrapping; - map.wrapT = texture.wrapV === 0 ? RepeatWrapping : ClampToEdgeWrapping; - - if ( texture.repeat ) { - - map.repeat.set( texture.repeat[ 0 ], texture.repeat[ 1 ] ); - - } - - } - - } - - if ( renderEnvironment ) { - - new EXRLoader().load( renderEnvironment.image, function ( texture ) { - - texture.mapping = THREE.EquirectangularReflectionMapping; - mat.envMap = texture; - - } ); - - } - - return mat; - - } - - _createGeometry( data ) { - - const object = new Object3D(); - const instanceDefinitionObjects = []; - const instanceDefinitions = []; - const instanceReferences = []; - - object.userData[ 'layers' ] = data.layers; - object.userData[ 'groups' ] = data.groups; - object.userData[ 'settings' ] = data.settings; - object.userData.settings[ 'renderSettings' ] = data.renderSettings; - object.userData[ 'objectType' ] = 'File3dm'; - object.userData[ 'materials' ] = null; - - object.name = this.url; - - let objects = data.objects; - const materials = data.materials; - - for ( let i = 0; i < objects.length; i ++ ) { - - const obj = objects[ i ]; - const attributes = obj.attributes; - - switch ( obj.objectType ) { - - case 'InstanceDefinition': - - instanceDefinitions.push( obj ); - - break; - - case 'InstanceReference': - - instanceReferences.push( obj ); - - break; - - default: - - let matId; - - switch( attributes.materialSource.name ) { - case 'ObjectMaterialSource_MaterialFromLayer': - //check layer index - if ( attributes.layerIndex >= 0 ) { - - matId = data.layers[ attributes.layerIndex ].renderMaterialIndex; - - } else { - - matId = null; - - } - - break; - - case 'ObjectMaterialSource_MaterialFromObject': - - if ( attributes.materialIndex >= 0 ) { - - matId = attributes.materialIndex; - - } else { - - matId = null; - - } - - break; - - } - - let material; - - if ( matId >= 0 ) { - - const rMaterial = materials[ matId ]; - material = this._createMaterial( rMaterial, data.renderEnvironment ); - - - } else { - - material = this._createMaterial(); - - } - - material = this._compareMaterials( material ); - const _object = this._createObject( obj, material ); - - if ( _object === undefined ) { - - continue; - - } - - const layer = data.layers[ attributes.layerIndex ]; - - _object.visible = layer ? data.layers[ attributes.layerIndex ].visible : true; - - if ( attributes.isInstanceDefinitionObject ) { - - instanceDefinitionObjects.push( _object ); - - } else { - - object.add( _object ); - - } - - break; - - } - - } - - for ( let i = 0; i < instanceDefinitions.length; i ++ ) { - - const iDef = instanceDefinitions[ i ]; - - objects = []; - - for ( let j = 0; j < iDef.attributes.objectIds.length; j ++ ) { - - const objId = iDef.attributes.objectIds[ j ]; - - for ( let p = 0; p < instanceDefinitionObjects.length; p ++ ) { - - const idoId = instanceDefinitionObjects[ p ].userData.attributes.id; - - if ( objId === idoId ) { - - objects.push( instanceDefinitionObjects[ p ] ); - - } - - } - - } - - // Currently clones geometry and does not take advantage of instancing - - for ( let j = 0; j < instanceReferences.length; j ++ ) { - - const iRef = instanceReferences[ j ]; - - if ( iRef.geometry.parentIdefId === iDef.attributes.id ) { - - const iRefObject = new Object3D(); - const xf = iRef.geometry.xform.array; - - const matrix = new Matrix4(); - matrix.set( ...xf ); - - iRefObject.applyMatrix4( matrix ); - - for ( let p = 0; p < objects.length; p ++ ) { - - iRefObject.add( objects[ p ].clone( true ) ); - - } - - object.add( iRefObject ); - - } - - } - - } - - object.userData[ 'materials' ] = this.materials; - object.name = ''; - return object; - - } - - _createObject( obj, mat ) { - - const loader = new BufferGeometryLoader(); - - const attributes = obj.attributes; - - let geometry, material, _color, color; - - switch ( obj.objectType ) { - - case 'Point': - case 'PointSet': - - geometry = loader.parse( obj.geometry ); - - if ( geometry.attributes.hasOwnProperty( 'color' ) ) { - - material = new PointsMaterial( { vertexColors: true, sizeAttenuation: false, size: 2 } ); - - } else { - - _color = attributes.drawColor; - color = new Color( _color.r / 255.0, _color.g / 255.0, _color.b / 255.0 ); - material = new PointsMaterial( { color: color, sizeAttenuation: false, size: 2 } ); - - } - - material = this._compareMaterials( material ); - - const points = new Points( geometry, material ); - points.userData[ 'attributes' ] = attributes; - points.userData[ 'objectType' ] = obj.objectType; - - if ( attributes.name ) { - - points.name = attributes.name; - - } - - return points; - - case 'Mesh': - case 'Extrusion': - case 'SubD': - case 'Brep': - - if ( obj.geometry === null ) return; - - geometry = loader.parse( obj.geometry ); - - if ( geometry.attributes.hasOwnProperty( 'color' ) ) { - - mat.vertexColors = true; - - } - - if ( mat === null ) { - - mat = this._createMaterial(); - mat = this._compareMaterials( mat ); - - } - - const mesh = new Mesh( geometry, mat ); - mesh.castShadow = attributes.castsShadows; - mesh.receiveShadow = attributes.receivesShadows; - mesh.userData[ 'attributes' ] = attributes; - mesh.userData[ 'objectType' ] = obj.objectType; - - if ( attributes.name ) { - - mesh.name = attributes.name; - - } - - return mesh; - - case 'Curve': - - geometry = loader.parse( obj.geometry ); - - _color = attributes.drawColor; - color = new Color( _color.r / 255.0, _color.g / 255.0, _color.b / 255.0 ); - - material = new LineBasicMaterial( { color: color } ); - material = this._compareMaterials( material ); - - const lines = new Line( geometry, material ); - lines.userData[ 'attributes' ] = attributes; - lines.userData[ 'objectType' ] = obj.objectType; - - if ( attributes.name ) { - - lines.name = attributes.name; - - } - - return lines; - - case 'TextDot': - - geometry = obj.geometry; - - const ctx = document.createElement( 'canvas' ).getContext( '2d' ); - const font = `${geometry.fontHeight}px ${geometry.fontFace}`; - ctx.font = font; - const width = ctx.measureText( geometry.text ).width + 10; - const height = geometry.fontHeight + 10; - - const r = window.devicePixelRatio; - - ctx.canvas.width = width * r; - ctx.canvas.height = height * r; - ctx.canvas.style.width = width + 'px'; - ctx.canvas.style.height = height + 'px'; - ctx.setTransform( r, 0, 0, r, 0, 0 ); - - ctx.font = font; - ctx.textBaseline = 'middle'; - ctx.textAlign = 'center'; - color = attributes.drawColor; - ctx.fillStyle = `rgba(${color.r},${color.g},${color.b},${color.a})`; - ctx.fillRect( 0, 0, width, height ); - ctx.fillStyle = 'white'; - ctx.fillText( geometry.text, width / 2, height / 2 ); - - const texture = new CanvasTexture( ctx.canvas ); - texture.minFilter = LinearFilter; - texture.wrapS = ClampToEdgeWrapping; - texture.wrapT = ClampToEdgeWrapping; - - material = new SpriteMaterial( { map: texture, depthTest: false } ); - const sprite = new Sprite( material ); - sprite.position.set( geometry.point[ 0 ], geometry.point[ 1 ], geometry.point[ 2 ] ); - sprite.scale.set( width / 10, height / 10, 1.0 ); - - sprite.userData[ 'attributes' ] = attributes; - sprite.userData[ 'objectType' ] = obj.objectType; - - if ( attributes.name ) { - - sprite.name = attributes.name; - - } - - return sprite; - - case 'Light': - - geometry = obj.geometry; - - let light; - - switch ( geometry.lightStyle.name ) { - - case 'LightStyle_WorldPoint': - - light = new PointLight(); - light.castShadow = attributes.castsShadows; - light.position.set( geometry.location[ 0 ], geometry.location[ 1 ], geometry.location[ 2 ] ); - light.shadow.normalBias = 0.1; - - break; - - case 'LightStyle_WorldSpot': - - light = new SpotLight(); - light.castShadow = attributes.castsShadows; - light.position.set( geometry.location[ 0 ], geometry.location[ 1 ], geometry.location[ 2 ] ); - light.target.position.set( geometry.direction[ 0 ], geometry.direction[ 1 ], geometry.direction[ 2 ] ); - light.angle = geometry.spotAngleRadians; - light.shadow.normalBias = 0.1; - - break; - - case 'LightStyle_WorldRectangular': - - light = new RectAreaLight(); - const width = Math.abs( geometry.width[ 2 ] ); - const height = Math.abs( geometry.length[ 0 ] ); - light.position.set( geometry.location[ 0 ] - ( height / 2 ), geometry.location[ 1 ], geometry.location[ 2 ] - ( width / 2 ) ); - light.height = height; - light.width = width; - light.lookAt( geometry.direction[ 0 ], geometry.direction[ 1 ], geometry.direction[ 2 ] ); - - break; - - case 'LightStyle_WorldDirectional': - - light = new DirectionalLight(); - light.castShadow = attributes.castsShadows; - light.position.set( geometry.location[ 0 ], geometry.location[ 1 ], geometry.location[ 2 ] ); - light.target.position.set( geometry.direction[ 0 ], geometry.direction[ 1 ], geometry.direction[ 2 ] ); - light.shadow.normalBias = 0.1; - - break; - - case 'LightStyle_WorldLinear': - // no conversion exists, warning has already been printed to the console - break; - - default: - break; - - } - - if ( light ) { - - light.intensity = geometry.intensity; - _color = geometry.diffuse; - color = new Color( _color.r / 255.0, _color.g / 255.0, _color.b / 255.0 ); - light.color = color; - light.userData[ 'attributes' ] = attributes; - light.userData[ 'objectType' ] = obj.objectType; - - } - - return light; - - } - - } - - _initLibrary() { - - if ( ! this.libraryPending ) { - - // Load rhino3dm wrapper. - const jsLoader = new FileLoader( this.manager ); - jsLoader.setPath( this.libraryPath ); - const jsContent = new Promise( ( resolve, reject ) => { - - jsLoader.load( 'rhino3dm.js', resolve, undefined, reject ); - - } ); - - // Load rhino3dm WASM binary. - const binaryLoader = new FileLoader( this.manager ); - binaryLoader.setPath( this.libraryPath ); - binaryLoader.setResponseType( 'arraybuffer' ); - const binaryContent = new Promise( ( resolve, reject ) => { - - binaryLoader.load( 'rhino3dm.wasm', resolve, undefined, reject ); - - } ); - - this.libraryPending = Promise.all( [ jsContent, binaryContent ] ) - .then( ( [ jsContent, binaryContent ] ) => { - - //this.libraryBinary = binaryContent; - this.libraryConfig.wasmBinary = binaryContent; - - const fn = Rhino3dmWorker.toString(); - - const body = [ - '/* rhino3dm.js */', - jsContent, - '/* worker */', - fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) ) - ].join( '\n' ); - - this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) ); - - } ); - - } - - return this.libraryPending; - - } - - _getWorker( taskCost ) { - - return this._initLibrary().then( () => { - - if ( this.workerPool.length < this.workerLimit ) { - - const worker = new Worker( this.workerSourceURL ); - - worker._callbacks = {}; - worker._taskCosts = {}; - worker._taskLoad = 0; - - worker.postMessage( { - type: 'init', - libraryConfig: this.libraryConfig - } ); - - worker.onmessage = e => { - - const message = e.data; - - switch ( message.type ) { - - case 'warning': - this.warnings.push( message.data ); - console.warn( message.data ); - break; - - case 'decode': - worker._callbacks[ message.id ].resolve( message ); - break; - - case 'error': - worker._callbacks[ message.id ].reject( message ); - break; - - default: - console.error( 'THREE.Rhino3dmLoader: Unexpected message, "' + message.type + '"' ); - - } - - }; - - this.workerPool.push( worker ); - - } else { - - this.workerPool.sort( function ( a, b ) { - - return a._taskLoad > b._taskLoad ? - 1 : 1; - - } ); - - } - - const worker = this.workerPool[ this.workerPool.length - 1 ]; - - worker._taskLoad += taskCost; - - return worker; - - } ); - - } - - _releaseTask( worker, taskID ) { - - worker._taskLoad -= worker._taskCosts[ taskID ]; - delete worker._callbacks[ taskID ]; - delete worker._taskCosts[ taskID ]; - - } - - dispose() { - - for ( let i = 0; i < this.workerPool.length; ++ i ) { - - this.workerPool[ i ].terminate(); - - } - - this.workerPool.length = 0; - - return this; - - } - -} - -/* WEB WORKER */ - -function Rhino3dmWorker() { - - let libraryPending; - let libraryConfig; - let rhino; - let taskID; - - onmessage = function ( e ) { - - const message = e.data; - - switch ( message.type ) { - - case 'init': - - libraryConfig = message.libraryConfig; - const wasmBinary = libraryConfig.wasmBinary; - let RhinoModule; - libraryPending = new Promise( function ( resolve ) { - - /* Like Basis Loader */ - RhinoModule = { wasmBinary, onRuntimeInitialized: resolve }; - - rhino3dm( RhinoModule ); // eslint-disable-line no-undef - - } ).then( () => { - - rhino = RhinoModule; - - } ); - - break; - - case 'decode': - - taskID = message.id; - const buffer = message.buffer; - libraryPending.then( () => { - - try { - - const data = decodeObjects( rhino, buffer ); - self.postMessage( { type: 'decode', id: message.id, data } ); - - } catch ( error ) { - - self.postMessage( { type: 'error', id: message.id, error } ); - - } - - } ); - - break; - - } - - }; - - function decodeObjects( rhino, buffer ) { - - const arr = new Uint8Array( buffer ); - const doc = rhino.File3dm.fromByteArray( arr ); - - const objects = []; - const materials = []; - const layers = []; - const views = []; - const namedViews = []; - const groups = []; - const strings = []; - - //Handle objects - - const objs = doc.objects(); - const cnt = objs.count; - - for ( let i = 0; i < cnt; i ++ ) { - - const _object = objs.get( i ); - - const object = extractObjectData( _object, doc ); - - _object.delete(); - - if ( object ) { - - objects.push( object ); - - } - - } - - // Handle instance definitions - // console.log( `Instance Definitions Count: ${doc.instanceDefinitions().count()}` ); - - for ( let i = 0; i < doc.instanceDefinitions().count; i ++ ) { - - const idef = doc.instanceDefinitions().get( i ); - const idefAttributes = extractProperties( idef ); - idefAttributes.objectIds = idef.getObjectIds(); - - objects.push( { geometry: null, attributes: idefAttributes, objectType: 'InstanceDefinition' } ); - - } - - // Handle materials - - const textureTypes = [ - // rhino.TextureType.Bitmap, - rhino.TextureType.Diffuse, - rhino.TextureType.Bump, - rhino.TextureType.Transparency, - rhino.TextureType.Opacity, - rhino.TextureType.Emap - ]; - - const pbrTextureTypes = [ - rhino.TextureType.PBR_BaseColor, - rhino.TextureType.PBR_Subsurface, - rhino.TextureType.PBR_SubsurfaceScattering, - rhino.TextureType.PBR_SubsurfaceScatteringRadius, - rhino.TextureType.PBR_Metallic, - rhino.TextureType.PBR_Specular, - rhino.TextureType.PBR_SpecularTint, - rhino.TextureType.PBR_Roughness, - rhino.TextureType.PBR_Anisotropic, - rhino.TextureType.PBR_Anisotropic_Rotation, - rhino.TextureType.PBR_Sheen, - rhino.TextureType.PBR_SheenTint, - rhino.TextureType.PBR_Clearcoat, - rhino.TextureType.PBR_ClearcoatBump, - rhino.TextureType.PBR_ClearcoatRoughness, - rhino.TextureType.PBR_OpacityIor, - rhino.TextureType.PBR_OpacityRoughness, - rhino.TextureType.PBR_Emission, - rhino.TextureType.PBR_AmbientOcclusion, - rhino.TextureType.PBR_Displacement - ]; - - for ( let i = 0; i < doc.materials().count; i ++ ) { - - const _material = doc.materials().get( i ); - - let material = extractProperties( _material ); - - const textures = []; - - textures.push( ...extractTextures( _material, textureTypes, doc ) ); - - material.pbrSupported = _material.physicallyBased().supported; - - if ( material.pbrSupported ) { - - textures.push( ...extractTextures( _material, pbrTextureTypes, doc ) ); - material.pbr = extractProperties( _material.physicallyBased() ); - - } - - material.textures = textures; - - materials.push( material ); - - _material.delete(); - - } - - // Handle layers - - for ( let i = 0; i < doc.layers().count; i ++ ) { - - const _layer = doc.layers().get( i ); - const layer = extractProperties( _layer ); - - layers.push( layer ); - - _layer.delete(); - - } - - // Handle views - - for ( let i = 0; i < doc.views().count; i ++ ) { - - const _view = doc.views().get( i ); - const view = extractProperties( _view ); - - views.push( view ); - - _view.delete(); - - } - - // Handle named views - - for ( let i = 0; i < doc.namedViews().count; i ++ ) { - - const _namedView = doc.namedViews().get( i ); - const namedView = extractProperties( _namedView ); - - namedViews.push( namedView ); - - _namedView.delete(); - - } - - // Handle groups - - for ( let i = 0; i < doc.groups().count; i ++ ) { - - const _group = doc.groups().get( i ); - const group = extractProperties( _group ); - - groups.push( group ); - - _group.delete(); - - } - - // Handle settings - - const settings = extractProperties( doc.settings() ); - - //TODO: Handle other document stuff like dimstyles, instance definitions, bitmaps etc. - - // Handle dimstyles - // console.log( `Dimstyle Count: ${doc.dimstyles().count()}` ); - - // Handle bitmaps - // console.log( `Bitmap Count: ${doc.bitmaps().count()}` ); - - // Handle strings - // console.log( `Document Strings Count: ${doc.strings().count()}` ); - // Note: doc.strings().documentUserTextCount() counts any doc.strings defined in a section - // console.log( `Document User Text Count: ${doc.strings().documentUserTextCount()}` ); - - const strings_count = doc.strings().count; - - for ( let i = 0; i < strings_count; i ++ ) { - - strings.push( doc.strings().get( i ) ); - - } - - // Handle Render Environments for Material Environment - - // get the id of the active render environment skylight, which we'll use for environment texture - const reflectionId = doc.settings().renderSettings().renderEnvironments.reflectionId - - const rc = doc.renderContent() - - let renderEnvironment = null - - for( let i = 0; i < rc.count; i++ ) { - - const content = rc.get(i) - - switch( content.kind ) { - - case 'environment': - - const id = content.id - - // there could be multiple render environments in a 3dm file - if ( id !== reflectionId ) break; - - const renderTexture = content.findChild( 'texture' ) - const fileName = renderTexture.fileName - - for ( let j = 0; j < doc.embeddedFiles().count; j ++ ) { - - const _fileName = doc.embeddedFiles().get( j ).fileName - - if ( fileName === _fileName ) { - - const background = doc.getEmbeddedFileAsBase64( fileName ) - const backgroundImage = 'data:image/png;base64,' + background - renderEnvironment = { type: 'renderEnvironment', image: backgroundImage, name: fileName }; - - } - - } - - break; - - } - - } - - // Handle Render Settings - - const renderSettings = { - ambientLight: doc.settings().renderSettings().ambientLight, - backgroundColorTop: doc.settings().renderSettings().backgroundColorTop, - backgroundColorBottom: doc.settings().renderSettings().backgroundColorBottom, - useHiddenLights: doc.settings().renderSettings().useHiddenLights, - depthCue: doc.settings().renderSettings().depthCue, - flatShade: doc.settings().renderSettings().flatShade, - renderBackFaces: doc.settings().renderSettings().renderBackFaces, - renderPoints: doc.settings().renderSettings().renderPoints, - renderCurves: doc.settings().renderSettings().renderCurves, - renderIsoParams: doc.settings().renderSettings().renderIsoParams, - renderMeshEdges: doc.settings().renderSettings().renderMeshEdges, - renderAnnotations: doc.settings().renderSettings().renderAnnotations, - useViewportSize: doc.settings().renderSettings().useViewportSize, - scaleBackgroundToFit: doc.settings().renderSettings().scaleBackgroundToFit, - transparentBackground: doc.settings().renderSettings().transparentBackground, - imageDpi: doc.settings().renderSettings().imageDpi, - shadowMapLevel: doc.settings().renderSettings().shadowMapLevel, - namedView: doc.settings().renderSettings().namedView, - snapShot: doc.settings().renderSettings().snapShot, - specificViewport: doc.settings().renderSettings().specificViewport, - groundPlane: extractProperties( doc.settings().renderSettings().groundPlane ), - safeFrame: extractProperties( doc.settings().renderSettings().safeFrame ), - dithering: extractProperties( doc.settings().renderSettings().dithering ), - skylight: extractProperties( doc.settings().renderSettings().skylight ), - linearWorkflow: extractProperties( doc.settings().renderSettings().linearWorkflow ), - renderChannels: extractProperties( doc.settings().renderSettings().renderChannels ), - sun: extractProperties( doc.settings().renderSettings().sun ), - renderEnvironments: extractProperties( doc.settings().renderSettings().renderEnvironments ), - postEffects: extractProperties( doc.settings().renderSettings().postEffects ), - - } - - doc.delete(); - - return { objects, materials, layers, views, namedViews, groups, strings, settings, renderSettings, renderEnvironment }; - - } - - function extractTextures( m, tTypes, d ) { - - const textures = [] - - for ( let i = 0; i < tTypes.length; i ++ ) { - - const _texture = m.getTexture( tTypes[ i ] ); - if ( _texture ) { - - let textureType = tTypes[ i ].constructor.name; - textureType = textureType.substring( 12, textureType.length ); - const texture = extractTextureData( _texture, textureType, d ); - textures.push( texture ); - _texture.delete(); - - } - - } - - return textures; - - } - - function extractTextureData( t, tType, d ) { - - const texture = { type: tType }; - - const image = d.getEmbeddedFileAsBase64( t.fileName ); - - texture.wrapU = t.wrapU; - texture.wrapV = t.wrapV; - texture.wrapW = t.wrapW; - const uvw = t.uvwTransform.toFloatArray( true ); - - texture.repeat = [ uvw[ 0 ], uvw[ 5 ] ]; - - if ( image ) { - - texture.image = 'data:image/png;base64,' + image; - - } else { - - self.postMessage( { type: 'warning', id: taskID, data: { - message: `THREE.3DMLoader: Image for ${tType} texture not embedded in file.`, - type: 'missing resource' - } - - } ); - - texture.image = null; - - } - - return texture; - - } - - function extractObjectData( object, doc ) { - - const _geometry = object.geometry(); - const _attributes = object.attributes(); - let objectType = _geometry.objectType; - let geometry, attributes, position, data, mesh; - - // skip instance definition objects - //if( _attributes.isInstanceDefinitionObject ) { continue; } - - // TODO: handle other geometry types - switch ( objectType ) { - - case rhino.ObjectType.Curve: - - const pts = curveToPoints( _geometry, 100 ); - - position = {}; - attributes = {}; - data = {}; - - position.itemSize = 3; - position.type = 'Float32Array'; - position.array = []; - - for ( let j = 0; j < pts.length; j ++ ) { - - position.array.push( pts[ j ][ 0 ] ); - position.array.push( pts[ j ][ 1 ] ); - position.array.push( pts[ j ][ 2 ] ); - - } - - attributes.position = position; - data.attributes = attributes; - - geometry = { data }; - - break; - - case rhino.ObjectType.Point: - - const pt = _geometry.location; - - position = {}; - const color = {}; - attributes = {}; - data = {}; - - position.itemSize = 3; - position.type = 'Float32Array'; - position.array = [ pt[ 0 ], pt[ 1 ], pt[ 2 ] ]; - - const _color = _attributes.drawColor( doc ); - - color.itemSize = 3; - color.type = 'Float32Array'; - color.array = [ _color.r / 255.0, _color.g / 255.0, _color.b / 255.0 ]; - - attributes.position = position; - attributes.color = color; - data.attributes = attributes; - - geometry = { data }; - - break; - - case rhino.ObjectType.PointSet: - case rhino.ObjectType.Mesh: - - geometry = _geometry.toThreejsJSON(); - - break; - - case rhino.ObjectType.Brep: - - const faces = _geometry.faces(); - mesh = new rhino.Mesh(); - - for ( let faceIndex = 0; faceIndex < faces.count; faceIndex ++ ) { - - const face = faces.get( faceIndex ); - const _mesh = face.getMesh( rhino.MeshType.Any ); - - if ( _mesh ) { - - mesh.append( _mesh ); - _mesh.delete(); - - } - - face.delete(); - - } - - if ( mesh.faces().count > 0 ) { - - mesh.compact(); - geometry = mesh.toThreejsJSON(); - faces.delete(); - - } - - mesh.delete(); - - break; - - case rhino.ObjectType.Extrusion: - - mesh = _geometry.getMesh( rhino.MeshType.Any ); - - if ( mesh ) { - - geometry = mesh.toThreejsJSON(); - mesh.delete(); - - } - - break; - - case rhino.ObjectType.TextDot: - - geometry = extractProperties( _geometry ); - - break; - - case rhino.ObjectType.Light: - - geometry = extractProperties( _geometry ); - - if ( geometry.lightStyle.name === 'LightStyle_WorldLinear' ) { - - self.postMessage( { type: 'warning', id: taskID, data: { - message: `THREE.3DMLoader: No conversion exists for ${objectType.constructor.name} ${geometry.lightStyle.name}`, - type: 'no conversion', - guid: _attributes.id - } - - } ); - - } - - break; - - case rhino.ObjectType.InstanceReference: - - geometry = extractProperties( _geometry ); - geometry.xform = extractProperties( _geometry.xform ); - geometry.xform.array = _geometry.xform.toFloatArray( true ); - - break; - - case rhino.ObjectType.SubD: - - // TODO: precalculate resulting vertices and faces and warn on excessive results - _geometry.subdivide( 3 ); - mesh = rhino.Mesh.createFromSubDControlNet( _geometry ); - if ( mesh ) { - - geometry = mesh.toThreejsJSON(); - mesh.delete(); - - } - - break; - - /* - case rhino.ObjectType.Annotation: - case rhino.ObjectType.Hatch: - case rhino.ObjectType.ClipPlane: - */ - - default: - - self.postMessage( { type: 'warning', id: taskID, data: { - message: `THREE.3DMLoader: Conversion not implemented for ${objectType.constructor.name}`, - type: 'not implemented', - guid: _attributes.id - } - - } ); - - break; - - } - - if ( geometry ) { - - attributes = extractProperties( _attributes ); - attributes.geometry = extractProperties( _geometry ); - - if ( _attributes.groupCount > 0 ) { - - attributes.groupIds = _attributes.getGroupList(); - - } - - if ( _attributes.userStringCount > 0 ) { - - attributes.userStrings = _attributes.getUserStrings(); - - } - - if ( _geometry.userStringCount > 0 ) { - - attributes.geometry.userStrings = _geometry.getUserStrings(); - - } - - if ( _attributes.decals().count > 0 ) { - - self.postMessage( { type: 'warning', id: taskID, data: { - message: `THREE.3DMLoader: No conversion exists for the decals associated with this object.`, - type: 'no conversion', - guid: _attributes.id - } - - } ); - - } - - attributes.drawColor = _attributes.drawColor( doc ); - - objectType = objectType.constructor.name; - objectType = objectType.substring( 11, objectType.length ); - - return { geometry, attributes, objectType }; - - } else { - - self.postMessage( { type: 'warning', id: taskID, data: { - message: `THREE.3DMLoader: ${objectType.constructor.name} has no associated mesh geometry.`, - type: 'missing mesh', - guid: _attributes.id - } - - } ); - - } - - } - - function extractProperties( object ) { - - const result = {}; - - for ( const property in object ) { - - const value = object[ property ]; - - if ( typeof value !== 'function' ) { - - if ( typeof value === 'object' && value !== null && value.hasOwnProperty( 'constructor' ) ) { - - result[ property ] = { name: value.constructor.name, value: value.value }; - - } else if ( typeof value === 'object' && value !== null ) { - - result[ property ] = extractProperties( value ); - - } else { - - result[ property ] = value; - - } - - } else { - - // these are functions that could be called to extract more data. - //console.log( `${property}: ${object[ property ].constructor.name}` ); - - } - - } - - return result; - - } - - function curveToPoints( curve, pointLimit ) { - - let pointCount = pointLimit; - let rc = []; - const ts = []; - - if ( curve instanceof rhino.LineCurve ) { - - return [ curve.pointAtStart, curve.pointAtEnd ]; - - } - - if ( curve instanceof rhino.PolylineCurve ) { - - pointCount = curve.pointCount; - for ( let i = 0; i < pointCount; i ++ ) { - - rc.push( curve.point( i ) ); - - } - - return rc; - - } - - if ( curve instanceof rhino.PolyCurve ) { - - const segmentCount = curve.segmentCount; - - for ( let i = 0; i < segmentCount; i ++ ) { - - const segment = curve.segmentCurve( i ); - const segmentArray = curveToPoints( segment, pointCount ); - rc = rc.concat( segmentArray ); - segment.delete(); - - } - - return rc; - - } - - if ( curve instanceof rhino.ArcCurve ) { - - pointCount = Math.floor( curve.angleDegrees / 5 ); - pointCount = pointCount < 2 ? 2 : pointCount; - // alternative to this hardcoded version: https://stackoverflow.com/a/18499923/2179399 - - } - - if ( curve instanceof rhino.NurbsCurve && curve.degree === 1 ) { - - const pLine = curve.tryGetPolyline(); - - for ( let i = 0; i < pLine.count; i ++ ) { - - rc.push( pLine.get( i ) ); - - } - - pLine.delete(); - - return rc; - - } - - const domain = curve.domain; - const divisions = pointCount - 1.0; - - for ( let j = 0; j < pointCount; j ++ ) { - - const t = domain[ 0 ] + ( j / divisions ) * ( domain[ 1 ] - domain[ 0 ] ); - - if ( t === domain[ 0 ] || t === domain[ 1 ] ) { - - ts.push( t ); - continue; - - } - - const tan = curve.tangentAt( t ); - const prevTan = curve.tangentAt( ts.slice( - 1 )[ 0 ] ); - - // Duplicated from THREE.Vector3 - // How to pass imports to worker? - - const tS = tan[ 0 ] * tan[ 0 ] + tan[ 1 ] * tan[ 1 ] + tan[ 2 ] * tan[ 2 ]; - const ptS = prevTan[ 0 ] * prevTan[ 0 ] + prevTan[ 1 ] * prevTan[ 1 ] + prevTan[ 2 ] * prevTan[ 2 ]; - - const denominator = Math.sqrt( tS * ptS ); - - let angle; - - if ( denominator === 0 ) { - - angle = Math.PI / 2; - - } else { - - const theta = ( tan.x * prevTan.x + tan.y * prevTan.y + tan.z * prevTan.z ) / denominator; - angle = Math.acos( Math.max( - 1, Math.min( 1, theta ) ) ); - - } - - if ( angle < 0.1 ) continue; - - ts.push( t ); - - } - - rc = ts.map( t => curve.pointAt( t ) ); - return rc; - - } - -} - -export { Rhino3dmLoader }; diff --git a/public/assets/lib/vendor/three/EXRLoader.js b/public/assets/lib/vendor/three/EXRLoader.js deleted file mode 100644 index deb77553..00000000 --- a/public/assets/lib/vendor/three/EXRLoader.js +++ /dev/null @@ -1,2310 +0,0 @@ -// @ts-nocheck -import { - DataTextureLoader, - DataUtils, - FloatType, - HalfFloatType, - NoColorSpace, - LinearFilter, - LinearSRGBColorSpace, - RedFormat, - RGBAFormat -} from './three.module.js'; -import * as fflate from './libs/fflate.module.js'; - -/** - * OpenEXR loader currently supports uncompressed, ZIP(S), RLE, PIZ and DWA/B compression. - * Supports reading as UnsignedByte, HalfFloat and Float type data texture. - * - * Referred to the original Industrial Light & Magic OpenEXR implementation and the TinyEXR / Syoyo Fujita - * implementation, so I have preserved their copyright notices. - */ - -// /* -// Copyright (c) 2014 - 2017, Syoyo Fujita -// All rights reserved. - -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// * Neither the name of the Syoyo Fujita nor the -// names of its contributors may be used to endorse or promote products -// derived from this software without specific prior written permission. - -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY -// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// */ - -// // TinyEXR contains some OpenEXR code, which is licensed under ------------ - -// /////////////////////////////////////////////////////////////////////////// -// // -// // Copyright (c) 2002, Industrial Light & Magic, a division of Lucas -// // Digital Ltd. LLC -// // -// // All rights reserved. -// // -// // Redistribution and use in source and binary forms, with or without -// // modification, are permitted provided that the following conditions are -// // met: -// // * Redistributions of source code must retain the above copyright -// // notice, this list of conditions and the following disclaimer. -// // * Redistributions in binary form must reproduce the above -// // copyright notice, this list of conditions and the following disclaimer -// // in the documentation and/or other materials provided with the -// // distribution. -// // * Neither the name of Industrial Light & Magic nor the names of -// // its contributors may be used to endorse or promote products derived -// // from this software without specific prior written permission. -// // -// // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// // -// /////////////////////////////////////////////////////////////////////////// - -// // End of OpenEXR license ------------------------------------------------- - -class EXRLoader extends DataTextureLoader { - - constructor( manager ) { - - super( manager ); - - this.type = HalfFloatType; - - } - - parse( buffer ) { - - const USHORT_RANGE = ( 1 << 16 ); - const BITMAP_SIZE = ( USHORT_RANGE >> 3 ); - - const HUF_ENCBITS = 16; // literal (value) bit length - const HUF_DECBITS = 14; // decoding bit size (>= 8) - - const HUF_ENCSIZE = ( 1 << HUF_ENCBITS ) + 1; // encoding table size - const HUF_DECSIZE = 1 << HUF_DECBITS; // decoding table size - const HUF_DECMASK = HUF_DECSIZE - 1; - - const NBITS = 16; - const A_OFFSET = 1 << ( NBITS - 1 ); - const MOD_MASK = ( 1 << NBITS ) - 1; - - const SHORT_ZEROCODE_RUN = 59; - const LONG_ZEROCODE_RUN = 63; - const SHORTEST_LONG_RUN = 2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN; - - const ULONG_SIZE = 8; - const FLOAT32_SIZE = 4; - const INT32_SIZE = 4; - const INT16_SIZE = 2; - const INT8_SIZE = 1; - - const STATIC_HUFFMAN = 0; - const DEFLATE = 1; - - const UNKNOWN = 0; - const LOSSY_DCT = 1; - const RLE = 2; - - const logBase = Math.pow( 2.7182818, 2.2 ); - - function reverseLutFromBitmap( bitmap, lut ) { - - let k = 0; - - for ( let i = 0; i < USHORT_RANGE; ++ i ) { - - if ( ( i == 0 ) || ( bitmap[ i >> 3 ] & ( 1 << ( i & 7 ) ) ) ) { - - lut[ k ++ ] = i; - - } - - } - - const n = k - 1; - - while ( k < USHORT_RANGE ) lut[ k ++ ] = 0; - - return n; - - } - - function hufClearDecTable( hdec ) { - - for ( let i = 0; i < HUF_DECSIZE; i ++ ) { - - hdec[ i ] = {}; - hdec[ i ].len = 0; - hdec[ i ].lit = 0; - hdec[ i ].p = null; - - } - - } - - const getBitsReturn = { l: 0, c: 0, lc: 0 }; - - function getBits( nBits, c, lc, uInt8Array, inOffset ) { - - while ( lc < nBits ) { - - c = ( c << 8 ) | parseUint8Array( uInt8Array, inOffset ); - lc += 8; - - } - - lc -= nBits; - - getBitsReturn.l = ( c >> lc ) & ( ( 1 << nBits ) - 1 ); - getBitsReturn.c = c; - getBitsReturn.lc = lc; - - } - - const hufTableBuffer = new Array( 59 ); - - function hufCanonicalCodeTable( hcode ) { - - for ( let i = 0; i <= 58; ++ i ) hufTableBuffer[ i ] = 0; - for ( let i = 0; i < HUF_ENCSIZE; ++ i ) hufTableBuffer[ hcode[ i ] ] += 1; - - let c = 0; - - for ( let i = 58; i > 0; -- i ) { - - const nc = ( ( c + hufTableBuffer[ i ] ) >> 1 ); - hufTableBuffer[ i ] = c; - c = nc; - - } - - for ( let i = 0; i < HUF_ENCSIZE; ++ i ) { - - const l = hcode[ i ]; - if ( l > 0 ) hcode[ i ] = l | ( hufTableBuffer[ l ] ++ << 6 ); - - } - - } - - function hufUnpackEncTable( uInt8Array, inOffset, ni, im, iM, hcode ) { - - const p = inOffset; - let c = 0; - let lc = 0; - - for ( ; im <= iM; im ++ ) { - - if ( p.value - inOffset.value > ni ) return false; - - getBits( 6, c, lc, uInt8Array, p ); - - const l = getBitsReturn.l; - c = getBitsReturn.c; - lc = getBitsReturn.lc; - - hcode[ im ] = l; - - if ( l == LONG_ZEROCODE_RUN ) { - - if ( p.value - inOffset.value > ni ) { - - throw new Error( 'Something wrong with hufUnpackEncTable' ); - - } - - getBits( 8, c, lc, uInt8Array, p ); - - let zerun = getBitsReturn.l + SHORTEST_LONG_RUN; - c = getBitsReturn.c; - lc = getBitsReturn.lc; - - if ( im + zerun > iM + 1 ) { - - throw new Error( 'Something wrong with hufUnpackEncTable' ); - - } - - while ( zerun -- ) hcode[ im ++ ] = 0; - - im --; - - } else if ( l >= SHORT_ZEROCODE_RUN ) { - - let zerun = l - SHORT_ZEROCODE_RUN + 2; - - if ( im + zerun > iM + 1 ) { - - throw new Error( 'Something wrong with hufUnpackEncTable' ); - - } - - while ( zerun -- ) hcode[ im ++ ] = 0; - - im --; - - } - - } - - hufCanonicalCodeTable( hcode ); - - } - - function hufLength( code ) { - - return code & 63; - - } - - function hufCode( code ) { - - return code >> 6; - - } - - function hufBuildDecTable( hcode, im, iM, hdecod ) { - - for ( ; im <= iM; im ++ ) { - - const c = hufCode( hcode[ im ] ); - const l = hufLength( hcode[ im ] ); - - if ( c >> l ) { - - throw new Error( 'Invalid table entry' ); - - } - - if ( l > HUF_DECBITS ) { - - const pl = hdecod[ ( c >> ( l - HUF_DECBITS ) ) ]; - - if ( pl.len ) { - - throw new Error( 'Invalid table entry' ); - - } - - pl.lit ++; - - if ( pl.p ) { - - const p = pl.p; - pl.p = new Array( pl.lit ); - - for ( let i = 0; i < pl.lit - 1; ++ i ) { - - pl.p[ i ] = p[ i ]; - - } - - } else { - - pl.p = new Array( 1 ); - - } - - pl.p[ pl.lit - 1 ] = im; - - } else if ( l ) { - - let plOffset = 0; - - for ( let i = 1 << ( HUF_DECBITS - l ); i > 0; i -- ) { - - const pl = hdecod[ ( c << ( HUF_DECBITS - l ) ) + plOffset ]; - - if ( pl.len || pl.p ) { - - throw new Error( 'Invalid table entry' ); - - } - - pl.len = l; - pl.lit = im; - - plOffset ++; - - } - - } - - } - - return true; - - } - - const getCharReturn = { c: 0, lc: 0 }; - - function getChar( c, lc, uInt8Array, inOffset ) { - - c = ( c << 8 ) | parseUint8Array( uInt8Array, inOffset ); - lc += 8; - - getCharReturn.c = c; - getCharReturn.lc = lc; - - } - - const getCodeReturn = { c: 0, lc: 0 }; - - function getCode( po, rlc, c, lc, uInt8Array, inOffset, outBuffer, outBufferOffset, outBufferEndOffset ) { - - if ( po == rlc ) { - - if ( lc < 8 ) { - - getChar( c, lc, uInt8Array, inOffset ); - c = getCharReturn.c; - lc = getCharReturn.lc; - - } - - lc -= 8; - - let cs = ( c >> lc ); - cs = new Uint8Array( [ cs ] )[ 0 ]; - - if ( outBufferOffset.value + cs > outBufferEndOffset ) { - - return false; - - } - - const s = outBuffer[ outBufferOffset.value - 1 ]; - - while ( cs -- > 0 ) { - - outBuffer[ outBufferOffset.value ++ ] = s; - - } - - } else if ( outBufferOffset.value < outBufferEndOffset ) { - - outBuffer[ outBufferOffset.value ++ ] = po; - - } else { - - return false; - - } - - getCodeReturn.c = c; - getCodeReturn.lc = lc; - - } - - function UInt16( value ) { - - return ( value & 0xFFFF ); - - } - - function Int16( value ) { - - const ref = UInt16( value ); - return ( ref > 0x7FFF ) ? ref - 0x10000 : ref; - - } - - const wdec14Return = { a: 0, b: 0 }; - - function wdec14( l, h ) { - - const ls = Int16( l ); - const hs = Int16( h ); - - const hi = hs; - const ai = ls + ( hi & 1 ) + ( hi >> 1 ); - - const as = ai; - const bs = ai - hi; - - wdec14Return.a = as; - wdec14Return.b = bs; - - } - - function wdec16( l, h ) { - - const m = UInt16( l ); - const d = UInt16( h ); - - const bb = ( m - ( d >> 1 ) ) & MOD_MASK; - const aa = ( d + bb - A_OFFSET ) & MOD_MASK; - - wdec14Return.a = aa; - wdec14Return.b = bb; - - } - - function wav2Decode( buffer, j, nx, ox, ny, oy, mx ) { - - const w14 = mx < ( 1 << 14 ); - const n = ( nx > ny ) ? ny : nx; - let p = 1; - let p2; - let py; - - while ( p <= n ) p <<= 1; - - p >>= 1; - p2 = p; - p >>= 1; - - while ( p >= 1 ) { - - py = 0; - const ey = py + oy * ( ny - p2 ); - const oy1 = oy * p; - const oy2 = oy * p2; - const ox1 = ox * p; - const ox2 = ox * p2; - let i00, i01, i10, i11; - - for ( ; py <= ey; py += oy2 ) { - - let px = py; - const ex = py + ox * ( nx - p2 ); - - for ( ; px <= ex; px += ox2 ) { - - const p01 = px + ox1; - const p10 = px + oy1; - const p11 = p10 + ox1; - - if ( w14 ) { - - wdec14( buffer[ px + j ], buffer[ p10 + j ] ); - - i00 = wdec14Return.a; - i10 = wdec14Return.b; - - wdec14( buffer[ p01 + j ], buffer[ p11 + j ] ); - - i01 = wdec14Return.a; - i11 = wdec14Return.b; - - wdec14( i00, i01 ); - - buffer[ px + j ] = wdec14Return.a; - buffer[ p01 + j ] = wdec14Return.b; - - wdec14( i10, i11 ); - - buffer[ p10 + j ] = wdec14Return.a; - buffer[ p11 + j ] = wdec14Return.b; - - } else { - - wdec16( buffer[ px + j ], buffer[ p10 + j ] ); - - i00 = wdec14Return.a; - i10 = wdec14Return.b; - - wdec16( buffer[ p01 + j ], buffer[ p11 + j ] ); - - i01 = wdec14Return.a; - i11 = wdec14Return.b; - - wdec16( i00, i01 ); - - buffer[ px + j ] = wdec14Return.a; - buffer[ p01 + j ] = wdec14Return.b; - - wdec16( i10, i11 ); - - buffer[ p10 + j ] = wdec14Return.a; - buffer[ p11 + j ] = wdec14Return.b; - - - } - - } - - if ( nx & p ) { - - const p10 = px + oy1; - - if ( w14 ) - wdec14( buffer[ px + j ], buffer[ p10 + j ] ); - else - wdec16( buffer[ px + j ], buffer[ p10 + j ] ); - - i00 = wdec14Return.a; - buffer[ p10 + j ] = wdec14Return.b; - - buffer[ px + j ] = i00; - - } - - } - - if ( ny & p ) { - - let px = py; - const ex = py + ox * ( nx - p2 ); - - for ( ; px <= ex; px += ox2 ) { - - const p01 = px + ox1; - - if ( w14 ) - wdec14( buffer[ px + j ], buffer[ p01 + j ] ); - else - wdec16( buffer[ px + j ], buffer[ p01 + j ] ); - - i00 = wdec14Return.a; - buffer[ p01 + j ] = wdec14Return.b; - - buffer[ px + j ] = i00; - - } - - } - - p2 = p; - p >>= 1; - - } - - return py; - - } - - function hufDecode( encodingTable, decodingTable, uInt8Array, inOffset, ni, rlc, no, outBuffer, outOffset ) { - - let c = 0; - let lc = 0; - const outBufferEndOffset = no; - const inOffsetEnd = Math.trunc( inOffset.value + ( ni + 7 ) / 8 ); - - while ( inOffset.value < inOffsetEnd ) { - - getChar( c, lc, uInt8Array, inOffset ); - - c = getCharReturn.c; - lc = getCharReturn.lc; - - while ( lc >= HUF_DECBITS ) { - - const index = ( c >> ( lc - HUF_DECBITS ) ) & HUF_DECMASK; - const pl = decodingTable[ index ]; - - if ( pl.len ) { - - lc -= pl.len; - - getCode( pl.lit, rlc, c, lc, uInt8Array, inOffset, outBuffer, outOffset, outBufferEndOffset ); - - c = getCodeReturn.c; - lc = getCodeReturn.lc; - - } else { - - if ( ! pl.p ) { - - throw new Error( 'hufDecode issues' ); - - } - - let j; - - for ( j = 0; j < pl.lit; j ++ ) { - - const l = hufLength( encodingTable[ pl.p[ j ] ] ); - - while ( lc < l && inOffset.value < inOffsetEnd ) { - - getChar( c, lc, uInt8Array, inOffset ); - - c = getCharReturn.c; - lc = getCharReturn.lc; - - } - - if ( lc >= l ) { - - if ( hufCode( encodingTable[ pl.p[ j ] ] ) == ( ( c >> ( lc - l ) ) & ( ( 1 << l ) - 1 ) ) ) { - - lc -= l; - - getCode( pl.p[ j ], rlc, c, lc, uInt8Array, inOffset, outBuffer, outOffset, outBufferEndOffset ); - - c = getCodeReturn.c; - lc = getCodeReturn.lc; - - break; - - } - - } - - } - - if ( j == pl.lit ) { - - throw new Error( 'hufDecode issues' ); - - } - - } - - } - - } - - const i = ( 8 - ni ) & 7; - - c >>= i; - lc -= i; - - while ( lc > 0 ) { - - const pl = decodingTable[ ( c << ( HUF_DECBITS - lc ) ) & HUF_DECMASK ]; - - if ( pl.len ) { - - lc -= pl.len; - - getCode( pl.lit, rlc, c, lc, uInt8Array, inOffset, outBuffer, outOffset, outBufferEndOffset ); - - c = getCodeReturn.c; - lc = getCodeReturn.lc; - - } else { - - throw new Error( 'hufDecode issues' ); - - } - - } - - return true; - - } - - function hufUncompress( uInt8Array, inDataView, inOffset, nCompressed, outBuffer, nRaw ) { - - const outOffset = { value: 0 }; - const initialInOffset = inOffset.value; - - const im = parseUint32( inDataView, inOffset ); - const iM = parseUint32( inDataView, inOffset ); - - inOffset.value += 4; - - const nBits = parseUint32( inDataView, inOffset ); - - inOffset.value += 4; - - if ( im < 0 || im >= HUF_ENCSIZE || iM < 0 || iM >= HUF_ENCSIZE ) { - - throw new Error( 'Something wrong with HUF_ENCSIZE' ); - - } - - const freq = new Array( HUF_ENCSIZE ); - const hdec = new Array( HUF_DECSIZE ); - - hufClearDecTable( hdec ); - - const ni = nCompressed - ( inOffset.value - initialInOffset ); - - hufUnpackEncTable( uInt8Array, inOffset, ni, im, iM, freq ); - - if ( nBits > 8 * ( nCompressed - ( inOffset.value - initialInOffset ) ) ) { - - throw new Error( 'Something wrong with hufUncompress' ); - - } - - hufBuildDecTable( freq, im, iM, hdec ); - - hufDecode( freq, hdec, uInt8Array, inOffset, nBits, iM, nRaw, outBuffer, outOffset ); - - } - - function applyLut( lut, data, nData ) { - - for ( let i = 0; i < nData; ++ i ) { - - data[ i ] = lut[ data[ i ] ]; - - } - - } - - function predictor( source ) { - - for ( let t = 1; t < source.length; t ++ ) { - - const d = source[ t - 1 ] + source[ t ] - 128; - source[ t ] = d; - - } - - } - - function interleaveScalar( source, out ) { - - let t1 = 0; - let t2 = Math.floor( ( source.length + 1 ) / 2 ); - let s = 0; - const stop = source.length - 1; - - while ( true ) { - - if ( s > stop ) break; - out[ s ++ ] = source[ t1 ++ ]; - - if ( s > stop ) break; - out[ s ++ ] = source[ t2 ++ ]; - - } - - } - - function decodeRunLength( source ) { - - let size = source.byteLength; - const out = new Array(); - let p = 0; - - const reader = new DataView( source ); - - while ( size > 0 ) { - - const l = reader.getInt8( p ++ ); - - if ( l < 0 ) { - - const count = - l; - size -= count + 1; - - for ( let i = 0; i < count; i ++ ) { - - out.push( reader.getUint8( p ++ ) ); - - } - - - } else { - - const count = l; - size -= 2; - - const value = reader.getUint8( p ++ ); - - for ( let i = 0; i < count + 1; i ++ ) { - - out.push( value ); - - } - - } - - } - - return out; - - } - - function lossyDctDecode( cscSet, rowPtrs, channelData, acBuffer, dcBuffer, outBuffer ) { - - let dataView = new DataView( outBuffer.buffer ); - - const width = channelData[ cscSet.idx[ 0 ] ].width; - const height = channelData[ cscSet.idx[ 0 ] ].height; - - const numComp = 3; - - const numFullBlocksX = Math.floor( width / 8.0 ); - const numBlocksX = Math.ceil( width / 8.0 ); - const numBlocksY = Math.ceil( height / 8.0 ); - const leftoverX = width - ( numBlocksX - 1 ) * 8; - const leftoverY = height - ( numBlocksY - 1 ) * 8; - - const currAcComp = { value: 0 }; - const currDcComp = new Array( numComp ); - const dctData = new Array( numComp ); - const halfZigBlock = new Array( numComp ); - const rowBlock = new Array( numComp ); - const rowOffsets = new Array( numComp ); - - for ( let comp = 0; comp < numComp; ++ comp ) { - - rowOffsets[ comp ] = rowPtrs[ cscSet.idx[ comp ] ]; - currDcComp[ comp ] = ( comp < 1 ) ? 0 : currDcComp[ comp - 1 ] + numBlocksX * numBlocksY; - dctData[ comp ] = new Float32Array( 64 ); - halfZigBlock[ comp ] = new Uint16Array( 64 ); - rowBlock[ comp ] = new Uint16Array( numBlocksX * 64 ); - - } - - for ( let blocky = 0; blocky < numBlocksY; ++ blocky ) { - - let maxY = 8; - - if ( blocky == numBlocksY - 1 ) - maxY = leftoverY; - - let maxX = 8; - - for ( let blockx = 0; blockx < numBlocksX; ++ blockx ) { - - if ( blockx == numBlocksX - 1 ) - maxX = leftoverX; - - for ( let comp = 0; comp < numComp; ++ comp ) { - - halfZigBlock[ comp ].fill( 0 ); - - // set block DC component - halfZigBlock[ comp ][ 0 ] = dcBuffer[ currDcComp[ comp ] ++ ]; - // set block AC components - unRleAC( currAcComp, acBuffer, halfZigBlock[ comp ] ); - - // UnZigZag block to float - unZigZag( halfZigBlock[ comp ], dctData[ comp ] ); - // decode float dct - dctInverse( dctData[ comp ] ); - - } - - if ( numComp == 3 ) { - - csc709Inverse( dctData ); - - } - - for ( let comp = 0; comp < numComp; ++ comp ) { - - convertToHalf( dctData[ comp ], rowBlock[ comp ], blockx * 64 ); - - } - - } // blockx - - let offset = 0; - - for ( let comp = 0; comp < numComp; ++ comp ) { - - const type = channelData[ cscSet.idx[ comp ] ].type; - - for ( let y = 8 * blocky; y < 8 * blocky + maxY; ++ y ) { - - offset = rowOffsets[ comp ][ y ]; - - for ( let blockx = 0; blockx < numFullBlocksX; ++ blockx ) { - - const src = blockx * 64 + ( ( y & 0x7 ) * 8 ); - - dataView.setUint16( offset + 0 * INT16_SIZE * type, rowBlock[ comp ][ src + 0 ], true ); - dataView.setUint16( offset + 1 * INT16_SIZE * type, rowBlock[ comp ][ src + 1 ], true ); - dataView.setUint16( offset + 2 * INT16_SIZE * type, rowBlock[ comp ][ src + 2 ], true ); - dataView.setUint16( offset + 3 * INT16_SIZE * type, rowBlock[ comp ][ src + 3 ], true ); - - dataView.setUint16( offset + 4 * INT16_SIZE * type, rowBlock[ comp ][ src + 4 ], true ); - dataView.setUint16( offset + 5 * INT16_SIZE * type, rowBlock[ comp ][ src + 5 ], true ); - dataView.setUint16( offset + 6 * INT16_SIZE * type, rowBlock[ comp ][ src + 6 ], true ); - dataView.setUint16( offset + 7 * INT16_SIZE * type, rowBlock[ comp ][ src + 7 ], true ); - - offset += 8 * INT16_SIZE * type; - - } - - } - - // handle partial X blocks - if ( numFullBlocksX != numBlocksX ) { - - for ( let y = 8 * blocky; y < 8 * blocky + maxY; ++ y ) { - - const offset = rowOffsets[ comp ][ y ] + 8 * numFullBlocksX * INT16_SIZE * type; - const src = numFullBlocksX * 64 + ( ( y & 0x7 ) * 8 ); - - for ( let x = 0; x < maxX; ++ x ) { - - dataView.setUint16( offset + x * INT16_SIZE * type, rowBlock[ comp ][ src + x ], true ); - - } - - } - - } - - } // comp - - } // blocky - - const halfRow = new Uint16Array( width ); - dataView = new DataView( outBuffer.buffer ); - - // convert channels back to float, if needed - for ( let comp = 0; comp < numComp; ++ comp ) { - - channelData[ cscSet.idx[ comp ] ].decoded = true; - const type = channelData[ cscSet.idx[ comp ] ].type; - - if ( channelData[ comp ].type != 2 ) continue; - - for ( let y = 0; y < height; ++ y ) { - - const offset = rowOffsets[ comp ][ y ]; - - for ( let x = 0; x < width; ++ x ) { - - halfRow[ x ] = dataView.getUint16( offset + x * INT16_SIZE * type, true ); - - } - - for ( let x = 0; x < width; ++ x ) { - - dataView.setFloat32( offset + x * INT16_SIZE * type, decodeFloat16( halfRow[ x ] ), true ); - - } - - } - - } - - } - - function unRleAC( currAcComp, acBuffer, halfZigBlock ) { - - let acValue; - let dctComp = 1; - - while ( dctComp < 64 ) { - - acValue = acBuffer[ currAcComp.value ]; - - if ( acValue == 0xff00 ) { - - dctComp = 64; - - } else if ( acValue >> 8 == 0xff ) { - - dctComp += acValue & 0xff; - - } else { - - halfZigBlock[ dctComp ] = acValue; - dctComp ++; - - } - - currAcComp.value ++; - - } - - } - - function unZigZag( src, dst ) { - - dst[ 0 ] = decodeFloat16( src[ 0 ] ); - dst[ 1 ] = decodeFloat16( src[ 1 ] ); - dst[ 2 ] = decodeFloat16( src[ 5 ] ); - dst[ 3 ] = decodeFloat16( src[ 6 ] ); - dst[ 4 ] = decodeFloat16( src[ 14 ] ); - dst[ 5 ] = decodeFloat16( src[ 15 ] ); - dst[ 6 ] = decodeFloat16( src[ 27 ] ); - dst[ 7 ] = decodeFloat16( src[ 28 ] ); - dst[ 8 ] = decodeFloat16( src[ 2 ] ); - dst[ 9 ] = decodeFloat16( src[ 4 ] ); - - dst[ 10 ] = decodeFloat16( src[ 7 ] ); - dst[ 11 ] = decodeFloat16( src[ 13 ] ); - dst[ 12 ] = decodeFloat16( src[ 16 ] ); - dst[ 13 ] = decodeFloat16( src[ 26 ] ); - dst[ 14 ] = decodeFloat16( src[ 29 ] ); - dst[ 15 ] = decodeFloat16( src[ 42 ] ); - dst[ 16 ] = decodeFloat16( src[ 3 ] ); - dst[ 17 ] = decodeFloat16( src[ 8 ] ); - dst[ 18 ] = decodeFloat16( src[ 12 ] ); - dst[ 19 ] = decodeFloat16( src[ 17 ] ); - - dst[ 20 ] = decodeFloat16( src[ 25 ] ); - dst[ 21 ] = decodeFloat16( src[ 30 ] ); - dst[ 22 ] = decodeFloat16( src[ 41 ] ); - dst[ 23 ] = decodeFloat16( src[ 43 ] ); - dst[ 24 ] = decodeFloat16( src[ 9 ] ); - dst[ 25 ] = decodeFloat16( src[ 11 ] ); - dst[ 26 ] = decodeFloat16( src[ 18 ] ); - dst[ 27 ] = decodeFloat16( src[ 24 ] ); - dst[ 28 ] = decodeFloat16( src[ 31 ] ); - dst[ 29 ] = decodeFloat16( src[ 40 ] ); - - dst[ 30 ] = decodeFloat16( src[ 44 ] ); - dst[ 31 ] = decodeFloat16( src[ 53 ] ); - dst[ 32 ] = decodeFloat16( src[ 10 ] ); - dst[ 33 ] = decodeFloat16( src[ 19 ] ); - dst[ 34 ] = decodeFloat16( src[ 23 ] ); - dst[ 35 ] = decodeFloat16( src[ 32 ] ); - dst[ 36 ] = decodeFloat16( src[ 39 ] ); - dst[ 37 ] = decodeFloat16( src[ 45 ] ); - dst[ 38 ] = decodeFloat16( src[ 52 ] ); - dst[ 39 ] = decodeFloat16( src[ 54 ] ); - - dst[ 40 ] = decodeFloat16( src[ 20 ] ); - dst[ 41 ] = decodeFloat16( src[ 22 ] ); - dst[ 42 ] = decodeFloat16( src[ 33 ] ); - dst[ 43 ] = decodeFloat16( src[ 38 ] ); - dst[ 44 ] = decodeFloat16( src[ 46 ] ); - dst[ 45 ] = decodeFloat16( src[ 51 ] ); - dst[ 46 ] = decodeFloat16( src[ 55 ] ); - dst[ 47 ] = decodeFloat16( src[ 60 ] ); - dst[ 48 ] = decodeFloat16( src[ 21 ] ); - dst[ 49 ] = decodeFloat16( src[ 34 ] ); - - dst[ 50 ] = decodeFloat16( src[ 37 ] ); - dst[ 51 ] = decodeFloat16( src[ 47 ] ); - dst[ 52 ] = decodeFloat16( src[ 50 ] ); - dst[ 53 ] = decodeFloat16( src[ 56 ] ); - dst[ 54 ] = decodeFloat16( src[ 59 ] ); - dst[ 55 ] = decodeFloat16( src[ 61 ] ); - dst[ 56 ] = decodeFloat16( src[ 35 ] ); - dst[ 57 ] = decodeFloat16( src[ 36 ] ); - dst[ 58 ] = decodeFloat16( src[ 48 ] ); - dst[ 59 ] = decodeFloat16( src[ 49 ] ); - - dst[ 60 ] = decodeFloat16( src[ 57 ] ); - dst[ 61 ] = decodeFloat16( src[ 58 ] ); - dst[ 62 ] = decodeFloat16( src[ 62 ] ); - dst[ 63 ] = decodeFloat16( src[ 63 ] ); - - } - - function dctInverse( data ) { - - const a = 0.5 * Math.cos( 3.14159 / 4.0 ); - const b = 0.5 * Math.cos( 3.14159 / 16.0 ); - const c = 0.5 * Math.cos( 3.14159 / 8.0 ); - const d = 0.5 * Math.cos( 3.0 * 3.14159 / 16.0 ); - const e = 0.5 * Math.cos( 5.0 * 3.14159 / 16.0 ); - const f = 0.5 * Math.cos( 3.0 * 3.14159 / 8.0 ); - const g = 0.5 * Math.cos( 7.0 * 3.14159 / 16.0 ); - - const alpha = new Array( 4 ); - const beta = new Array( 4 ); - const theta = new Array( 4 ); - const gamma = new Array( 4 ); - - for ( let row = 0; row < 8; ++ row ) { - - const rowPtr = row * 8; - - alpha[ 0 ] = c * data[ rowPtr + 2 ]; - alpha[ 1 ] = f * data[ rowPtr + 2 ]; - alpha[ 2 ] = c * data[ rowPtr + 6 ]; - alpha[ 3 ] = f * data[ rowPtr + 6 ]; - - beta[ 0 ] = b * data[ rowPtr + 1 ] + d * data[ rowPtr + 3 ] + e * data[ rowPtr + 5 ] + g * data[ rowPtr + 7 ]; - beta[ 1 ] = d * data[ rowPtr + 1 ] - g * data[ rowPtr + 3 ] - b * data[ rowPtr + 5 ] - e * data[ rowPtr + 7 ]; - beta[ 2 ] = e * data[ rowPtr + 1 ] - b * data[ rowPtr + 3 ] + g * data[ rowPtr + 5 ] + d * data[ rowPtr + 7 ]; - beta[ 3 ] = g * data[ rowPtr + 1 ] - e * data[ rowPtr + 3 ] + d * data[ rowPtr + 5 ] - b * data[ rowPtr + 7 ]; - - theta[ 0 ] = a * ( data[ rowPtr + 0 ] + data[ rowPtr + 4 ] ); - theta[ 3 ] = a * ( data[ rowPtr + 0 ] - data[ rowPtr + 4 ] ); - theta[ 1 ] = alpha[ 0 ] + alpha[ 3 ]; - theta[ 2 ] = alpha[ 1 ] - alpha[ 2 ]; - - gamma[ 0 ] = theta[ 0 ] + theta[ 1 ]; - gamma[ 1 ] = theta[ 3 ] + theta[ 2 ]; - gamma[ 2 ] = theta[ 3 ] - theta[ 2 ]; - gamma[ 3 ] = theta[ 0 ] - theta[ 1 ]; - - data[ rowPtr + 0 ] = gamma[ 0 ] + beta[ 0 ]; - data[ rowPtr + 1 ] = gamma[ 1 ] + beta[ 1 ]; - data[ rowPtr + 2 ] = gamma[ 2 ] + beta[ 2 ]; - data[ rowPtr + 3 ] = gamma[ 3 ] + beta[ 3 ]; - - data[ rowPtr + 4 ] = gamma[ 3 ] - beta[ 3 ]; - data[ rowPtr + 5 ] = gamma[ 2 ] - beta[ 2 ]; - data[ rowPtr + 6 ] = gamma[ 1 ] - beta[ 1 ]; - data[ rowPtr + 7 ] = gamma[ 0 ] - beta[ 0 ]; - - } - - for ( let column = 0; column < 8; ++ column ) { - - alpha[ 0 ] = c * data[ 16 + column ]; - alpha[ 1 ] = f * data[ 16 + column ]; - alpha[ 2 ] = c * data[ 48 + column ]; - alpha[ 3 ] = f * data[ 48 + column ]; - - beta[ 0 ] = b * data[ 8 + column ] + d * data[ 24 + column ] + e * data[ 40 + column ] + g * data[ 56 + column ]; - beta[ 1 ] = d * data[ 8 + column ] - g * data[ 24 + column ] - b * data[ 40 + column ] - e * data[ 56 + column ]; - beta[ 2 ] = e * data[ 8 + column ] - b * data[ 24 + column ] + g * data[ 40 + column ] + d * data[ 56 + column ]; - beta[ 3 ] = g * data[ 8 + column ] - e * data[ 24 + column ] + d * data[ 40 + column ] - b * data[ 56 + column ]; - - theta[ 0 ] = a * ( data[ column ] + data[ 32 + column ] ); - theta[ 3 ] = a * ( data[ column ] - data[ 32 + column ] ); - - theta[ 1 ] = alpha[ 0 ] + alpha[ 3 ]; - theta[ 2 ] = alpha[ 1 ] - alpha[ 2 ]; - - gamma[ 0 ] = theta[ 0 ] + theta[ 1 ]; - gamma[ 1 ] = theta[ 3 ] + theta[ 2 ]; - gamma[ 2 ] = theta[ 3 ] - theta[ 2 ]; - gamma[ 3 ] = theta[ 0 ] - theta[ 1 ]; - - data[ 0 + column ] = gamma[ 0 ] + beta[ 0 ]; - data[ 8 + column ] = gamma[ 1 ] + beta[ 1 ]; - data[ 16 + column ] = gamma[ 2 ] + beta[ 2 ]; - data[ 24 + column ] = gamma[ 3 ] + beta[ 3 ]; - - data[ 32 + column ] = gamma[ 3 ] - beta[ 3 ]; - data[ 40 + column ] = gamma[ 2 ] - beta[ 2 ]; - data[ 48 + column ] = gamma[ 1 ] - beta[ 1 ]; - data[ 56 + column ] = gamma[ 0 ] - beta[ 0 ]; - - } - - } - - function csc709Inverse( data ) { - - for ( let i = 0; i < 64; ++ i ) { - - const y = data[ 0 ][ i ]; - const cb = data[ 1 ][ i ]; - const cr = data[ 2 ][ i ]; - - data[ 0 ][ i ] = y + 1.5747 * cr; - data[ 1 ][ i ] = y - 0.1873 * cb - 0.4682 * cr; - data[ 2 ][ i ] = y + 1.8556 * cb; - - } - - } - - function convertToHalf( src, dst, idx ) { - - for ( let i = 0; i < 64; ++ i ) { - - dst[ idx + i ] = DataUtils.toHalfFloat( toLinear( src[ i ] ) ); - - } - - } - - function toLinear( float ) { - - if ( float <= 1 ) { - - return Math.sign( float ) * Math.pow( Math.abs( float ), 2.2 ); - - } else { - - return Math.sign( float ) * Math.pow( logBase, Math.abs( float ) - 1.0 ); - - } - - } - - function uncompressRAW( info ) { - - return new DataView( info.array.buffer, info.offset.value, info.size ); - - } - - function uncompressRLE( info ) { - - const compressed = info.viewer.buffer.slice( info.offset.value, info.offset.value + info.size ); - - const rawBuffer = new Uint8Array( decodeRunLength( compressed ) ); - const tmpBuffer = new Uint8Array( rawBuffer.length ); - - predictor( rawBuffer ); // revert predictor - - interleaveScalar( rawBuffer, tmpBuffer ); // interleave pixels - - return new DataView( tmpBuffer.buffer ); - - } - - function uncompressZIP( info ) { - - const compressed = info.array.slice( info.offset.value, info.offset.value + info.size ); - - const rawBuffer = fflate.unzlibSync( compressed ); - const tmpBuffer = new Uint8Array( rawBuffer.length ); - - predictor( rawBuffer ); // revert predictor - - interleaveScalar( rawBuffer, tmpBuffer ); // interleave pixels - - return new DataView( tmpBuffer.buffer ); - - } - - function uncompressPIZ( info ) { - - const inDataView = info.viewer; - const inOffset = { value: info.offset.value }; - - const outBuffer = new Uint16Array( info.width * info.scanlineBlockSize * ( info.channels * info.type ) ); - const bitmap = new Uint8Array( BITMAP_SIZE ); - - // Setup channel info - let outBufferEnd = 0; - const pizChannelData = new Array( info.channels ); - for ( let i = 0; i < info.channels; i ++ ) { - - pizChannelData[ i ] = {}; - pizChannelData[ i ][ 'start' ] = outBufferEnd; - pizChannelData[ i ][ 'end' ] = pizChannelData[ i ][ 'start' ]; - pizChannelData[ i ][ 'nx' ] = info.width; - pizChannelData[ i ][ 'ny' ] = info.lines; - pizChannelData[ i ][ 'size' ] = info.type; - - outBufferEnd += pizChannelData[ i ].nx * pizChannelData[ i ].ny * pizChannelData[ i ].size; - - } - - // Read range compression data - - const minNonZero = parseUint16( inDataView, inOffset ); - const maxNonZero = parseUint16( inDataView, inOffset ); - - if ( maxNonZero >= BITMAP_SIZE ) { - - throw new Error( 'Something is wrong with PIZ_COMPRESSION BITMAP_SIZE' ); - - } - - if ( minNonZero <= maxNonZero ) { - - for ( let i = 0; i < maxNonZero - minNonZero + 1; i ++ ) { - - bitmap[ i + minNonZero ] = parseUint8( inDataView, inOffset ); - - } - - } - - // Reverse LUT - const lut = new Uint16Array( USHORT_RANGE ); - const maxValue = reverseLutFromBitmap( bitmap, lut ); - - const length = parseUint32( inDataView, inOffset ); - - // Huffman decoding - hufUncompress( info.array, inDataView, inOffset, length, outBuffer, outBufferEnd ); - - // Wavelet decoding - for ( let i = 0; i < info.channels; ++ i ) { - - const cd = pizChannelData[ i ]; - - for ( let j = 0; j < pizChannelData[ i ].size; ++ j ) { - - wav2Decode( - outBuffer, - cd.start + j, - cd.nx, - cd.size, - cd.ny, - cd.nx * cd.size, - maxValue - ); - - } - - } - - // Expand the pixel data to their original range - applyLut( lut, outBuffer, outBufferEnd ); - - // Rearrange the pixel data into the format expected by the caller. - let tmpOffset = 0; - const tmpBuffer = new Uint8Array( outBuffer.buffer.byteLength ); - for ( let y = 0; y < info.lines; y ++ ) { - - for ( let c = 0; c < info.channels; c ++ ) { - - const cd = pizChannelData[ c ]; - - const n = cd.nx * cd.size; - const cp = new Uint8Array( outBuffer.buffer, cd.end * INT16_SIZE, n * INT16_SIZE ); - - tmpBuffer.set( cp, tmpOffset ); - tmpOffset += n * INT16_SIZE; - cd.end += n; - - } - - } - - return new DataView( tmpBuffer.buffer ); - - } - - function uncompressPXR( info ) { - - const compressed = info.array.slice( info.offset.value, info.offset.value + info.size ); - - const rawBuffer = fflate.unzlibSync( compressed ); - - const sz = info.lines * info.channels * info.width; - const tmpBuffer = ( info.type == 1 ) ? new Uint16Array( sz ) : new Uint32Array( sz ); - - let tmpBufferEnd = 0; - let writePtr = 0; - const ptr = new Array( 4 ); - - for ( let y = 0; y < info.lines; y ++ ) { - - for ( let c = 0; c < info.channels; c ++ ) { - - let pixel = 0; - - switch ( info.type ) { - - case 1: - - ptr[ 0 ] = tmpBufferEnd; - ptr[ 1 ] = ptr[ 0 ] + info.width; - tmpBufferEnd = ptr[ 1 ] + info.width; - - for ( let j = 0; j < info.width; ++ j ) { - - const diff = ( rawBuffer[ ptr[ 0 ] ++ ] << 8 ) | rawBuffer[ ptr[ 1 ] ++ ]; - - pixel += diff; - - tmpBuffer[ writePtr ] = pixel; - writePtr ++; - - } - - break; - - case 2: - - ptr[ 0 ] = tmpBufferEnd; - ptr[ 1 ] = ptr[ 0 ] + info.width; - ptr[ 2 ] = ptr[ 1 ] + info.width; - tmpBufferEnd = ptr[ 2 ] + info.width; - - for ( let j = 0; j < info.width; ++ j ) { - - const diff = ( rawBuffer[ ptr[ 0 ] ++ ] << 24 ) | ( rawBuffer[ ptr[ 1 ] ++ ] << 16 ) | ( rawBuffer[ ptr[ 2 ] ++ ] << 8 ); - - pixel += diff; - - tmpBuffer[ writePtr ] = pixel; - writePtr ++; - - } - - break; - - } - - } - - } - - return new DataView( tmpBuffer.buffer ); - - } - - function uncompressDWA( info ) { - - const inDataView = info.viewer; - const inOffset = { value: info.offset.value }; - const outBuffer = new Uint8Array( info.width * info.lines * ( info.channels * info.type * INT16_SIZE ) ); - - // Read compression header information - const dwaHeader = { - - version: parseInt64( inDataView, inOffset ), - unknownUncompressedSize: parseInt64( inDataView, inOffset ), - unknownCompressedSize: parseInt64( inDataView, inOffset ), - acCompressedSize: parseInt64( inDataView, inOffset ), - dcCompressedSize: parseInt64( inDataView, inOffset ), - rleCompressedSize: parseInt64( inDataView, inOffset ), - rleUncompressedSize: parseInt64( inDataView, inOffset ), - rleRawSize: parseInt64( inDataView, inOffset ), - totalAcUncompressedCount: parseInt64( inDataView, inOffset ), - totalDcUncompressedCount: parseInt64( inDataView, inOffset ), - acCompression: parseInt64( inDataView, inOffset ) - - }; - - if ( dwaHeader.version < 2 ) - throw new Error( 'EXRLoader.parse: ' + EXRHeader.compression + ' version ' + dwaHeader.version + ' is unsupported' ); - - // Read channel ruleset information - const channelRules = new Array(); - let ruleSize = parseUint16( inDataView, inOffset ) - INT16_SIZE; - - while ( ruleSize > 0 ) { - - const name = parseNullTerminatedString( inDataView.buffer, inOffset ); - const value = parseUint8( inDataView, inOffset ); - const compression = ( value >> 2 ) & 3; - const csc = ( value >> 4 ) - 1; - const index = new Int8Array( [ csc ] )[ 0 ]; - const type = parseUint8( inDataView, inOffset ); - - channelRules.push( { - name: name, - index: index, - type: type, - compression: compression, - } ); - - ruleSize -= name.length + 3; - - } - - // Classify channels - const channels = EXRHeader.channels; - const channelData = new Array( info.channels ); - - for ( let i = 0; i < info.channels; ++ i ) { - - const cd = channelData[ i ] = {}; - const channel = channels[ i ]; - - cd.name = channel.name; - cd.compression = UNKNOWN; - cd.decoded = false; - cd.type = channel.pixelType; - cd.pLinear = channel.pLinear; - cd.width = info.width; - cd.height = info.lines; - - } - - const cscSet = { - idx: new Array( 3 ) - }; - - for ( let offset = 0; offset < info.channels; ++ offset ) { - - const cd = channelData[ offset ]; - - for ( let i = 0; i < channelRules.length; ++ i ) { - - const rule = channelRules[ i ]; - - if ( cd.name == rule.name ) { - - cd.compression = rule.compression; - - if ( rule.index >= 0 ) { - - cscSet.idx[ rule.index ] = offset; - - } - - cd.offset = offset; - - } - - } - - } - - let acBuffer, dcBuffer, rleBuffer; - - // Read DCT - AC component data - if ( dwaHeader.acCompressedSize > 0 ) { - - switch ( dwaHeader.acCompression ) { - - case STATIC_HUFFMAN: - - acBuffer = new Uint16Array( dwaHeader.totalAcUncompressedCount ); - hufUncompress( info.array, inDataView, inOffset, dwaHeader.acCompressedSize, acBuffer, dwaHeader.totalAcUncompressedCount ); - break; - - case DEFLATE: - - const compressed = info.array.slice( inOffset.value, inOffset.value + dwaHeader.totalAcUncompressedCount ); - const data = fflate.unzlibSync( compressed ); - acBuffer = new Uint16Array( data.buffer ); - inOffset.value += dwaHeader.totalAcUncompressedCount; - break; - - } - - - } - - // Read DCT - DC component data - if ( dwaHeader.dcCompressedSize > 0 ) { - - const zlibInfo = { - array: info.array, - offset: inOffset, - size: dwaHeader.dcCompressedSize - }; - dcBuffer = new Uint16Array( uncompressZIP( zlibInfo ).buffer ); - inOffset.value += dwaHeader.dcCompressedSize; - - } - - // Read RLE compressed data - if ( dwaHeader.rleRawSize > 0 ) { - - const compressed = info.array.slice( inOffset.value, inOffset.value + dwaHeader.rleCompressedSize ); - const data = fflate.unzlibSync( compressed ); - rleBuffer = decodeRunLength( data.buffer ); - - inOffset.value += dwaHeader.rleCompressedSize; - - } - - // Prepare outbuffer data offset - let outBufferEnd = 0; - const rowOffsets = new Array( channelData.length ); - for ( let i = 0; i < rowOffsets.length; ++ i ) { - - rowOffsets[ i ] = new Array(); - - } - - for ( let y = 0; y < info.lines; ++ y ) { - - for ( let chan = 0; chan < channelData.length; ++ chan ) { - - rowOffsets[ chan ].push( outBufferEnd ); - outBufferEnd += channelData[ chan ].width * info.type * INT16_SIZE; - - } - - } - - // Lossy DCT decode RGB channels - lossyDctDecode( cscSet, rowOffsets, channelData, acBuffer, dcBuffer, outBuffer ); - - // Decode other channels - for ( let i = 0; i < channelData.length; ++ i ) { - - const cd = channelData[ i ]; - - if ( cd.decoded ) continue; - - switch ( cd.compression ) { - - case RLE: - - let row = 0; - let rleOffset = 0; - - for ( let y = 0; y < info.lines; ++ y ) { - - let rowOffsetBytes = rowOffsets[ i ][ row ]; - - for ( let x = 0; x < cd.width; ++ x ) { - - for ( let byte = 0; byte < INT16_SIZE * cd.type; ++ byte ) { - - outBuffer[ rowOffsetBytes ++ ] = rleBuffer[ rleOffset + byte * cd.width * cd.height ]; - - } - - rleOffset ++; - - } - - row ++; - - } - - break; - - case LOSSY_DCT: // skip - - default: - throw new Error( 'EXRLoader.parse: unsupported channel compression' ); - - } - - } - - return new DataView( outBuffer.buffer ); - - } - - function parseNullTerminatedString( buffer, offset ) { - - const uintBuffer = new Uint8Array( buffer ); - let endOffset = 0; - - while ( uintBuffer[ offset.value + endOffset ] != 0 ) { - - endOffset += 1; - - } - - const stringValue = new TextDecoder().decode( - uintBuffer.slice( offset.value, offset.value + endOffset ) - ); - - offset.value = offset.value + endOffset + 1; - - return stringValue; - - } - - function parseFixedLengthString( buffer, offset, size ) { - - const stringValue = new TextDecoder().decode( - new Uint8Array( buffer ).slice( offset.value, offset.value + size ) - ); - - offset.value = offset.value + size; - - return stringValue; - - } - - function parseRational( dataView, offset ) { - - const x = parseInt32( dataView, offset ); - const y = parseUint32( dataView, offset ); - - return [ x, y ]; - - } - - function parseTimecode( dataView, offset ) { - - const x = parseUint32( dataView, offset ); - const y = parseUint32( dataView, offset ); - - return [ x, y ]; - - } - - function parseInt32( dataView, offset ) { - - const Int32 = dataView.getInt32( offset.value, true ); - - offset.value = offset.value + INT32_SIZE; - - return Int32; - - } - - function parseUint32( dataView, offset ) { - - const Uint32 = dataView.getUint32( offset.value, true ); - - offset.value = offset.value + INT32_SIZE; - - return Uint32; - - } - - function parseUint8Array( uInt8Array, offset ) { - - const Uint8 = uInt8Array[ offset.value ]; - - offset.value = offset.value + INT8_SIZE; - - return Uint8; - - } - - function parseUint8( dataView, offset ) { - - const Uint8 = dataView.getUint8( offset.value ); - - offset.value = offset.value + INT8_SIZE; - - return Uint8; - - } - - const parseInt64 = function ( dataView, offset ) { - - let int; - - if ( 'getBigInt64' in DataView.prototype ) { - - int = Number( dataView.getBigInt64( offset.value, true ) ); - - } else { - - int = dataView.getUint32( offset.value + 4, true ) + Number( dataView.getUint32( offset.value, true ) << 32 ); - - } - - offset.value += ULONG_SIZE; - - return int; - - }; - - function parseFloat32( dataView, offset ) { - - const float = dataView.getFloat32( offset.value, true ); - - offset.value += FLOAT32_SIZE; - - return float; - - } - - function decodeFloat32( dataView, offset ) { - - return DataUtils.toHalfFloat( parseFloat32( dataView, offset ) ); - - } - - // https://stackoverflow.com/questions/5678432/decompressing-half-precision-floats-in-javascript - function decodeFloat16( binary ) { - - const exponent = ( binary & 0x7C00 ) >> 10, - fraction = binary & 0x03FF; - - return ( binary >> 15 ? - 1 : 1 ) * ( - exponent ? - ( - exponent === 0x1F ? - fraction ? NaN : Infinity : - Math.pow( 2, exponent - 15 ) * ( 1 + fraction / 0x400 ) - ) : - 6.103515625e-5 * ( fraction / 0x400 ) - ); - - } - - function parseUint16( dataView, offset ) { - - const Uint16 = dataView.getUint16( offset.value, true ); - - offset.value += INT16_SIZE; - - return Uint16; - - } - - function parseFloat16( buffer, offset ) { - - return decodeFloat16( parseUint16( buffer, offset ) ); - - } - - function parseChlist( dataView, buffer, offset, size ) { - - const startOffset = offset.value; - const channels = []; - - while ( offset.value < ( startOffset + size - 1 ) ) { - - const name = parseNullTerminatedString( buffer, offset ); - const pixelType = parseInt32( dataView, offset ); - const pLinear = parseUint8( dataView, offset ); - offset.value += 3; // reserved, three chars - const xSampling = parseInt32( dataView, offset ); - const ySampling = parseInt32( dataView, offset ); - - channels.push( { - name: name, - pixelType: pixelType, - pLinear: pLinear, - xSampling: xSampling, - ySampling: ySampling - } ); - - } - - offset.value += 1; - - return channels; - - } - - function parseChromaticities( dataView, offset ) { - - const redX = parseFloat32( dataView, offset ); - const redY = parseFloat32( dataView, offset ); - const greenX = parseFloat32( dataView, offset ); - const greenY = parseFloat32( dataView, offset ); - const blueX = parseFloat32( dataView, offset ); - const blueY = parseFloat32( dataView, offset ); - const whiteX = parseFloat32( dataView, offset ); - const whiteY = parseFloat32( dataView, offset ); - - return { redX: redX, redY: redY, greenX: greenX, greenY: greenY, blueX: blueX, blueY: blueY, whiteX: whiteX, whiteY: whiteY }; - - } - - function parseCompression( dataView, offset ) { - - const compressionCodes = [ - 'NO_COMPRESSION', - 'RLE_COMPRESSION', - 'ZIPS_COMPRESSION', - 'ZIP_COMPRESSION', - 'PIZ_COMPRESSION', - 'PXR24_COMPRESSION', - 'B44_COMPRESSION', - 'B44A_COMPRESSION', - 'DWAA_COMPRESSION', - 'DWAB_COMPRESSION' - ]; - - const compression = parseUint8( dataView, offset ); - - return compressionCodes[ compression ]; - - } - - function parseBox2i( dataView, offset ) { - - const xMin = parseUint32( dataView, offset ); - const yMin = parseUint32( dataView, offset ); - const xMax = parseUint32( dataView, offset ); - const yMax = parseUint32( dataView, offset ); - - return { xMin: xMin, yMin: yMin, xMax: xMax, yMax: yMax }; - - } - - function parseLineOrder( dataView, offset ) { - - const lineOrders = [ - 'INCREASING_Y' - ]; - - const lineOrder = parseUint8( dataView, offset ); - - return lineOrders[ lineOrder ]; - - } - - function parseV2f( dataView, offset ) { - - const x = parseFloat32( dataView, offset ); - const y = parseFloat32( dataView, offset ); - - return [ x, y ]; - - } - - function parseV3f( dataView, offset ) { - - const x = parseFloat32( dataView, offset ); - const y = parseFloat32( dataView, offset ); - const z = parseFloat32( dataView, offset ); - - return [ x, y, z ]; - - } - - function parseValue( dataView, buffer, offset, type, size ) { - - if ( type === 'string' || type === 'stringvector' || type === 'iccProfile' ) { - - return parseFixedLengthString( buffer, offset, size ); - - } else if ( type === 'chlist' ) { - - return parseChlist( dataView, buffer, offset, size ); - - } else if ( type === 'chromaticities' ) { - - return parseChromaticities( dataView, offset ); - - } else if ( type === 'compression' ) { - - return parseCompression( dataView, offset ); - - } else if ( type === 'box2i' ) { - - return parseBox2i( dataView, offset ); - - } else if ( type === 'lineOrder' ) { - - return parseLineOrder( dataView, offset ); - - } else if ( type === 'float' ) { - - return parseFloat32( dataView, offset ); - - } else if ( type === 'v2f' ) { - - return parseV2f( dataView, offset ); - - } else if ( type === 'v3f' ) { - - return parseV3f( dataView, offset ); - - } else if ( type === 'int' ) { - - return parseInt32( dataView, offset ); - - } else if ( type === 'rational' ) { - - return parseRational( dataView, offset ); - - } else if ( type === 'timecode' ) { - - return parseTimecode( dataView, offset ); - - } else if ( type === 'preview' ) { - - offset.value += size; - return 'skipped'; - - } else { - - offset.value += size; - return undefined; - - } - - } - - function parseHeader( dataView, buffer, offset ) { - - const EXRHeader = {}; - - if ( dataView.getUint32( 0, true ) != 20000630 ) { // magic - - throw new Error( 'THREE.EXRLoader: Provided file doesn\'t appear to be in OpenEXR format.' ); - - } - - EXRHeader.version = dataView.getUint8( 4 ); - - const spec = dataView.getUint8( 5 ); // fullMask - - EXRHeader.spec = { - singleTile: !! ( spec & 2 ), - longName: !! ( spec & 4 ), - deepFormat: !! ( spec & 8 ), - multiPart: !! ( spec & 16 ), - }; - - // start of header - - offset.value = 8; // start at 8 - after pre-amble - - let keepReading = true; - - while ( keepReading ) { - - const attributeName = parseNullTerminatedString( buffer, offset ); - - if ( attributeName == 0 ) { - - keepReading = false; - - } else { - - const attributeType = parseNullTerminatedString( buffer, offset ); - const attributeSize = parseUint32( dataView, offset ); - const attributeValue = parseValue( dataView, buffer, offset, attributeType, attributeSize ); - - if ( attributeValue === undefined ) { - - console.warn( `THREE.EXRLoader: Skipped unknown header attribute type \'${attributeType}\'.` ); - - } else { - - EXRHeader[ attributeName ] = attributeValue; - - } - - } - - } - - if ( ( spec & ~ 0x04 ) != 0 ) { // unsupported tiled, deep-image, multi-part - - console.error( 'THREE.EXRHeader:', EXRHeader ); - throw new Error( 'THREE.EXRLoader: Provided file is currently unsupported.' ); - - } - - return EXRHeader; - - } - - function setupDecoder( EXRHeader, dataView, uInt8Array, offset, outputType ) { - - const EXRDecoder = { - size: 0, - viewer: dataView, - array: uInt8Array, - offset: offset, - width: EXRHeader.dataWindow.xMax - EXRHeader.dataWindow.xMin + 1, - height: EXRHeader.dataWindow.yMax - EXRHeader.dataWindow.yMin + 1, - channels: EXRHeader.channels.length, - bytesPerLine: null, - lines: null, - inputSize: null, - type: EXRHeader.channels[ 0 ].pixelType, - uncompress: null, - getter: null, - format: null, - colorSpace: LinearSRGBColorSpace, - }; - - switch ( EXRHeader.compression ) { - - case 'NO_COMPRESSION': - EXRDecoder.lines = 1; - EXRDecoder.uncompress = uncompressRAW; - break; - - case 'RLE_COMPRESSION': - EXRDecoder.lines = 1; - EXRDecoder.uncompress = uncompressRLE; - break; - - case 'ZIPS_COMPRESSION': - EXRDecoder.lines = 1; - EXRDecoder.uncompress = uncompressZIP; - break; - - case 'ZIP_COMPRESSION': - EXRDecoder.lines = 16; - EXRDecoder.uncompress = uncompressZIP; - break; - - case 'PIZ_COMPRESSION': - EXRDecoder.lines = 32; - EXRDecoder.uncompress = uncompressPIZ; - break; - - case 'PXR24_COMPRESSION': - EXRDecoder.lines = 16; - EXRDecoder.uncompress = uncompressPXR; - break; - - case 'DWAA_COMPRESSION': - EXRDecoder.lines = 32; - EXRDecoder.uncompress = uncompressDWA; - break; - - case 'DWAB_COMPRESSION': - EXRDecoder.lines = 256; - EXRDecoder.uncompress = uncompressDWA; - break; - - default: - throw new Error( 'EXRLoader.parse: ' + EXRHeader.compression + ' is unsupported' ); - - } - - EXRDecoder.scanlineBlockSize = EXRDecoder.lines; - - if ( EXRDecoder.type == 1 ) { - - // half - switch ( outputType ) { - - case FloatType: - EXRDecoder.getter = parseFloat16; - EXRDecoder.inputSize = INT16_SIZE; - break; - - case HalfFloatType: - EXRDecoder.getter = parseUint16; - EXRDecoder.inputSize = INT16_SIZE; - break; - - } - - } else if ( EXRDecoder.type == 2 ) { - - // float - switch ( outputType ) { - - case FloatType: - EXRDecoder.getter = parseFloat32; - EXRDecoder.inputSize = FLOAT32_SIZE; - break; - - case HalfFloatType: - EXRDecoder.getter = decodeFloat32; - EXRDecoder.inputSize = FLOAT32_SIZE; - - } - - } else { - - throw new Error( 'EXRLoader.parse: unsupported pixelType ' + EXRDecoder.type + ' for ' + EXRHeader.compression + '.' ); - - } - - EXRDecoder.blockCount = ( EXRHeader.dataWindow.yMax + 1 ) / EXRDecoder.scanlineBlockSize; - - for ( let i = 0; i < EXRDecoder.blockCount; i ++ ) - parseInt64( dataView, offset ); // scanlineOffset - - // we should be passed the scanline offset table, ready to start reading pixel data. - - // RGB images will be converted to RGBA format, preventing software emulation in select devices. - EXRDecoder.outputChannels = ( ( EXRDecoder.channels == 3 ) ? 4 : EXRDecoder.channels ); - const size = EXRDecoder.width * EXRDecoder.height * EXRDecoder.outputChannels; - - switch ( outputType ) { - - case FloatType: - EXRDecoder.byteArray = new Float32Array( size ); - - // Fill initially with 1s for the alpha value if the texture is not RGBA, RGB values will be overwritten - if ( EXRDecoder.channels < EXRDecoder.outputChannels ) - EXRDecoder.byteArray.fill( 1, 0, size ); - - break; - - case HalfFloatType: - EXRDecoder.byteArray = new Uint16Array( size ); - - if ( EXRDecoder.channels < EXRDecoder.outputChannels ) - EXRDecoder.byteArray.fill( 0x3C00, 0, size ); // Uint16Array holds half float data, 0x3C00 is 1 - - break; - - default: - console.error( 'THREE.EXRLoader: unsupported type: ', outputType ); - break; - - } - - EXRDecoder.bytesPerLine = EXRDecoder.width * EXRDecoder.inputSize * EXRDecoder.channels; - - if ( EXRDecoder.outputChannels == 4 ) { - - EXRDecoder.format = RGBAFormat; - EXRDecoder.colorSpace = LinearSRGBColorSpace; - - } else { - - EXRDecoder.format = RedFormat; - EXRDecoder.colorSpace = NoColorSpace; - - } - - return EXRDecoder; - - } - - // start parsing file [START] - - const bufferDataView = new DataView( buffer ); - const uInt8Array = new Uint8Array( buffer ); - const offset = { value: 0 }; - - // get header information and validate format. - const EXRHeader = parseHeader( bufferDataView, buffer, offset ); - - // get input compression information and prepare decoding. - const EXRDecoder = setupDecoder( EXRHeader, bufferDataView, uInt8Array, offset, this.type ); - - const tmpOffset = { value: 0 }; - const channelOffsets = { R: 0, G: 1, B: 2, A: 3, Y: 0 }; - - for ( let scanlineBlockIdx = 0; scanlineBlockIdx < EXRDecoder.height / EXRDecoder.scanlineBlockSize; scanlineBlockIdx ++ ) { - - const line = parseUint32( bufferDataView, offset ); // line_no - EXRDecoder.size = parseUint32( bufferDataView, offset ); // data_len - EXRDecoder.lines = ( ( line + EXRDecoder.scanlineBlockSize > EXRDecoder.height ) ? ( EXRDecoder.height - line ) : EXRDecoder.scanlineBlockSize ); - - const isCompressed = EXRDecoder.size < EXRDecoder.lines * EXRDecoder.bytesPerLine; - const viewer = isCompressed ? EXRDecoder.uncompress( EXRDecoder ) : uncompressRAW( EXRDecoder ); - - offset.value += EXRDecoder.size; - - for ( let line_y = 0; line_y < EXRDecoder.scanlineBlockSize; line_y ++ ) { - - const true_y = line_y + scanlineBlockIdx * EXRDecoder.scanlineBlockSize; - if ( true_y >= EXRDecoder.height ) break; - - for ( let channelID = 0; channelID < EXRDecoder.channels; channelID ++ ) { - - const cOff = channelOffsets[ EXRHeader.channels[ channelID ].name ]; - - for ( let x = 0; x < EXRDecoder.width; x ++ ) { - - tmpOffset.value = ( line_y * ( EXRDecoder.channels * EXRDecoder.width ) + channelID * EXRDecoder.width + x ) * EXRDecoder.inputSize; - const outIndex = ( EXRDecoder.height - 1 - true_y ) * ( EXRDecoder.width * EXRDecoder.outputChannels ) + x * EXRDecoder.outputChannels + cOff; - EXRDecoder.byteArray[ outIndex ] = EXRDecoder.getter( viewer, tmpOffset ); - - } - - } - - } - - } - - return { - header: EXRHeader, - width: EXRDecoder.width, - height: EXRDecoder.height, - data: EXRDecoder.byteArray, - format: EXRDecoder.format, - colorSpace: EXRDecoder.colorSpace, - type: this.type, - }; - - } - - setDataType( value ) { - - this.type = value; - return this; - - } - - load( url, onLoad, onProgress, onError ) { - - function onLoadCallback( texture, texData ) { - - texture.colorSpace = texData.colorSpace; - texture.minFilter = LinearFilter; - texture.magFilter = LinearFilter; - texture.generateMipmaps = false; - texture.flipY = false; - - if ( onLoad ) onLoad( texture, texData ); - - } - - return super.load( url, onLoadCallback, onProgress, onError ); - - } - -} - -export { EXRLoader }; diff --git a/public/assets/lib/vendor/three/README.md b/public/assets/lib/vendor/three/README.md deleted file mode 100644 index 30398dda..00000000 --- a/public/assets/lib/vendor/three/README.md +++ /dev/null @@ -1,9 +0,0 @@ -reference: -- https://threejs.org/docs/index.html#examples/en/loaders/MTLLoader - -example: -- https://unpkg.com/three@0.160.0/build/three.module.js -- https://unpkg.com/three@0.160.0/examples/jsm/controls/OrbitControls.js -- https://unpkg.com/three@0.160.0/examples/jsm/loaders/GLTFLoader.js - -*note*: update the file to get the right import location diff --git a/public/assets/lib/vendor/three/rhino3dm/rhino3dm.d.ts b/public/assets/lib/vendor/three/rhino3dm/rhino3dm.d.ts deleted file mode 100644 index 579ee880..00000000 --- a/public/assets/lib/vendor/three/rhino3dm/rhino3dm.d.ts +++ /dev/null @@ -1,6961 +0,0 @@ -declare module 'rhino3dm' { - - export default function rhino3dm() : Promise; - - enum ActiveSpace { - None, - ModelSpace, - PageSpace - } - - enum BasepointZero { - GroundLevel, - MeanSeaLevel, - CenterOfEarth - } - - enum ComponentIndexType { - InvalidType, - BrepVertex, - BrepEdge, - BrepFace, - BrepTrim, - BrepLoop, - MeshVertex, - MeshTopologyVertex, - MeshTopologyEdge, - MeshFace, - MeshNgon, - InstanceDefinitionPart, - PolycurveSegment, - PointCloudPoint, - GroupMember, - ExtrusionBottomProfile, - ExtrusionTopProfile, - ExtrusionWallEdge, - ExtrusionWallSurface, - ExtrusionCapSurface, - ExtrusionPath, - SubdVertex, - SubdEdge, - SubdFace, - DimLinearPoint, - DimRadialPoint, - DimAngularPoint, - DimOrdinatePoint, - DimTextPoint, - NoType - } - - enum CoordinateSystem { - World, - Camera, - Clip, - Screen - } - - enum CurvePipingCapTypes { - None, - Flat, - Box, - Dome - } - - enum DecalMappings { - None, - Planar, - Cylindrical, - Spherical, - UV - } - - enum DecalProjections { - None, - Forward, - Backward, - Both - } - - enum DisplacementSweepResolutionFormulas { - Default, - AbsoluteToleranceDependent - } - - enum DitheringMethods { - SimpleNoise, - FloydSteinberg - } - - enum EnvironmentBackgroundProjections { - Planar, - Spherical, - Emap, - Box, - Automatic, - LightProbe, - CubeMap, - VerticalCrossCubeMap, - HorizontalCrossCubeMap, - Hemispherical - } - - enum InstanceDefinitionUpdateType { - Static, - Embedded, - LinkedAndEmbedded, - Linked - } - - enum LightStyle { - None, - CameraDirectional, - CameraPoint, - CameraSpot, - WorldDirectional, - WorldPoint, - WorldSpot, - Ambient, - WorldLinear, - WorldRectangular - } - - enum LineCircleIntersection { - None, - Single, - Multiple - } - - enum LineCylinderIntersection { - None, - Single, - Multiple, - Overlap - } - - enum LineSphereIntersection { - None, - Single, - Multiple - } - - enum Mappings { - None, - Planar, - Cylindrical, - Spherical, - UV - } - - enum MeshType { - Default, - Render, - Analysis, - Preview, - Any - } - - enum ObjectColorSource { - ColorFromLayer, - ColorFromObject, - ColorFromMaterial, - ColorFromParent - } - - enum ObjectDecoration { - None, - StartArrowhead, - EndArrowhead, - BothArrowhead - } - - enum ObjectLinetypeSource { - LinetypeFromLayer, - LinetypeFromObject, - LinetypeFromParent - } - - enum ObjectMaterialSource { - MaterialFromLayer, - MaterialFromObject, - MaterialFromParent - } - - enum ObjectMode { - Normal, - Hidden, - Locked, - InstanceDefinitionObject - } - - enum ObjectPlotColorSource { - PlotColorFromLayer, - PlotColorFromObject, - PlotColorFromDisplay, - PlotColorFromParent - } - - enum ObjectPlotWeightSource { - PlotWeightFromLayer, - PlotWeightFromObject, - PlotWeightFromParent - } - - enum ObjectType { - None, - Point, - PointSet, - Curve, - Surface, - Brep, - Mesh, - Light, - Annotation, - InstanceDefinition, - InstanceReference, - TextDot, - Grip, - Detail, - Hatch, - MorphControl, - SubD, - BrepLoop, - PolysrfFilter, - EdgeFilter, - PolyedgeFilter, - MeshVertex, - MeshEdge, - MeshFace, - Cage, - Phantom, - ClipPlane, - Extrusion, - AnyObject - } - - enum PlaneSphereIntersection { - None, - Point, - Circle - } - - enum PostEffectTypes { - Early, - ToneMapping, - Late - } - - enum Projections { - None, - Forward, - Backward, - Both - } - - enum RenderChannelsModes { - Automatic, - Custom - } - - enum SphereSphereIntersection { - None, - Point, - Circle, - Overlap - } - - enum TextureType { - None, - Bitmap, - Diffuse, - Bump, - Transparency, - Opacity, - Emap, - PBR_BaseColor, - PBR_Subsurface, - PBR_SubsurfaceScattering, - PBR_SubsurfaceScatteringRadius, - PBR_Metallic, - PBR_Specular, - PBR_SpecularTint, - PBR_Roughness, - PBR_Anisotropic, - PBR_Anisotropic_Rotation, - PBR_Sheen, - PBR_SheenTint, - PBR_Clearcoat, - PBR_ClearcoatRoughness, - PBR_OpacityIor, - PBR_OpacityRoughness, - PBR_Emission, - PBR_AmbientOcclusion, - PBR_Displacement, - PBR_ClearcoatBump - } - - enum TextureUvwWrapping { - Repeat, - Clamp - } - - enum TransformRigidType { - RigidReversing, - NotRigid, - Rigid - } - - enum TransformSimilarityType { - OrientationReversing, - NotSimilarity, - OrientationPreserving - } - - enum UnitSystem { - None, - Angstroms, - Nanometers, - Microns, - Millimeters, - Centimeters, - Decimeters, - Meters, - Dekameters, - Hectometers, - Kilometers, - Megameters, - Gigameters, - Microinches, - Mils, - Inches, - Feet, - Yards, - Miles, - PrinterPoints, - PrinterPicas, - NauticalMiles, - AstronomicalUnits, - LightYears, - Parsecs, - CustomUnits, - Unset - } - - class RhinoModule { - ActiveSpace: typeof ActiveSpace - BasepointZero: typeof BasepointZero - ComponentIndexType: typeof ComponentIndexType - CoordinateSystem: typeof CoordinateSystem - CurvePipingCapTypes: typeof CurvePipingCapTypes - DecalMappings: typeof DecalMappings - DecalProjections: typeof DecalProjections - DisplacementSweepResolutionFormulas: typeof DisplacementSweepResolutionFormulas - DitheringMethods: typeof DitheringMethods - EnvironmentBackgroundProjections: typeof EnvironmentBackgroundProjections - InstanceDefinitionUpdateType: typeof InstanceDefinitionUpdateType - LightStyle: typeof LightStyle - LineCircleIntersection: typeof LineCircleIntersection - LineCylinderIntersection: typeof LineCylinderIntersection - LineSphereIntersection: typeof LineSphereIntersection - Mappings: typeof Mappings - MeshType: typeof MeshType - ObjectColorSource: typeof ObjectColorSource - ObjectDecoration: typeof ObjectDecoration - ObjectLinetypeSource: typeof ObjectLinetypeSource - ObjectMaterialSource: typeof ObjectMaterialSource - ObjectMode: typeof ObjectMode - ObjectPlotColorSource: typeof ObjectPlotColorSource - ObjectPlotWeightSource: typeof ObjectPlotWeightSource - ObjectType: typeof ObjectType - PlaneSphereIntersection: typeof PlaneSphereIntersection - PostEffectTypes: typeof PostEffectTypes - Projections: typeof Projections - RenderChannelsModes: typeof RenderChannelsModes - SphereSphereIntersection: typeof SphereSphereIntersection - TextureType: typeof TextureType - TextureUvwWrapping: typeof TextureUvwWrapping - TransformRigidType: typeof TransformRigidType - TransformSimilarityType: typeof TransformSimilarityType - UnitSystem: typeof UnitSystem - AnnotationBase: typeof AnnotationBase; - Arc: typeof Arc; - ArcCurve: typeof ArcCurve; - ArchivableDictionary: typeof ArchivableDictionary; - BezierCurve: typeof BezierCurve; - Bitmap: typeof Bitmap; - BoundingBox: typeof BoundingBox; - Box: typeof Box; - Brep: typeof Brep; - BrepEdge: typeof BrepEdge; - BrepEdgeList: typeof BrepEdgeList; - BrepFace: typeof BrepFace; - BrepFaceList: typeof BrepFaceList; - BrepSurfaceList: typeof BrepSurfaceList; - BrepVertex: typeof BrepVertex; - BrepVertexList: typeof BrepVertexList; - Circle: typeof Circle; - CommonObject: typeof CommonObject; - ComponentIndex: typeof ComponentIndex; - Cone: typeof Cone; - ConstructionPlane: typeof ConstructionPlane; - Curve: typeof Curve; - CurvePiping: typeof CurvePiping; - CurveProxy: typeof CurveProxy; - Cylinder: typeof Cylinder; - Decal: typeof Decal; - DimensionStyle: typeof DimensionStyle; - Displacement: typeof Displacement; - Dithering: typeof Dithering; - DracoCompression: typeof DracoCompression; - DracoCompressionOptions: typeof DracoCompressionOptions; - EarthAnchorPoint: typeof EarthAnchorPoint; - EdgeSoftening: typeof EdgeSoftening; - Ellipse: typeof Ellipse; - EmbeddedFile: typeof EmbeddedFile; - Environment: typeof Environment; - Extrusion: typeof Extrusion; - File3dm: typeof File3dm; - File3dmBitmapTable: typeof File3dmBitmapTable; - File3dmDecalTable: typeof File3dmDecalTable; - File3dmDimStyleTable: typeof File3dmDimStyleTable; - File3dmEmbeddedFileTable: typeof File3dmEmbeddedFileTable; - File3dmGroupTable: typeof File3dmGroupTable; - File3dmInstanceDefinitionTable: typeof File3dmInstanceDefinitionTable; - File3dmLayerTable: typeof File3dmLayerTable; - File3dmLinetypeTable: typeof File3dmLinetypeTable; - File3dmMaterialTable: typeof File3dmMaterialTable; - File3dmMeshModifiers: typeof File3dmMeshModifiers; - File3dmObject: typeof File3dmObject; - File3dmObjectTable: typeof File3dmObjectTable; - File3dmPlugInData: typeof File3dmPlugInData; - File3dmPlugInDataTable: typeof File3dmPlugInDataTable; - File3dmPostEffectTable: typeof File3dmPostEffectTable; - File3dmRdkDocumentData: typeof File3dmRdkDocumentData; - File3dmRenderContentTable: typeof File3dmRenderContentTable; - File3dmSettings: typeof File3dmSettings; - File3dmShutLiningCurveTable: typeof File3dmShutLiningCurveTable; - File3dmStringTable: typeof File3dmStringTable; - File3dmViewTable: typeof File3dmViewTable; - File3dmWriteOptions: typeof File3dmWriteOptions; - FileReference: typeof FileReference; - Font: typeof Font; - GeometryBase: typeof GeometryBase; - GroundPlane: typeof GroundPlane; - Group: typeof Group; - Hatch: typeof Hatch; - InstanceDefinition: typeof InstanceDefinition; - InstanceReference: typeof InstanceReference; - Intersection: typeof Intersection; - Layer: typeof Layer; - Light: typeof Light; - Line: typeof Line; - LinearWorkflow: typeof LinearWorkflow; - LineCurve: typeof LineCurve; - Linetype: typeof Linetype; - Material: typeof Material; - Mesh: typeof Mesh; - MeshFaceList: typeof MeshFaceList; - MeshingParameters: typeof MeshingParameters; - MeshNormalList: typeof MeshNormalList; - MeshTextureCoordinateList: typeof MeshTextureCoordinateList; - MeshTopologyEdgeList: typeof MeshTopologyEdgeList; - MeshVertexColorList: typeof MeshVertexColorList; - MeshVertexList: typeof MeshVertexList; - ModelComponent: typeof ModelComponent; - NurbsCurve: typeof NurbsCurve; - NurbsCurveKnotList: typeof NurbsCurveKnotList; - NurbsCurvePointList: typeof NurbsCurvePointList; - NurbsSurface: typeof NurbsSurface; - NurbsSurfaceKnotList: typeof NurbsSurfaceKnotList; - NurbsSurfacePointList: typeof NurbsSurfacePointList; - ObjectAttributes: typeof ObjectAttributes; - PhysicallyBasedMaterial: typeof PhysicallyBasedMaterial; - Plane: typeof Plane; - PlaneSurface: typeof PlaneSurface; - Point: typeof Point; - Point3d: typeof Point3d; - Point3dList: typeof Point3dList; - PointCloud: typeof PointCloud; - PointCloudItem: typeof PointCloudItem; - PointGrid: typeof PointGrid; - PolyCurve: typeof PolyCurve; - Polyline: typeof Polyline; - PolylineCurve: typeof PolylineCurve; - PostEffect: typeof PostEffect; - RenderChannels: typeof RenderChannels; - RenderContent: typeof RenderContent; - RenderEnvironment: typeof RenderEnvironment; - RenderEnvironments: typeof RenderEnvironments; - RenderMaterial: typeof RenderMaterial; - RenderSettings: typeof RenderSettings; - RenderTexture: typeof RenderTexture; - RevSurface: typeof RevSurface; - SafeFrame: typeof SafeFrame; - ShutLining: typeof ShutLining; - ShutLiningCurve: typeof ShutLiningCurve; - Skylight: typeof Skylight; - Sphere: typeof Sphere; - SubD: typeof SubD; - Sun: typeof Sun; - Surface: typeof Surface; - SurfaceProxy: typeof SurfaceProxy; - TextDot: typeof TextDot; - Texture: typeof Texture; - TextureMapping: typeof TextureMapping; - Thickening: typeof Thickening; - Transform: typeof Transform; - ViewInfo: typeof ViewInfo; - ViewportInfo: typeof ViewportInfo; - } - - class AnnotationBase extends GeometryBase { - /** - * Text including additional RTF formatting information - */ - richText: string; - /** - * Text stripped of RTF formatting information - */ - plainText: string; - } - - class Arc { - /** - * Gets a value indicating whether or not this arc is valid. - * Detail: - * Radius>0 and 0 center + cos(t)*radius*xaxis + sin(t)*radius*yaxis. - * @param {number} t Parameter of point to evaluate. - * @returns {number[]} The point on the circle at the given parameter. - */ - pointAt(t:number): number[]; - /** - * @description Circles use trigonometric parameterization: - t -> center + cos(t)*radius*xaxis + sin(t)*radius*yaxis. - * @param {number} t Parameter of tangent to evaluate. - * @returns {number[]} The tangent at the circle at the given parameter. - */ - tangentAt(t:number): number[]; - /** - * @description Determines the value of the Nth derivative at a parameter. - * @param {number} derivative Which order of derivative is wanted. - * @param {number} t Parameter to evaluate derivative. Valid values are 0, 1, 2 and 3. - * @returns {number[]} The derivative of the circle at the given parameter. - */ - derivativeAt(derivative:number,t:number): number[]; - /** - * @description Gets the parameter on the circle which is closest to a test point. - * @param {number[]} testPoint Point to project onto the circle. - * @returns {Array} [boolean, number] - * (boolean) true on success, false on failure. - * (number) Parameter on circle closes to testPoint. - */ - closestParameter(testPoint:number[]): object; - /** - * @description Gets the point on the circle which is closest to a test point. - * @param {number[]} testPoint Point to project onto the circle. - * @returns {number[]} The point on the circle that is closest to testPoint or - Point3d.Unset on failure. - */ - closestPoint(testPoint:number[]): number[]; - /** - * @description Transforms this circle using an transformation matrix. - * @param {Transform} xform Transformation to apply. - * @returns {boolean} true on success, false on failure. - */ - transform(xform:Transform): boolean; - /** - * @description Moves the circle. - * @param {number[]} delta Translation vector. - * @returns {boolean} true on success, false on failure. - */ - translate(delta:number[]): boolean; - /** - * @description Reverse the orientation of the circle. Changes the domain from [a,b] - to [-b,-a]. - * @returns {void} - */ - reverse(): void; - /** - * @description Constructs a nurbs curve representation of this circle. - This amounts to the same as calling NurbsCurve.CreateFromCircle(). - * @returns {NurbsCurve} A nurbs curve representation of this circle or null if no such representation could be made. - */ - toNurbsCurve(): NurbsCurve; - } - - class CommonObject { - /** - * Tests an object to see if it is valid. - */ - isValid: boolean; - /** - */ - userStringCount: any; - /** ... */ - encode(): void; - /** - * @description Create a JSON string representation of this object - * @returns {string} - */ - toJSON(): string; - /** ... */ - static decode(): void; - /** ... */ - setUserString(): void; - /** ... */ - getUserString(): void; - /** ... */ - getUserStrings(): void; - /** ... */ - rdkXml(): void; - } - - class ComponentIndex { - /** - * The interpretation of Index depends on the Type value. - * Type m_index interpretation (0 based indices) - * no_type used when context makes it clear what array is being index - * brep_vertex Brep.m_V[] array index - * brep_edge Brep.m_E[] array index - * brep_face Brep.m_F[] array index - * brep_trim Brep.m_T[] array index - * brep_loop Brep.m_L[] array index - * mesh_vertex Mesh.m_V[] array index - * meshtop_vertex MeshTopology.m_topv[] array index - * meshtop_edge MeshTopology.m_tope[] array index - * mesh_face Mesh.m_F[] array index - * idef_part InstanceDefinition.m_object_uuid[] array index - * polycurve_segment PolyCurve::m_segment[] array index - * dim_linear_point LinearDimension2::POINT_INDEX - * dim_radial_point RadialDimension2::POINT_INDEX - * dim_angular_point AngularDimension2::POINT_INDEX - * dim_ordinate_point OrdinateDimension2::POINT_INDEX - * dim_text_point TextEntity2 origin point. - */ - componentIndexType: ComponentIndexType; - /** - * The interpretation of m_index depends on the m_type value. - * m_type m_index interpretation (0 based indices) - * no_type used when context makes it clear what array is being index - * brep_vertex Brep.m_V[] array index - * brep_edge Brep.m_E[] array index - * brep_face Brep.m_F[] array index - * brep_trim Brep.m_T[] array index - * brep_loop Brep.m_L[] array index - * mesh_vertex Mesh.m_V[] array index - * meshtop_vertex MeshTopology.m_topv[] array index - * meshtop_edge MeshTopology.m_tope[] array index - * mesh_face Mesh.m_F[] array index - * idef_part InstanceDefinition.m_object_uuid[] array index - * polycurve_segment PolyCurve::m_segment[] array index - * dim_linear_point LinearDimension2::POINT_INDEX - * dim_radial_point RadialDimension2::POINT_INDEX - * dim_angular_point AngularDimension2::POINT_INDEX - * dim_ordinate_point OrdinateDimension2::POINT_INDEX - * dim_text_point TextEntity2 origin point. - */ - index: number; - } - - class Cone { - /** - * Gets or sets the height of the circular right cone. - */ - height: number; - /** - * Gets or sets the radius of the cone. - */ - radius: number; - /** - * true if plane is valid, height is not zero and radius is not zero. - */ - isValid: boolean; - /** - * Center of base circle. - */ - basePoint: number[]; - /** - * Point at tip of the cone. - */ - apexPoint: number[]; - /** - * Unit vector axis of cone. - */ - axis: number[]; - /** - */ - angleInRadians: any; - /** - */ - angleInDegrees: any; - /** - * @description Constructs a Nurbs surface representation of this Cone. - This is synonymous with calling NurbsSurface.CreateFromCone(). - * @returns {NurbsSurface} A Nurbs surface representation of the cone or null. - */ - toNurbsSurface(): NurbsSurface; - /** - * @description Gets a Brep representation of the cone with a single - face for the cone, an edge along the cone seam, - and vertices at the base and apex ends of this seam edge. - The optional cap is a single face with one circular edge - starting and ending at the base vertex. - * @param {boolean} capBottom true if the bottom should be filled with a surface. false otherwise. - * @returns {Brep} A brep (polysurface) representation of this cone values. - */ - toBrep(capBottom:boolean): Brep; - } - - class ConstructionPlane { - /** - * Gets or sets the geometric plane to use for construction. - */ - plane: Plane; - /** - * Gets or sets the distance between grid lines. - */ - gridSpacing: number; - /** - * when "grid snap" is enabled, the distance between snap points. - * Typically this is the same distance as grid spacing. - */ - snapSpacing: number; - /** - * Gets or sets the total amount of grid lines in each direction. - */ - gridLineCount: number; - /** - * Gets or sets the recurrence of a wider line on the grid. - * 0: No lines are thick, all are drawn thin.1: All lines are thick.2: Every other line is thick.3: One line in three lines is thick (and two are thin).4: ... - */ - thickLineFrequency: number; - /** - * Gets or sets whether the grid is drawn on top of geometry. - * false=grid is always drawn behind 3d geometrytrue=grid is drawn at its depth as a 3d plane and grid lines obscure things behind the grid. - */ - depthBuffered: boolean; - /** - * Gets or sets the name of the construction plane. - */ - name: string; - } - - class Curve extends GeometryBase { - /** - * Gets or sets the domain of the curve. - */ - domain: number[]; - /** - * Gets the dimension of the object. - * The dimension is typically three. For parameter space trimming - * curves the dimension is two. In rare cases the dimension can - * be one or greater than three. - */ - dimension: number; - /** - * Gets the number of non-empty smooth (c-infinity) spans in the curve. - */ - spanCount: number; - /** - * Gets the maximum algebraic degree of any span - * or a good estimate if curve spans are not algebraic. - */ - degree: number; - /** - * Gets a value indicating whether or not this curve is a closed curve. - */ - isClosed: boolean; - /** - * Gets a value indicating whether or not this curve is considered to be Periodic. - */ - isPeriodic: boolean; - /** - * Evaluates point at the start of the curve. - */ - pointAtStart: number[]; - /** - * Evaluates point at the end of the curve. - */ - pointAtEnd: number[]; - /** - * Evaluates the unit tangent vector at the start of the curve. - */ - tangentAtStart: number[]; - /** - * Evaluate unit tangent vector at the end of the curve. - */ - tangentAtEnd: number[]; - /** ... */ - static createControlPointCurve(): void; - /** - * @description Changes the dimension of a curve. - * @param {number} desiredDimension The desired dimension. - * @returns {boolean} true if the curve's dimension was already desiredDimension - or if the curve's dimension was successfully changed to desiredDimension; - otherwise false. - */ - changeDimension(desiredDimension:number): boolean; - /** - * @description Test a curve to see if it is linear to within RhinoMath.ZeroTolerance units (1e-12). - * @returns {boolean} true if the curve is linear. - */ - isLinear(): boolean; - /** - * @description Several types of Curve can have the form of a polyline - including a degree 1 NurbsCurve, a PolylineCurve, - and a PolyCurve all of whose segments are some form of - polyline. IsPolyline tests a curve to see if it can be - represented as a polyline. - * @returns {boolean} true if this curve can be represented as a polyline; otherwise, false. - */ - isPolyline(): boolean; - /** - * @description Several types of Curve can have the form of a polyline - including a degree 1 NurbsCurve, a PolylineCurve, - and a PolyCurve all of whose segments are some form of - polyline. IsPolyline tests a curve to see if it can be - represented as a polyline. - * @returns {Array} [boolean, Polyline] - * (boolean) true if this curve can be represented as a polyline; otherwise, false. - * (Polyline) If true is returned, then the polyline form is returned here. - */ - tryGetPolyline(): object; - /** - * @description Test a curve to see if it can be represented by an arc or circle within RhinoMath.ZeroTolerance. - * @returns {boolean} true if the curve can be represented by an arc or a circle within tolerance. - */ - isArc(): boolean; - /** - * @description Try to convert this curve into an Arc using RhinoMath.ZeroTolerance. - * @returns {Array} [boolean, Arc] - * (boolean) true if the curve could be converted into an arc. - * (Arc) On success, the Arc will be filled in. - */ - tryGetArc(): object; - /** - * @description Test a curve to see if it can be represented by a circle within RhinoMath.ZeroTolerance. - * @returns {boolean} true if the Curve can be represented by a circle within tolerance. - */ - isCircle(): boolean; - /** - * @description Try to convert this curve into a circle using RhinoMath.ZeroTolerance. - * @returns {Array} [boolean, Circle] - * (boolean) true if the curve could be converted into a Circle. - * (Circle) On success, the Circle will be filled in. - */ - tryGetCircle(): object; - /** - * @description Test a curve to see if it can be represented by an ellipse within RhinoMath.ZeroTolerance. - * @returns {boolean} true if the Curve can be represented by an ellipse within tolerance. - */ - isEllipse(): boolean; - /** - * @description Test a curve for planarity. - * @returns {boolean} true if the curve is planar (flat) to within RhinoMath.ZeroTolerance units (1e-12). - */ - isPlanar(): boolean; - /** - * @description If this curve is closed, then modify it so that the start/end point is at curve parameter t. - * @param {number} t Curve parameter of new start/end point. The returned curves domain will start at t. - * @returns {boolean} true on success, false on failure. - */ - changeClosedCurveSeam(t:number): boolean; - /** - * @description Reverses the direction of the curve. - * @returns {boolean} true on success, false on failure. - */ - reverse(): boolean; - /** - * @description Determines the orientation (counterclockwise or clockwise) of a closed, planar curve in the world XY plane. - Only works with simple (no self intersections) closed, planar curves. - * @returns {CurveOrientation} The orientation of this curve with respect to world XY plane. - */ - closedCurveOrientation(): CurveOrientation; - /** ... */ - closedCurveOrientationPlane(): void; - /** - * @description Evaluates point at a curve parameter. - * @param {number} t Evaluation parameter. - * @returns {number[]} Point (location of curve at the parameter t). - */ - pointAt(t:number): number[]; - /** - * @description Forces the curve to start at a specified point. - Not all curve types support this operation. - * @param {number[]} point New start point of curve. - * @returns {boolean} true on success, false on failure. - */ - setStartPoint(point:number[]): boolean; - /** - * @description Forces the curve to end at a specified point. - Not all curve types support this operation. - * @param {number[]} point New end point of curve. - * @returns {boolean} true on success, false on failure. - */ - setEndPoint(point:number[]): boolean; - /** - * @description Evaluates the unit tangent vector at a curve parameter. - * @param {number} t Evaluation parameter. - * @returns {number[]} Unit tangent vector of the curve at the parameter t. - */ - tangentAt(t:number): number[]; - /** - * @description Evaluate the curvature vector at a curve parameter. - * @param {number} t Evaluation parameter. - * @returns {number[]} Curvature vector of the curve at the parameter t. - */ - curvatureAt(t:number): number[]; - /** - * @description Returns a 3d frame at a parameter. - * @param {number} t Evaluation parameter. - * @returns {Array} [boolean, Plane] - * (boolean) true on success, false on failure. - * (Plane) The frame is returned here. - */ - frameAt(t:number): object; - /** - * @description Evaluate the derivatives at the specified curve parameter. - * @param {number} t Curve parameter to evaluate. - * @param {number} derivativeCount Number of derivatives to evaluate, must be at least 0. - * @returns {any[]} An array of vectors that represents all the derivatives starting at zero. - */ - derivativeAt(t:number,derivativeCount:number): any[]; - /** ... */ - derivativeAtSide(): void; - /** - * @description Convert a NURBS curve parameter to a curve parameter. - * @param {number} nurbsParameter NURBS form parameter. - * @returns {Array} [boolean, number] - * (boolean) true on success, false on failure. - * (number) Curve parameter. - */ - getCurveParameterFromNurbsFormParameter(nurbsParameter:number): object; - /** - * @description Convert a curve parameter to a NURBS curve parameter. - * @param {number} curveParameter Curve parameter. - * @returns {Array} [boolean, number] - * (boolean) true on success, false on failure. - * (number) NURBS form parameter. - */ - getNurbsFormParameterFromCurveParameter(curveParameter:number): object; - /** - * @description Removes portions of the curve outside the specified interval. - * @param {number} t0 Start of the trimming interval. Portions of the curve before curve(t0) are removed. - * @param {number} t1 End of the trimming interval. Portions of the curve after curve(t1) are removed. - * @returns {Curve} Trimmed portion of this curve is successful, null on failure. - */ - trim(t0:number,t1:number): Curve; - /** - * @description Splits (divides) the curve at the specified parameter. - The parameter must be in the interior of the curve's domain. - * @param {number} t Parameter to split the curve at in the interval returned by Domain(). - * @returns {Curve[]} Two curves on success, null on failure. - */ - split(t:number): Curve[]; - /** - * @description Constructs a NURBS curve representation of this curve. - * @returns {NurbsCurve} NURBS representation of the curve on success, null on failure. - */ - toNurbsCurve(): NurbsCurve; - /** ... */ - toNurbsCurveSubDomain(): void; - } - - class CurvePiping { - /** - */ - on: any; - /** - */ - radius: any; - /** - */ - segments: any; - /** - */ - faceted: any; - /** - */ - accuracy: any; - /** - */ - capType: any; - } - - class CurveProxy extends Curve { - /** - * True if "this" is a curve is reversed from the "real" curve geometry - */ - proxyCurveIsReversed: boolean; - } - - class Cylinder { - /** - * Gets a boolean value indicating whether this cylinder is valid. - * A valid cylinder is represented by a valid circle and two valid heights. - */ - isValid: boolean; - /** - * true if the cylinder is finite (Height0 != Height1) - * false if the cylinder is infinite. - */ - isFinite: boolean; - /** - * Gets the center point of the defining circle. - */ - center: number[]; - /** - * Gets the axis direction of the cylinder. - */ - axis: number[]; - /** - * Gets the height of the cylinder. - * Infinite cylinders have a height of zero, not Double.PositiveInfinity. - */ - totalHeight: number; - /** - * Gets or sets the start height of the cylinder. - * The center of bottom cap is: BasePlane.Origin + Height1 * BasePlane.ZAxis. - */ - height1: number; - /** - * Gets or sets the end height of the cylinder. - * If the end height equals the start height, the cylinder is - * presumed to be infinite. - * The center of top cap is: BasePlane.Origin + Height2 * BasePlane.ZAxis. - */ - height2: number; - /** - * Gets or sets the radius of the cylinder. - */ - radius: number; - - constructor(baseCircle: Circle); - - constructor(baseCircle: Circle, height: number); - /** - * @description Compute the circle at the given elevation parameter. - * @param {number} linearParameter Height parameter for circle section. - * @returns {Circle} - */ - circleAt(linearParameter:number): Circle; - /** - * @description Constructs a Brep representation of this Cylinder. - This is synonymous with calling NurbsSurface.CreateFromCylinder(). - * @param {boolean} capBottom If true, the bottom of the cylinder will be capped. - * @param {boolean} capTop If true, the top of the cylinder will be capped. - * @returns {Brep} A Brep representation of the cylinder or null. - */ - toBrep(capBottom:boolean,capTop:boolean): Brep; - /** - * @description Constructs a Nurbs surface representation of this cylinder. - This is synonymous with calling NurbsSurface.CreateFromCylinder(). - * @returns {NurbsSurface} A Nurbs surface representation of the cylinder or null. - */ - toNurbsSurface(): NurbsSurface; - } - - class Decal { - /** - * Gets the texture ID for this decal. - */ - textureInstanceId: string; - /** - * Gets the decal's mapping. - */ - mapping: DecalMapping; - /** - * Gets the decal's projection. Used only when mapping is planar. - */ - projection: DecalProjection; - /** - * Used only when mapping is cylindrical or spherical. - */ - mapToInside: boolean; - /** - * Gets the decal's transparency in the range 0 to 1. - */ - transparency: number; - /** - * Gets the origin of the decal in world space. - */ - origin: Rhino.Point3d; - /** - * For cylindrical and spherical mapping, the vector is unitized. - */ - vectorUp: Rhino.Vector3d; - /** - * Gets the vector across. For cylindrical and spherical mapping, the vector is unitized. - */ - vectorAcross: Rhino.Vector3d; - /** - * Gets the height of the decal. Only used when mapping is cylindrical. - */ - height: number; - /** - * Gets the radius of the decal. Only used when mapping is cylindrical or spherical. - */ - radius: number; - /** - */ - horzSweepStart: any; - /** - */ - horzSweepEnd: any; - /** - */ - vertSweepStart: any; - /** - */ - vertSweepEnd: any; - /** - */ - boundsMinU: any; - /** - */ - boundsMinV: any; - /** - */ - boundsMaxU: any; - /** - */ - boundsMaxV: any; - } - - class DimensionStyle extends CommonObject { - /** - */ - name: any; - /** - */ - arrowBlockId1: string; - /** - */ - arrowBlockId2: string; - /** - */ - leaderArrowBlockId: string; - /** - */ - suppressExtension1: boolean; - /** - */ - suppressExtension2: boolean; - /** - */ - suppressArrow1: boolean; - /** - */ - suppressArrow2: boolean; - /** - */ - alternateBelowLine: boolean; - /** - */ - drawTextMask: boolean; - /** - */ - leaderHasLanding: boolean; - /** - */ - drawForward: boolean; - /** - */ - textUnderlined: boolean; - /** - */ - arrowLength: number; - /** - */ - leaderArrowLength: number; - /** - */ - centermarkSize: number; - /** - */ - textGap: number; - /** - */ - textHEight: number; - /** - */ - lengthFactor: number; - /** - */ - alternateLengthFactor: number; - /** - */ - toleranceUpperValue: number; - /** - */ - toleranceLowerValue: number; - /** - */ - toleranceHeightScale: number; - /** - */ - baselineSpacing: number; - /** - */ - textRotation: number; - /** - */ - stackHeightScale: number; - /** - */ - leaderLandingLength: number; - /** - * Checks if any fields in this DimensionStyle are overrides - */ - hasFieldOverrides: boolean; - /** - * Tests if this DimensionStyle is a child of any other DimensionStyle - */ - isChild: boolean; - /** - * Get or Set the Id of this DimensionStyle's parent. - * If ParentId is Guid.Empty, this DimensionStyle has no parent - */ - parentId: string; - /** ... */ - getFont(): void; - /** ... */ - setFont(): void; - /** - * @description Scales all length values by 'scale' - * @returns {void} - */ - scaleLengthValues(): void; - /** - * @description Sets all the fields in this DimensionStyle to be not overridden - Does not change any dimstyle_id's or parent_id's - * @returns {void} - */ - clearAllFieldOverrides(): void; - /** - * @description Tests if this DimensionStyle is a child of a specific DimensionStyle - * @returns {boolean} True if this is a child of the DimensionStyle with Parent - False otherwise. - */ - isChildOf(): boolean; - } - - class Displacement { - /** - */ - on: any; - /** - */ - texture: any; - /** - */ - blackPoint: any; - /** - */ - whitePoint: any; - /** - */ - postWeldAngle: any; - /** - */ - fairingOn: any; - /** - */ - fairing: any; - /** - */ - finalMaxFaces: any; - /** - */ - finalMaxFacesOn: any; - /** - */ - initialQuality: any; - /** - */ - mappingChannel: any; - /** - */ - meshMemoryLimit: any; - /** - */ - refineSteps: any; - /** - */ - refineSensitivity: any; - /** - */ - sweepResolutionFormula: any; - } - - class Dithering { - /** - */ - enabled: boolean; - /** - */ - method: Methods; - } - - class DracoCompression { - /** ... */ - static compress(): void; - /** ... */ - static compressOptions(): void; - /** ... */ - static decompressByteArray(): void; - /** ... */ - static decompressBase64String(): void; - /** ... */ - toBase64String(): void; - } - - class DracoCompressionOptions { - /** - */ - compressionLevel: any; - /** - */ - positionQuantizationBits: any; - /** - */ - textureCoordintateQuantizationBits: any; - /** - */ - normalQuantizationBits: any; - /** - */ - includeNormals: any; - /** - */ - includeTextureCoordinates: any; - /** - */ - includeVertexColors: any; - } - - class EarthAnchorPoint { - /** - * Gets or sets a point latitude on earth, in degrees. - * +90 = north pole, 0 = equator, -90 = south pole. - */ - earthBasepointLatitude: number; - /** - * Gets or sets the point longitude on earth, in degrees. - */ - earthBasepointLongitude: number; - /** - * Gets or sets the point elevation on earth, in meters. - */ - earthBasepointElevation: number; - /** - * Gets or sets a value indicating the zero level convention relating to a location on Earth. - */ - earthBasepointElevationZero: BasepointZero; - /** - * Corresponding model point in model coordinates. - */ - modelBasePoint: number[]; - /** - * Earth directions in model coordinates. - */ - modelNorth: number[]; - /** - * Earth directions in model coordinates. - */ - modelEast: number[]; - /** - * Gets or sets the short form of the identifying information about this location. - */ - name: string; - /** - * Gets or sets the long form of the identifying information about this location. - */ - description: string; - /** - * @description Checks if the earth location is set or not. - * @returns {boolean} Boolean value, true if set else false - */ - earthLocationIsSet(): boolean; - /** - * @description Returns a plane in model coordinates whose X axis points East, - Y axis points North and Z axis points Up. The origin - is set to ModelBasepoint. - * @returns {Plane} A plane value. This might be invalid on error. - */ - getModelCompass(): Plane; - /** - * @description Gets a transformation from model coordinates to earth coordinates. - This transformation assumes the model is small enough that - the curvature of the earth can be ignored. - * @param {UnitSystem} modelUnitSystem The model unit system. - * @returns {Transform} Transform on success. Invalid Transform on error. - */ - getModelToEarthTransform(modelUnitSystem:UnitSystem): Transform; - } - - class EdgeSoftening { - /** - */ - on: any; - /** - */ - softening: any; - /** - */ - chamfer: any; - /** - */ - faceted: any; - /** - */ - edgeAngleThreshold: any; - /** - */ - forceSoftening: any; - } - - class Ellipse { - } - - class EmbeddedFile { - /** - */ - length: any; - /** - */ - fileName: any; - /** ... */ - write(): void; - /** ... */ - clear(): void; - } - - class Environment { - /** - * The background color. - */ - backgroundColor: number[]; - /** - * The background projection. - */ - backgroundProjection: BackgroundProjections; - /** ... */ - getBackgroundImage(): void; - /** ... */ - setBackgroundImage(): void; - } - - class Extrusion extends Surface { - /** - * Gets the start point of the path. - */ - pathStart: number[]; - /** - * Gets the end point of the path. - */ - pathEnd: number[]; - /** - * Gets the up vector of the path. - */ - pathTangent: number[]; - /** - * Gets or sets the normal of the miter plane at the start in profile coordinates. - * In profile coordinates, 0,0,1 always maps to the extrusion axis - */ - miterPlaneNormalAtStart: number[]; - /** - * Gets or sets the normal of the miter plane at the end in profile coordinates. - * In profile coordinates, 0,0,1 always maps to the extrusion axis - */ - miterPlaneNormalAtEnd: number[]; - /** - * Returns a value indicating whether a miter plane at start is defined. - */ - isMiteredAtStart: boolean; - /** - * Gets a value indicating whether a miter plane at the end is defined. - */ - isMiteredAtEnd: boolean; - /** - * Gets a value indicating whether there is no gap among all surfaces constructing this object. - */ - isSolid: boolean; - /** - * Gets a value indicating whether the surface that fills the bottom profile is existing. - */ - isCappedAtBottom: boolean; - /** - * Gets a value indicating whether the surface that fills the top profile is existing. - */ - isCappedAtTop: boolean; - /** - * Gets the amount of capping surfaces. - */ - capCount: number; - /** - * Gets the amount of profile curves. - */ - profileCount: number; - /** - * @description Creates an extrusion of a 3d curve (which must be planar) and a height. - * @param {Curve} planarCurve Planar curve used as profile - * @param {number} height If the height > 0, the bottom of the extrusion will be in plane and - the top will be height units above the plane. - If the height < 0, the top of the extrusion will be in plane and - the bottom will be height units below the plane. - The plane used is the one that is returned from the curve's TryGetPlane function. - * @param {boolean} cap If the curve is closed and cap is true, then the resulting extrusion is capped. - * @returns {Extrusion} If the input is valid, then a new extrusion is returned. Otherwise null is returned - */ - static create(planarCurve:Curve,height:number,cap:boolean): Extrusion; - /** - * @description Gets an extrusion from a box. - * @param {Box} box IsValid must be true. - * @param {boolean} cap If true, the base and the top of the box will be capped. Defaults to true. - * @returns {Extrusion} Extrusion on success. null on failure. - */ - static createBoxExtrusion(box:Box,cap:boolean): Extrusion; - /** - * @description Gets an extrusion form of a cylinder. - * @param {Cylinder} cylinder IsFinite must be true. - * @param {boolean} capBottom If true, the end at cylinder.Height1 will be capped. - * @param {boolean} capTop If true, the end at cylinder.Height2 will be capped. - * @returns {Extrusion} Extrusion on success. null on failure. - */ - static createCylinderExtrusion(cylinder:Cylinder,capBottom:boolean,capTop:boolean): Extrusion; - /** - * @description Gets an extrusion form of a pipe. - * @param {Cylinder} cylinder IsFinite must be true. - * @param {number} otherRadius If cylinder.Radius is less than other radius, then the cylinder will be the inside - of the pipe. - * @param {boolean} capBottom If true, the end at cylinder.Height1 will be capped. - * @param {boolean} capTop If true, the end at cylinder.Height2 will be capped. - * @returns {Extrusion} Extrusion on success. null on failure. - */ - static createPipeExtrusion(cylinder:Cylinder,otherRadius:number,capBottom:boolean,capTop:boolean): Extrusion; - /** - * @description Constructs a brep form of the extrusion. The outer profile is always the first face of the brep. - If there are inner profiles, additional brep faces are created for each profile. If the - outer profile is closed, then end caps are added as the last two faces of the brep. - * @param {boolean} splitKinkyFaces If true and the profiles have kinks, then the faces corresponding to those profiles are split - so they will be G1. - * @returns {Brep} A brep with a similar shape like this extrusion, or null on error. - */ - toBrep(splitKinkyFaces:boolean): Brep; - /** - * @description Allows to set the two points at the extremes and the up vector. - * @param {number[]} a The start point. - * @param {number[]} b The end point. - * @param {number[]} up The up vector. - * @returns {boolean} true if the operation succeeded; otherwise false. - Setting up=a-b will make the operation fail. - */ - setPathAndUp(a:number[],b:number[],up:number[]): boolean; - /** - * @description Gets the transformation that maps the XY profile curve to its 3d location. - * @param {number} s 0.0 = starting profile - 1.0 = ending profile. - * @returns {Transform} A Transformation. The transform is Invalid on failure. - */ - getProfileTransformation(s:number): Transform; - /** - * @description Gets the 3D plane containing the profile curve at a normalized path parameter. - * @param {number} s 0.0 = starting profile - 1.0 = ending profile. - * @returns {Plane} A plane. The plane is Invalid on failure. - */ - getProfilePlane(s:number): Plane; - /** - * @description Gets the 3D plane perpendicular to the path at a normalized path parameter. - * @param {number} s 0.0 = starting profile - 1.0 = ending profile. - * @returns {Plane} A plane. The plane is Invalid on failure. - */ - getPathPlane(s:number): Plane; - /** - * @description Sets the outer profile of the extrusion. - * @param {Curve} outerProfile curve in the XY plane or a 2D curve. - * @param {boolean} cap If outerProfile is a closed curve, then cap determines if the extrusion - has end caps. If outerProfile is an open curve, cap is ignored. - * @returns {boolean} true if the profile was set. If the outer profile is closed, then the - extrusion may also have inner profiles. If the outer profile is open, - the extrusion may not have inner profiles. If the extrusion already - has a profile, the set will fail. - */ - setOuterProfile(outerProfile:Curve,cap:boolean): boolean; - /** - * @description Adds an inner profile. - * @param {Curve} innerProfile Closed curve in the XY plane or a 2d curve. - * @returns {boolean} true if the profile was set. - */ - addInnerProfile(innerProfile:Curve): boolean; - /** - * @description Gets a transversal isocurve of the extruded profile. - * @param {number} profileIndex 0 <= profileIndex < ProfileCount - The outer profile has index 0. - * @param {number} s 0.0 <= s <= 1.0 - A relative parameter controlling which profile is returned. - 0 = bottom profile and 1 = top profile. - * @returns {Curve} The profile. - */ - profile3d(profileIndex:number,s:number): Curve; - /** - * @description Gets the line-like curve that is the conceptual axis of the extrusion. - * @returns {LineCurve} The path as a line curve. - */ - pathLineCurve(): LineCurve; - /** - * @description Gets one of the longitudinal curves along the beam or extrusion. - * @param {ComponentIndex} ci The index of this profile. - * @returns {Curve} The profile. - */ - wallEdge(ci:ComponentIndex): Curve; - /** - * @description Gets one of the longitudinal surfaces of the extrusion. - * @param {ComponentIndex} ci The index specifying which precise item to retrieve. - * @returns {Surface} The surface. - */ - wallSurface(ci:ComponentIndex): Surface; - /** - * @description Gets the line-like curve that is the conceptual axis of the extrusion. - * @returns {LineCurve} The path as a line curve. - */ - pathLineCurve(): LineCurve; - /** - * @description Gets the index of the profile curve at a domain related to a parameter. - * @param {number} profileParameter Parameter on profile curve. - * @returns {number} -1 if profileParameter does not correspond to a point on the profile curve. - When the profileParameter corresponds to the end of one profile and the - beginning of the next profile, the index of the next profile is returned. - */ - profileIndex(profileParameter:number): number; - /** - * @description Obtains a reference to a specified type of mesh for this extrusion. - * @param {MeshType} meshType The mesh type. - * @returns {Mesh} A mesh. - */ - getMesh(meshType:MeshType): Mesh; - /** - * @description Sets a specified type of mesh for this extrusion. - * @param {Mesh} mesh The mesh. - * @param {MeshType} meshType The mesh type. - * @returns {boolean} A bool. - */ - setMesh(mesh:Mesh,meshType:MeshType): boolean; - } - - class File3dm { - /** - * Gets or sets the start section comments, which are the comments with which the 3dm file begins. - */ - startSectionComments: string; - /** - * Gets or sets the name of the application that wrote this file. - */ - applicationName: string; - /** - * Gets or sets a URL for the application that wrote this file. - */ - applicationUrl: string; - /** - * Gets or sets details for the application that wrote this file. - */ - applicationDetails: string; - /** - * Gets the 3dm file archive version. - */ - archiveVersion: number; - /** - * Get the DateTime that this file was originally created. If the - * value is not set in the 3dm file, then DateTime.MinValue is returned - */ - created: DateTime; - /** - * Gets a string that names the user who created the file. - */ - createdBy: string; - /** - * Get the DateTime that this file was last edited. If the - * value is not set in the 3dm file, then DateTime.MinValue is returned - */ - lastEdited: DateTime; - /** - * Gets a string that names the user who last edited the file. - */ - lastEditedBy: string; - /** - * Gets or sets the revision number. - */ - revision: number; - /** ... */ - destroy(): void; - /** - * @description Read a 3dm file from a byte array - * @returns {File3dm} New File3dm on success, null on error. - */ - static fromByteArray(): File3dm; - /** ... */ - settings(): void; - /** ... */ - objects(): void; - /** ... */ - materials(): void; - /** ... */ - linetypes(): void; - /** ... */ - bitmaps(): void; - /** ... */ - layers(): void; - /** ... */ - groups(): void; - /** ... */ - dimstyles(): void; - /** ... */ - instanceDefinitions(): void; - /** ... */ - views(): void; - /** ... */ - namedViews(): void; - /** ... */ - plugInData(): void; - /** ... */ - strings(): void; - /** ... */ - embeddedFiles(): void; - /** ... */ - renderContent(): void; - /** ... */ - encode(): void; - /** ... */ - encodeOptions(): void; - /** - * @description Write to an in-memory byte[] - * @returns {Uint8Array} - */ - toByteArray(): Uint8Array; - /** ... */ - toByteArrayOptions(): void; - /** ... */ - static decode(): void; - /** ... */ - embeddedFilePaths(): void; - /** ... */ - getEmbeddedFileAsBase64(): void; - /** ... */ - getEmbeddedFileAsBase64Strict(): void; - /** ... */ - rdkXml(): void; - } - - class File3dmBitmapTable { - /** - */ - count: any; - /** ... */ - get(): void; - /** ... */ - add(): void; - /** ... */ - findIndex(): void; - /** ... */ - findId(): void; - } - - class File3dmDecalTable { - /** - */ - count: any; - /** ... */ - get(): void; - /** ... */ - findIndex(): void; - } - - class File3dmDimStyleTable { - /** - */ - count: any; - /** ... */ - get(): void; - /** ... */ - add(): void; - /** - * @description Retrieves a DimensionStyle object based on Index. This search type of search is discouraged. - We are moving towards using only IDs for all tables. - * @param {number} index The index to search for. - * @returns {DimensionStyle} A DimensionStyle object, or null if none was found. - */ - findIndex(index:number): DimensionStyle; - /** ... */ - findId(): void; - } - - class File3dmEmbeddedFileTable { - /** - */ - count: any; - /** ... */ - get(): void; - /** ... */ - add(): void; - /** ... */ - findIndex(): void; - } - - class File3dmGroupTable { - /** - */ - count: any; - /** ... */ - get(): void; - /** ... */ - add(): void; - /** ... */ - delete(): void; - /** ... */ - deleteIndex(): void; - /** ... */ - deleteId(): void; - /** - * @description Retrieves a Group object based on an index. This search type of search is discouraged. - We are moving towards using only IDs for all tables. - * @param {number} groupIndex The index to search for. - * @returns {Group} A Group object, or null if none was found. - */ - findIndex(groupIndex:number): Group; - /** - * @description Finds a Group given its name. - * @param {string} name The name of the Group to be searched. - * @returns {Group} A Group, or null on error. - */ - findName(name:string): Group; - } - - class File3dmInstanceDefinitionTable { - /** - */ - count: any; - /** ... */ - get(): void; - /** - * @description Adds an instance definition to the instance definition table. - * @param {string} name The definition name. - * @param {string} description The definition description. - * @param {string} url A URL or hyperlink. - * @param {string} urlTag A description of the URL or hyperlink. - * @param {number[]} basePoint A base point. - * @param {GeometryBase[]} geometry An array, a list or any enumerable set of geometry. - * @param {ObjectAttributes[]} attributes An array, a list or any enumerable set of attributes. - * @returns {number} >=0 index of instance definition in the instance definition table. -1 on failure. - */ - add(name:string,description:string,url:string,urlTag:string,basePoint:number[],geometry:GeometryBase[],attributes:ObjectAttributes[]): number; - /** ... */ - findIndex(): void; - /** ... */ - findId(): void; - } - - class File3dmLayerTable { - /** - */ - count: any; - /** ... */ - get(): void; - /** ... */ - add(): void; - /** - * @description Easy way to add a new layer to the model. - * @param {string} name Layer name. - * @param {number[]} color Layer color. - * @returns {number} The layer's index (>=0) is returned. Otherwise, RhinoMath.UnsetIntIndex is returned. - */ - addLayer(name:string,color:number[]): number; - /** - * @description Finds a Layer given its name. - * @param {string} name The name of the Layer to be searched. - * @param {string} parentId The id of the parent Layer to be searched. - * @returns {Layer} A Layer, or null on error. - */ - findName(name:string,parentId:string): Layer; - /** - * @description Retrieves a Layer object based on Index. This search type of search is discouraged. - We are moving towards using only IDs for all tables. - * @param {number} index The index to search for. - * @returns {Layer} A Layer object, or null if none was found. - */ - findIndex(index:number): Layer; - /** ... */ - findId(): void; - } - - class File3dmLinetypeTable { - /** - */ - count: any; - /** ... */ - get(): void; - /** ... */ - add(): void; - /** ... */ - delete(): void; - /** - * @description Retrieves a Linetype object based on Index. This search type of search is discouraged. - We are moving towards using only IDs for all tables. - * @param {number} index The index to search for. - * @returns {Linetype} A Linetype, or null if none was found. - */ - findIndex(index:number): Linetype; - /** ... */ - findId(): void; - /** - * @description Finds a Linetype given its name. - * @param {string} name The name of the Linetype to be searched. - * @returns {Linetype} A Linetype, or null on error. - */ - findName(name:string): Linetype; - /** ... */ - fromAttributes(): void; - /** ... */ - fromLayerIndex(): void; - } - - class File3dmMaterialTable { - /** - */ - count: any; - /** ... */ - get(): void; - /** ... */ - add(): void; - /** - * @description Retrieves a material based on Index. This search type of search is discouraged. - We are moving towards using only IDs for all tables. - * @param {number} index The index to search for. - * @returns {Material} A material, or null if none was found. - */ - findIndex(index:number): Material; - /** ... */ - findId(): void; - /** ... */ - findFromAttributes(): void; - } - - class File3dmMeshModifiers { - /** ... */ - displacement(): void; - /** ... */ - edgeSoftening(): void; - /** ... */ - thickening(): void; - /** ... */ - curvePiping(): void; - /** ... */ - shutLining(): void; - /** ... */ - createDisplacement(): void; - /** ... */ - createEdgeSoftening(): void; - /** ... */ - createThickening (): void; - /** ... */ - createCurvePiping(): void; - /** ... */ - createShutLining (): void; - } - - class File3dmObject { - /** ... */ - attributes(): void; - /** ... */ - geometry(): void; - } - - class File3dmObjectTable { - /** - * Returns the total amount of items in the object table, including lights. - */ - count: number; - /** ... */ - get(): void; - /** ... */ - addPointXYZ(): void; - /** - * @description Adds a point object to the table. - * @param {number} x X component of point coordinate. - * @param {number} y Y component of point coordinate. - * @param {number} z Z component of point coordinate. - * @returns {string} id of new object. - */ - addPoint(x:number,y:number,z:number): string; - /** - * @description Adds a point cloud object to the document. - * @param {PointCloud} cloud PointCloud to add. - * @returns {string} A unique identifier for the object. - */ - addPointCloud(cloud:PointCloud): string; - /** - * @description Adds a line object to Rhino. - * @param {number[]} from A line start point. - * @param {number[]} to A line end point. - * @returns {string} A unique identifier of new rhino object. - */ - addLine(from:number[],to:number[]): string; - /** - * @description Adds a polyline object to Rhino. - * @param {Point3d[]} points A list, an array or any enumerable set of . - * @returns {string} A unique identifier for the object. - */ - addPolyline(points:Point3d[]): string; - /** - * @description Adds a curve object to the document representing an arc. - * @param {Arc} arc An arc. - * @returns {string} A unique identifier for the object. - */ - addArc(arc:Arc): string; - /** - * @description Adds a curve object to the document representing a circle. - * @param {Circle} circle A circle to add. - * @returns {string} A unique identifier for the object. - */ - addCircle(circle:Circle): string; - /** - * @description Adds a curve object to the document representing an ellipse. - * @param {Ellipse} ellipse An ellipse to add. - * @returns {string} A unique identifier for the object. - */ - addEllipse(ellipse:Ellipse): string; - /** - * @description Adds a surface object to the document representing a sphere. - * @param {Sphere} sphere A sphere to add. - * @returns {string} A unique identifier for the object. - */ - addSphere(sphere:Sphere): string; - /** - * @description Adds a curve object to the table. - * @param {Curve} curve A curve to add. - * @returns {string} A unique identifier for the object. - */ - addCurve(curve:Curve): string; - /** - * @description Adds a text dot object to the table. - * @param {string} text The text. - * @param {number[]} location The location. - * @returns {string} A unique identifier for the object. - */ - addTextDot(text:string,location:number[]): string; - /** - * @description Adds a surface object to Rhino. - * @param {Surface} surface A duplicate of this surface is added to Rhino. - * @returns {string} A unique identifier for the object. - */ - addSurface(surface:Surface): string; - /** - * @description Adds an extrusion object to Rhino. - * @param {Extrusion} extrusion A duplicate of this extrusion is added to Rhino. - * @returns {string} A unique identifier for the object. - */ - addExtrusion(extrusion:Extrusion): string; - /** - * @description Adds a mesh object to Rhino. - * @param {Mesh} mesh A duplicate of this mesh is added to Rhino. - * @returns {string} A unique identifier for the object. - */ - addMesh(mesh:Mesh): string; - /** - * @description Adds a brep object to Rhino. - * @param {Brep} brep A duplicate of this brep is added to Rhino. - * @returns {string} A unique identifier for the object. - */ - addBrep(brep:Brep): string; - /** - * @description Duplicates the object, then adds a copy of the object to the document. - * @param {File3dmObject} item The item to duplicate and add. - * @returns {void} - */ - add(item:File3dmObject): void; - /** - * @description Gets the bounding box containing every object in this table. - * @returns {BoundingBox} The computed bounding box. - */ - getBoundingBox(): BoundingBox; - /** ... */ - deleteItem(): void; - /** ... */ - findId(): void; - } - - class File3dmPlugInData { - } - - class File3dmPlugInDataTable { - /** - * Gets the number of objects in this table. - */ - count: number; - /** ... */ - get(): void; - } - - class File3dmPostEffectTable { - /** - */ - count: any; - /** ... */ - get(): void; - /** ... */ - findIndex(): void; - /** ... */ - findId(): void; - } - - class File3dmRdkDocumentData extends File3dmPlugInData { - /** ... */ - rdkXml(): void; - } - - class File3dmRenderContentTable { - /** - */ - count: any; - /** ... */ - add(): void; - /** ... */ - get(): void; - /** ... */ - findId(): void; - } - - class File3dmSettings { - /** - * Gets or sets a Uniform Resource Locator (URL) direction for the model. - */ - modelUrl: string; - /** - * Gets or sets the model base point that is used when the file is read as an instance definition. - * This point is mapped to the origin in the instance definition. - */ - modelBasePoint: number[]; - /** - */ - earthAnchorPoint: any; - /** - * Gets or sets the model space absolute tolerance. - */ - modelAbsoluteTolerance: number; - /** - * Gets or sets the model space angle tolerance. - */ - modelAngleToleranceRadians: number; - /** - * Gets or sets the model space angle tolerance. - */ - modelAngleToleranceDegrees: number; - /** - * Gets or sets the model space relative tolerance. - */ - modelRelativeTolerance: number; - /** - * Gets or sets the page space absolute tolerance. - */ - pageAbsoluteTolerance: number; - /** - * Gets or sets the page space angle tolerance. - */ - pageAngleToleranceRadians: number; - /** - * Gets or sets the page space angle tolerance. - */ - pageAngleToleranceDegrees: number; - /** - * Gets or sets the page space relative tolerance. - */ - pageRelativeTolerance: number; - /** - * Gets or sets the model unit system, using enumeration. - */ - modelUnitSystem: UnitSystem; - /** - * Gets or sets the page unit system, using enumeration. - */ - pageUnitSystem: UnitSystem; - /** ... */ - renderSettings(): void; - } - - class File3dmShutLiningCurveTable { - /** - */ - count: any; - /** ... */ - get(): void; - /** ... */ - add(): void; - /** ... */ - findIndex(): void; - /** ... */ - findId(): void; - } - - class File3dmStringTable { - /** - * Returns the number of document strings in the 3dm file. - */ - count: number; - /** ... */ - get(): void; - /** - * @description Returns a string value at a given index. - * @param {number} i The index at which to get the value. - * @returns {string} The string value if successful. - */ - getvalue(i:number): string; - /** ... */ - set(): void; - /** ... */ - documentUserTextCount(): void; - /** - * @description Removes document strings from the 3dm file. - * @param {string} section name of section to delete. If null, all sections will be deleted. - * @param {string} entry name of entry to delete. If null, all entries will be deleted for a given section. - * @returns {void} - */ - delete(section:string,entry:string): void; - } - - class File3dmViewTable { - /** - * Gets the amount of items in the table. - */ - count: number; - /** ... */ - get(): void; - /** ... */ - set(): void; - /** - * @description Adds a - * @returns {void} - */ - add(): void; - } - - class File3dmWriteOptions { - /** - * File version. Default is major version number of this assembly version.Must be in range [2; current version].Alternatively, 0 is a placeholder for the last valid version.Rhino can read its current version, plus earlier file versions except 1.Use latest version when possible. - */ - version: number; - /** - * Include custom user data in the file. Default is true - */ - saveUserData: boolean; - } - - class FileReference { - /** - * Gets the absolute path of this file reference. - */ - fullPath: string; - /** - * Gets the relative path of this file reference. - */ - relativePath: string; - /** - * @description Returns a new file reference. This returns a new instance even if the path does not exist. - * @param {string} fullPath A full path. - * @returns {FileReference} A file reference to the specified path. - */ - static createFromFullPath(fullPath:string): FileReference; - /** - * @description Returns a new file reference. This returns a new instance even if the path does not exist. - * @param {string} fullPath A full path. This parameter cannot be null. - * @param {string} relativePath A relative path. This parameter can be null. - * @returns {FileReference} A file reference to the specified paths. - */ - static createFromFullAndRelativePaths(fullPath:string,relativePath:string): FileReference; - } - - class Font { - /** - */ - quartetName: string; - /** - * Returns Face name - */ - faceName: string; - /** - * Returns the Font PostScriptName - "Apple font name" - */ - postScriptName: string; - /** - * Returns the Font RichTextFontName used in RTF strings: - * {\\fonttbl...{\\fN RichTextFontName;}...} - */ - richTextFontName: string; - /** - */ - bold: boolean; - /** - */ - italic: boolean; - /** - */ - underlined: boolean; - /** - */ - strikeOut: boolean; - /** - */ - isEngravingFont: boolean; - /** - */ - isSymbolFont: boolean; - /** - */ - isSingleStrokeFont: boolean; - /** - */ - isSimulated: boolean; - /** - */ - pointSize: number; - /** - */ - familyName: string; - } - - class GeometryBase extends CommonObject { - /** - * Useful for switch statements that need to differentiate between - * basic object types like points, curves, surfaces, and so on. - */ - objectType: ObjectType; - /** - * true if object can be accurately modified with "squishy" transformations like - * projections, shears, and non-uniform scaling. - */ - isDeformable: boolean; - /** - * Returns true if the Brep.TryConvertBrep function will be successful for this object - */ - hasBrepForm: boolean; - /** - * @description Transforms the geometry. If the input Transform has a SimilarityType of - OrientationReversing, you may want to consider flipping the transformed - geometry after calling this function when it makes sense. For example, - you may want to call Flip() on a Brep after transforming it. - * @param {Transform} xform Transformation to apply to geometry. - * @returns {boolean} true if geometry successfully transformed. - */ - transform(xform:Transform): boolean; - /** - * @description Translates the object along the specified vector. - * @param {number[]} translationVector A moving vector. - * @returns {boolean} true if geometry successfully translated. - */ - translate(translationVector:number[]): boolean; - /** - * @description Scales the object by the specified factor. The scale is centered at the origin. - * @param {number} scaleFactor The uniform scaling factor. - * @returns {boolean} true if geometry successfully scaled. - */ - scale(scaleFactor:number): boolean; - /** - * @description Rotates the object about the specified axis. A positive rotation - angle results in a counter-clockwise rotation about the axis (right hand rule). - * @param {number} angleRadians Angle of rotation in radians. - * @param {number[]} rotationAxis Direction of the axis of rotation. - * @param {number[]} rotationCenter Point on the axis of rotation. - * @returns {boolean} true if geometry successfully rotated. - */ - rotate(angleRadians:number,rotationAxis:number[],rotationCenter:number[]): boolean; - /** - * @description Bounding box solver. Gets the world axis aligned bounding box for the geometry. - * @param {boolean} accurate If true, a physically accurate bounding box will be computed. - If not, a bounding box estimate will be computed. For some geometry types there is no - difference between the estimate and the accurate bounding box. Estimated bounding boxes - can be computed much (much) faster than accurate (or "tight") bounding boxes. - Estimated bounding boxes are always similar to or larger than accurate bounding boxes. - * @returns {BoundingBox} The bounding box of the geometry in world coordinates or BoundingBox.Empty - if not bounding box could be found. - */ - getBoundingBox(accurate:boolean): BoundingBox; - /** - * @description If possible, converts the object into a form that can be accurately modified - with "squishy" transformations like projections, shears, an non-uniform scaling. - * @returns {boolean} false if object cannot be converted to a deformable object. true if object was - already deformable or was converted into a deformable object. - */ - makeDeformable(): boolean; - /** - * @description Constructs a deep (full) copy of this object. - * @returns {GeometryBase} An object of the same type as this, with the same properties and behavior. - */ - duplicate(): GeometryBase; - } - - class GroundPlane { - /** - * Determines whether the document ground plane is enabled. - */ - enabled: boolean; - /** - * If this is off, the ground plane will not be visible when seen from below. - */ - showUnderside: boolean; - /** - * Height above world XY plane in model units. Auto-altitude is computed if enabled. - */ - altitude: number; - /** - * Determines whether the ground plane is fixed by the Altitude property, or whether it is automatically placed at the lowest point in the model. - */ - autoAltitude: boolean; - /** - * Determines whether the ground plane shows the material assigned, or whether it is transparent, but captures shadows. - */ - shadowOnly: boolean; - /** - * Id of material in material table for this ground plane. - */ - materialInstanceId: string; - /** - * Texture mapping offset in world units. - */ - textureOffset: Rhino.Vector2d; - /** - * Texture offset locked. - */ - textureOffsetLocked: boolean; - /** - * Texture size locked. - */ - textureSizeLocked: boolean; - /** - * Texture mapping single UV span size in world units. - */ - textureSize: Rhino.Vector2d; - /** - * Texture mapping rotation around world origin + offset in degrees. - */ - textureRotation: number; - } - - class Group extends CommonObject { - /** - */ - name: any; - /** - */ - id: any; - /** - */ - index: any; - } - - class Hatch extends GeometryBase { - /** - * Gets or sets the index of the pattern in the document hatch pattern table. - */ - patternIndex: number; - /** - * Gets or sets the relative rotation of the pattern. - */ - patternRotation: number; - /** - * Gets or sets the hatch pattern base point - */ - basePoint: number[]; - /** - * Gets or sets the hatch plane - */ - plane: Plane; - /** - * Gets or sets the scaling factor of the pattern. - */ - patternScale: number; - /** - * @description Scale the hatch's pattern - * @returns {void} - */ - scalePattern(): void; - } - - class InstanceDefinition extends CommonObject { - /** - */ - description: any; - /** - */ - name: any; - /** - */ - id: any; - /** - */ - sourceArchive: any; - /** - */ - updateType: any; - /** ... */ - getObjectIds(): void; - /** ... */ - isInstanceGeometryId(): void; - } - - class InstanceReference extends GeometryBase { - /** - */ - parentIdefId: any; - /** - */ - xform: any; - } - - class Intersection { - /** - * @description Intersects two lines. - * @param {Line} lineA First line for intersection. - * @param {Line} lineB Second line for intersection. - * @param {number} tolerance If tolerance > 0.0, then an intersection is reported only if the distance between the points is <= tolerance. - If tolerance <= 0.0, then the closest point between the lines is reported. - * @param {boolean} finiteSegments If true, the input lines are treated as finite segments. - If false, the input lines are treated as infinite lines. - * @returns {Array} [boolean, number, number] - * (boolean) true if a closest point can be calculated and the result passes the tolerance parameter test; otherwise false. - * (number) Parameter on lineA that is closest to LineB. - The shortest distance between the lines is the chord from lineA.PointAt(a) to lineB.PointAt(b) - * (number) Parameter on lineB that is closest to LineA. - The shortest distance between the lines is the chord from lineA.PointAt(a) to lineB.PointAt(b) - */ - static lineLine(lineA:Line,lineB:Line,tolerance:number,finiteSegments:boolean): object; - /** ... */ - static lineLineTolerance(): void; - /** - * @description Intersects a line and a plane. This function only returns true if the - intersection result is a single point (i.e. if the line is coincident with - the plane then no intersection is assumed). - * @param {Line} line Line for intersection. - * @param {Plane} plane Plane to intersect. - * @returns {Array} [boolean, number] - * (boolean) true on success, false on failure. - * (number) Parameter on line where intersection occurs. - If the parameter is not within the {0, 1} Interval then the finite segment - does not intersect the plane. - */ - static linePlane(line:Line,plane:Plane): object; - /** - * @description Intersects two planes and return the intersection line. If the planes are - parallel or coincident, no intersection is assumed. - * @param {Plane} planeA First plane for intersection. - * @param {Plane} planeB Second plane for intersection. - * @returns {Array} [boolean, Line] - * (boolean) true on success, false on failure. - * (Line) If this function returns true, - the intersectionLine parameter will return the line where the planes intersect. - */ - static planePlane(planeA:Plane,planeB:Plane): object; - /** - * @description Intersects three planes to find the single point they all share. - * @param {Plane} planeA First plane for intersection. - * @param {Plane} planeB Second plane for intersection. - * @param {Plane} planeC Third plane for intersection. - * @returns {Array} [boolean, number[]] - * (boolean) true on success, false on failure. If at least two out of the three planes - are parallel or coincident, failure is assumed. - * (number[]) Point where all three planes converge. - */ - static planePlanePlane(planeA:Plane,planeB:Plane,planeC:Plane): object; - /** - * @description Intersects a plane with a sphere using exact calculations. - * @param {Plane} plane Plane to intersect. - * @param {Sphere} sphere Sphere to intersect. - * @returns {Array} [PlaneSphereIntersection, Circle] - * (PlaneSphereIntersection) If is returned, the intersectionCircle has a radius of zero and the center point - is the point on the plane closest to the sphere. - * (Circle) Intersection result. - */ - static planeSphere(plane:Plane,sphere:Sphere): object; - /** - * @description Intersects a line with a circle using exact calculations. - * @param {Line} line Line for intersection. - * @param {Circle} circle Circle for intersection. - * @returns {Array} [LineCircleIntersection, number, number[], number, number[]] - * (LineCircleIntersection) If is returned, only t1 and point1 will have valid values. - If is returned, t2 and point2 will also be filled out. - * (number) Parameter on line for first intersection. - * (number[]) Point on circle closest to first intersection. - * (number) Parameter on line for second intersection. - * (number[]) Point on circle closest to second intersection. - */ - static lineCircle(line:Line,circle:Circle): object; - /** - * @description Intersects a line with a sphere using exact calculations. - * @param {Line} line Line for intersection. - * @param {Sphere} sphere Sphere for intersection. - * @returns {Array} [LineSphereIntersection, number[], number[]] - * (LineSphereIntersection) If is returned, the first point is the point on the line closest to the sphere and - the second point is the point on the sphere closest to the line. - If is returned, the first point is the point on the line and the second point is the - same point on the sphere. - * (number[]) First intersection point. - * (number[]) Second intersection point. - */ - static lineSphere(line:Line,sphere:Sphere): object; - /** - * @description Intersects a line with a cylinder using exact calculations. - * @param {Line} line Line for intersection. - * @param {Cylinder} cylinder Cylinder for intersection. - * @returns {Array} [LineCylinderIntersection, number[], number[]] - * (LineCylinderIntersection) If None is returned, the first point is the point on the line closest - to the cylinder and the second point is the point on the cylinder closest to - the line. - If is returned, the first point - is the point on the line and the second point is the same point on the - cylinder. - * (number[]) First intersection point. - * (number[]) Second intersection point. - */ - static lineCylinder(line:Line,cylinder:Cylinder): object; - /** - * @description Intersects two spheres using exact calculations. - * @param {Sphere} sphereA First sphere to intersect. - * @param {Sphere} sphereB Second sphere to intersect. - * @returns {Array} [SphereSphereIntersection, Circle] - * (SphereSphereIntersection) The intersection type. - * (Circle) If intersection is a point, then that point will be the center, radius 0. - */ - static sphereSphere(sphereA:Sphere,sphereB:Sphere): object; - /** - * @description Intersects an infinite line and an axis aligned bounding box. - * @param {BoundingBox} box BoundingBox to intersect. - * @param {Line} line Line for intersection. - * @param {number} tolerance If tolerance > 0.0, then the intersection is performed against a box - that has each side moved out by tolerance. - * @returns {Array} [boolean, number[]] - * (boolean) true if the line intersects the box, false if no intersection occurs. - * (number[]) The chord from line.PointAt(lineParameters.T0) to line.PointAt(lineParameters.T1) is the intersection. - */ - static lineBox(box:BoundingBox,line:Line,tolerance:number): object; - } - - class Layer extends CommonObject { - /** - * Gets or sets the name of this layer. - */ - name: string; - /** - * Gets the full path to this layer. The full path includes nesting information. - */ - fullPath: string; - /** - * Gets or sets the ID of this layer object. - * You typically do not need to assign a custom ID. - */ - id: string; - /** - * Gets the ID of the parent layer. Layers can be organized in a hierarchical structure, - * in which case this returns the parent layer ID. If the layer has no parent, - * Guid.Empty will be returned. - */ - parentLayerId: string; - /** - * Gets or sets the IGES level for this layer. - */ - igesLevel: number; - /** - * Gets or sets the display color for this layer. - */ - color: number[]; - /** - * Gets or sets the plot color for this layer. - */ - plotColor: number[]; - /** - * Gets or sets the weight of the plotting pen in millimeters. - * A weight of 0.0 indicates the "default" pen weight should be used. - * A weight of -1.0 indicates the layer should not be printed. - */ - plotWeight: number; - /** - * Gets or sets the line-type index for this layer. - */ - linetypeIndex: number; - /** - * Gets or sets the index of render material for objects on this layer that have - * MaterialSource() == MaterialFromLayer. - * A material index of -1 indicates no material has been assigned - * and the material created by the default Material constructor - * should be used. - */ - renderMaterialIndex: number; - /** - */ - visible: any; - /** - */ - locked: any; - /** - */ - expanded: any; - /** - * @description Verifies that a layer has per viewport settings. - * @param {string} viewportId If not Guid.Empty, then checks for settings for that specific viewport. - If Guid.Empty, then checks for any viewport settings. - * @returns {boolean} True if the layer has per viewport settings, false otherwise. - */ - hasPerViewportSettings(viewportId:string): boolean; - /** - * @description Deletes per viewport layer settings. - * @param {string} viewportId If not Guid.Empty, then the settings for that viewport are deleted. - If Guid.Empty, then all per viewport settings are deleted. - * @returns {void} - */ - deletePerViewportSettings(viewportId:string): void; - /** - * @description Gets the display color for this layer. - * @param {string} viewportId If not Guid.Empty, then the setting applies only to the viewport with the specified id. - * @returns {number[]} The display color. - */ - perViewportColor(viewportId:string): number[]; - /** - * @description Sets the display color for this layer. - * @param {string} viewportId If not Guid.Empty, then the setting applies only to the viewport with the specified id. - * @param {number[]} color The display color. - * @returns {void} - */ - setPerViewportColor(viewportId:string,color:number[]): void; - /** - * @description Remove any per viewport layer color setting so the layer's overall setting will be used for all viewports. - * @param {string} viewportId If not Guid.Empty, then the setting for this viewport will be deleted. - If Guid.Empty, the all per viewport layer color settings will be removed. - * @returns {void} - */ - deletePerViewportColor(viewportId:string): void; - /** - * @description The global persistent visibility setting is used for layers whose visibility can - be changed by a "parent" object. A common case is when a layer is a - child layer (ParentId is not nil). In this case, when a parent layer is - turned off, then child layers are also turned off. The persistent - visibility setting determines what happens when the parent is turned on - again. - * @returns {boolean} - */ - getPersistentVisibility(): boolean; - /** - * @description Set the global persistent visibility setting for this layer. - * @returns {void} - */ - setPersistentVisibility(): void; - /** - * @description Remove any explicit persistent visibility setting from this layer - * @returns {void} - */ - unsetPersistentVisibility(): void; - /** - * @description The persistent locking setting is used for layers that can be locked by - a "parent" object. A common case is when a layer is a child layer - (Layer.ParentI is not nil). In this case, when a parent layer is locked, - then child layers are also locked. The persistent locking setting - determines what happens when the parent is unlocked again. - * @returns {boolean} - */ - getPersistentLocking(): boolean; - /** - * @description Set the persistent locking setting for this layer - * @returns {void} - */ - setPersistentLocking(): void; - /** - * @description Remove any explicitly persistent locking settings from this layer - * @returns {void} - */ - unsetPersistentLocking(): void; - } - - class Light extends GeometryBase { - /** - * Gets or sets a value that defines if the light is turned on (true) or off (false). - */ - isEnabled: boolean; - /** - * Gets or sets a light style on this camera. - */ - lightStyle: LightStyle; - /** - * Gets a value indicating whether the light style - * is CameraPoint or WorldPoint. - */ - isPointLight: boolean; - /** - * Gets a value indicating whether the light style - * is CameraDirectional or WorldDirectional. - */ - isDirectionalLight: boolean; - /** - * Gets a value indicating whether the light style - * is CameraSpot or WorldSpot. - */ - isSpotLight: boolean; - /** - * Gets a value indicating whether the light style - * is WorldLinear. - */ - isLinearLight: boolean; - /** - * Gets a value indicating whether the light style - * is WorldRectangular. - */ - isRectangularLight: boolean; - /** - * Gets or sets the light or 3D position or location. - */ - location: number[]; - /** - * Gets or sets the vector direction of the camera. - */ - direction: number[]; - /** - * Gets a perpendicular vector to the camera direction. - */ - perpendicularDirection: number[]; - /** - * Gets or sets the light intensity. - */ - intensity: number; - /** - * Gets or sets the light power in watts (W). - */ - powerWatts: number; - /** - * Gets or sets the light power in lumens (lm). - */ - powerLumens: number; - /** - * Gets or sets the light power in candelas (cd). - */ - powerCandela: number; - /** - * Gets or sets the ambient color. - */ - ambient: number[]; - /** - * Gets or sets the diffuse color. - */ - diffuse: number[]; - /** - * Gets or sets the specular color. - */ - specular: number[]; - /** - * Gets or Sets the attenuation vector. - */ - attenuationVector: number[]; - /** - * Gets or sets the spot angle in radians. - * Ignored for non-spot lights.angle = 0 to pi/2 (0 to 90 degrees). - */ - spotAngleRadians: number; - /** - * The spot exponent varies from 0.0 to 128.0 and provides - * an exponential interface for controlling the focus or - * concentration of a spotlight (like the - * OpenGL GL_SPOT_EXPONENT parameter). The spot exponent - * and hot spot parameters are linked; changing one will - * change the other. - * A hot spot setting of 0.0 corresponds to a spot exponent of 128. - * A hot spot setting of 1.0 corresponds to a spot exponent of 0.0. - */ - spotExponent: number; - /** - * The hot spot setting runs from 0.0 to 1.0 and is used to - * provides a linear interface for controlling the focus or - * concentration of a spotlight. - * A hot spot setting of 0.0 corresponds to a spot exponent of 128. - * A hot spot setting of 1.0 corresponds to a spot exponent of 0.0. - */ - hotSpot: number; - /** - * Gets or sets the height in linear and rectangular lights. - * (ignored for non-linear/rectangular lights.) - */ - length: number[]; - /** - * Gets or sets the width in linear and rectangular lights. - * (ignored for non-linear/rectangular lights.) - */ - width: number[]; - /** - * Gets or sets the shadow intensity for the light. - */ - shadowIntensity: number; - /** - * Gets or sets the spot light name. - */ - name: string; - /** - * @description Sets the attenuation settings (ignored for "directional" and "ambient" lights). - attenuation = 1/(a0 + d*a1 + d^2*a2) where d = distance to light. - * @param {number} a0 The new constant attenuation divisor term. - * @param {number} a1 The new reverse linear attenuation divisor term. - * @param {number} a2 The new reverse quadratic attenuation divisor term. - * @returns {void} - */ - setAttenuation(a0:number,a1:number,a2:number): void; - /** - * @description Gets the attenuation settings (ignored for "directional" and "ambient" lights). - attenuation = 1/(a0 + d*a1 + d^2*a2) where d = distance to light. - * @param {number} d The distance to evaluate. - * @returns {number} 0 if a0 + d*a1 + d^2*a2 <= 0. - */ - getAttenuation(d:number): number; - /** - * @description Gets the spot light radii. - * @returns {Array} [boolean, number, number] - * (boolean) true if operation succeeded; otherwise, false. - * (number) The inner radius. This out parameter is assigned during this call. - * (number) The outer radius. This out parameter is assigned during this call. - */ - getSpotLightRadii(): object; - } - - class Line { - /** - * Start point of line segment. - */ - from: number[]; - /** - * End point of line segment. - */ - to: number[]; - /** - * Gets or sets the length of this line segment. - * Note that a negative length will invert the line segment without - * making the actual length negative. The line From point will remain fixed - * when a new Length is set. - */ - length: number; - - constructor(from: number[], to: number[]); - } - - class LinearWorkflow { - /** - */ - preProcessTexturesOn: any; - /** - */ - preProcessColorsOn: any; - /** - * Linear workflow pre-process gamma value. This is currently the same as the post-process gamma value. - */ - preProcessGamma: number; - /** - */ - preProcessGammaOn: any; - /** - * Linear workflow post-process gamma value. - */ - postProcessGamma: number; - /** - * Linear workflow post-process gamma enabled state. - */ - postProcessGammaOn: boolean; - } - - class LineCurve extends Curve { - /** - * Gets or sets the Line value inside this curve. - */ - line: Line; - - constructor(from: number[], to: number[]); - } - - class Linetype extends ModelComponent { - /** - * The name of this linetype. - */ - name: string; - /** - */ - index: any; - /** - * Total length of one repeat of the pattern. - */ - patternLength: number; - /** - * Number of segments in the pattern. - */ - segmentCount: number; - /** - * @description Gets the segment information at a index. - * @param {number} index Zero based index of the segment. - * @returns {Array} [void, number, boolean] - * (void) - * (number) The length of the segment in millimeters. - * (boolean) If the length is interpreted as a line, true is assigned during the call to this out parameter. - If the length is interpreted as a space, then false is assigned during the call to this out parameter. - */ - getSegment(index:number): object; - /** - * @description Sets the length and type of the segment at index. - * @param {number} index Zero based index of the segment. - * @param {number} length The length of the segment to be added in millimeters. - * @param {boolean} isSolid If true, the length is interpreted as a line. If false, - then the length is interpreted as a space. - * @returns {boolean} true if the operation was successful; otherwise false. - */ - setSegment(index:number,length:number,isSolid:boolean): boolean; - /** - * @description Adds a segment to the pattern. - * @param {number} length The length of the segment to be added. - * @param {boolean} isSolid If true, the length is interpreted as a line. If false, - then the length is interpreted as a space. - * @returns {number} Index of the added segment. - */ - appendSegment(length:number,isSolid:boolean): number; - /** - * @description Removes a segment in the linetype. - * @param {number} index Zero based index of the segment to remove. - * @returns {boolean} true if the segment index was removed. - */ - removeSegment(index:number): boolean; - /** ... */ - clearPattern(): void; - /** ... */ - static border(): void; - /** ... */ - static byLayer(): void; - /** ... */ - static byParent(): void; - /** ... */ - static center(): void; - /** ... */ - static continuous(): void; - /** ... */ - static dashdot(): void; - /** ... */ - static dashed(): void; - /** ... */ - static dots(): void; - /** ... */ - static hidden(): void; - } - - class Material extends ModelComponent { - /** - * The Id of the RenderPlugIn that is associated with this material. - */ - renderPlugInId: string; - /** - */ - name: string; - /** - * Gets or sets the shine factor of the material. - */ - shine: number; - /** - * Gets or sets the transparency of the material (0.0 = opaque to 1.0 = transparent) - */ - transparency: number; - /** - * Gets or sets the index of refraction of the material, generally - * >= 1.0 (speed of light in vacuum)/(speed of light in material) - */ - indexOfRefraction: number; - /** - * Gets or sets the Fresnel index of refraction of the material, - * default is 1.56 - */ - fresnelIndexOfRefraction: number; - /** - * Gets or sets the refraction glossiness. - */ - refractionGlossiness: number; - /** - * Gets or sets the reflection glossiness. - */ - reflectionGlossiness: number; - /** - * Gets or sets if Fresnel reflections are used. - */ - fresnelReflections: boolean; - /** - */ - disableLighting: boolean; - /** - * Gets or sets how reflective a material is, 0f is no reflection - * 1f is 100% reflective. - */ - reflectivity: number; - /** - * Very simple preview color function for GUIs. - */ - previewColor: number[]; - /** - */ - diffuseColor: number[]; - /** - */ - ambientColor: number[]; - /** - */ - emissionColor: number[]; - /** - */ - specularColor: number[]; - /** - */ - reflectionColor: number[]; - /** - */ - transparentColor: number[]; - /** ... */ - static compareAppearance(): void; - /** - * @description Set material to default settings. - * @returns {void} - */ - default(): void; - /** - * @description Get the texture that corresponds with the specified texture type for this material. - * @returns {Texture} - */ - getTexture(): Texture; - /** - * @returns {Texture} - */ - getBitmapTexture(): Texture; - /** ... */ - setBitmapTextureFilename(): void; - /** - * @returns {boolean} - */ - setBitmapTexture(): boolean; - /** - * @description Gets the bump texture of this material. - * @returns {Texture} A texture; or null if no bump texture has been added to this material. - */ - getBumpTexture(): Texture; - /** ... */ - setBumpTextureFilename(): void; - /** - * @returns {boolean} - */ - setBumpTexture(): boolean; - /** - * @returns {Texture} - */ - getEnvironmentTexture(): Texture; - /** ... */ - setEnvironmentTextureFilename(): void; - /** - * @returns {boolean} - */ - setEnvironmentTexture(): boolean; - /** - * @returns {Texture} - */ - getTransparencyTexture(): Texture; - /** ... */ - setTransparencyTextureFilename(): void; - /** - * @returns {boolean} - */ - setTransparencyTexture(): boolean; - /** ... */ - physicallyBased(): void; - /** - * @returns {void} - */ - toPhysicallyBased(): void; - } - - class Mesh extends GeometryBase { - /** - * Returns true if every mesh "edge" has two or more faces. - */ - isClosed: boolean; - /** - * Will return true if SetCachedTextureCoordinates has been called; - * otherwise will return false. - */ - hasCachedTextureCoordinates: boolean; - /** - * HasPrincipalCurvatures - */ - hasPrincipalCurvatures: boolean; - /** - * Number of partition information chunks stored on this mesh based - * on the last call to CreatePartitions - */ - partitionCount: number; - /** - * @description Create a mesh from a SubD control net - * @returns {Mesh} mesh representing control net on success, null on failure - */ - static createFromSubDControlNet(): Mesh; - /** ... */ - static toThreejsJSONMerged(): void; - /** - * @description Returns true if every mesh "edge" has at most two faces. - * @returns {boolean} true if the mesh is manifold, false otherwise. - */ - isManifold(): boolean; - /** ... */ - vertices(): void; - /** ... */ - topologyEdges(): void; - /** ... */ - faces(): void; - /** ... */ - normals(): void; - /** ... */ - vertexColors(): void; - /** ... */ - textureCoordinates(): void; - /** - * @description Removes all texture coordinate information from this mesh. - * @returns {void} - */ - clearTextureData(): void; - /** - * @description Removes surface parameters, curvature parameters and surface statistics from the mesh. - * @returns {void} - */ - clearSurfaceData(): void; - /** - * @description Removes topology data, forcing all topology information to be recomputed. - * @returns {void} - */ - destroyTopology(): void; - /** - * @description Destroys the mesh vertex access tree. - * @returns {void} - */ - destroyTree(): void; - /** - * @description Destroys mesh partition. - * @returns {void} - */ - destroyPartition(): void; - /** - * @description Set texture coordinates using given mapping and applying given transform. - Set lazy to false to generate texture coordinates right away. - * @param {TextureMapping} tm Texture mapping - * @param {Transform} xf Transform to apply to the texture mapping - * @param {boolean} lazy Whether to generate lazily (true) or right away (false) - * @returns {void} - */ - setTextureCoordinates(tm:TextureMapping,xf:Transform,lazy:boolean): void; - /** - * @description Removes any unreferenced objects from arrays, re-indexes as needed - and shrinks arrays to minimum required size. - * @returns {boolean} true on success, false on failure. - */ - compact(): boolean; - /** - * @description Appends a copy of another mesh to this one and updates indices of appended mesh parts. - * @param {Mesh} other Mesh to append to this one. - * @returns {void} - */ - append(other:Mesh): void; - /** - * @description In ancient times (or modern smart phone times), some rendering engines - were only able to process small batches of triangles and the - CreatePartitions() function was provided to partition the mesh into - subsets of vertices and faces that those rendering engines could handle. - * @returns {boolean} true on success - */ - createPartitions(): boolean; - /** ... */ - toThreejsJSON(): void; - /** ... */ - toThreejsJSONRotate(): void; - /** ... */ - static createFromThreejsJSON(): void; - } - - class MeshFaceList { - /** - * Gets or sets the number of mesh faces. When getting this can includes invalid faces. - */ - count: number; - /** - * Gets the number of faces that are valid quads (4 corners). - */ - quadCount: number; - /** - * Gets the number of faces that are valid triangles (3 corners). - */ - triangleCount: number; - /** - * Gets or sets the total number of mesh triangles and quads the internal data structure can hold without resizing. - */ - capacity: number; - /** ... */ - get(): void; - /** - * @description Gets the 3D location of the vertices forming a face. - * @param {number} faceIndex A face index. - * @returns {Array} [boolean, Point3f, Point3f, Point3f, Point3f] - * (boolean) true if the operation succeeded, otherwise false. - * (Point3f) A first point. This out argument is assigned during the call. - * (Point3f) A second point. This out argument is assigned during the call. - * (Point3f) A third point. This out argument is assigned during the call. - * (Point3f) A fourth point. This out argument is assigned during the call. - */ - getFaceVertices(faceIndex:number): object; - /** - * @description Gets the center point of a face. - For a triangular face, this is the centroid or barycenter.For a quad, this is the average of four comer points. - * @param {number} faceIndex A face index. - * @returns {number[]} The center point. - */ - getFaceCenter(faceIndex:number): number[]; - /** - * @description Clears the Face list on the mesh. - * @returns {void} - */ - clear(): void; - /** - * @description Releases all memory allocated to store faces. The list capacity will be 0 after this call. - Subsequent calls can add new items. - * @returns {void} - */ - destroy(): void; - /** ... */ - addTriFace(): void; - /** ... */ - addQuadFace(): void; - /** ... */ - setTriFace(): void; - /** ... */ - setQuadFace(): void; - /** - * @description Splits all quads along the short diagonal. - * @returns {boolean} true on success, false on failure. - */ - convertQuadsToTriangles(): boolean; - /** - * @description Splits non-planar quads into two triangles based on given parameters. - * @param {number} planarTolerance If planarTolerance >= 0, then a quad is split if its vertices - are not coplanar. - If both planarTolerance = Rhino.RhinoMath.UnsetValue and - angleToleranceRadians >= 0.0, then the planarity test is skipped. - * @param {number} angleToleranceRadians If angleToleranceRadians >= 0.0, then a quad is split if the - angle between opposite corner normals is > angleToleranceRadians. - The corner normal is the normal to the triangle formed by two - adjacent edges and the diagonal connecting their endpoints. - A quad has four corner normals. - If both angleToleranceRadians = Rhino.RhinoMath.UnsetValue and planarTolerance >= 0.0, - then the corner normal angle test is skipped. - * @param {number} splitMethod 0 default - Currently divides along the short diagonal. This may be - changed as better methods are found or preferences change. - By passing zero, you let the developers of this code - decide what's best for you over time. - 1 divide along the short diagonal - 2 divide along the long diagonal - 3 minimize resulting area - 4 maximize resulting area - 5 minimize angle between triangle normals - 6 maximize angle between triangle normals - * @returns {number} Number of quads that were converted to triangles. - */ - convertNonPlanarQuadsToTriangles(planarTolerance:number,angleToleranceRadians:number,splitMethod:number): number; - /** - * @description Joins adjacent triangles into quads if the resulting quad is 'nice'. - * @param {number} angleToleranceRadians Used to compare adjacent triangles' face normals. For two triangles - to be considered, the angle between their face normals has to - be <= angleToleranceRadians. When in doubt use RhinoMath.PI/90.0 (2 degrees). - * @param {number} minimumDiagonalLengthRatio ( <= 1.0) For two triangles to be considered the ratio of the - resulting quad's diagonals - (length of the shortest diagonal)/(length of longest diagonal). - has to be >= minimumDiagonalLengthRatio. When in doubt us .875. - * @returns {boolean} true on success, false on failure. - */ - convertTrianglesToQuads(angleToleranceRadians:number,minimumDiagonalLengthRatio:number): boolean; - /** - * @description Attempts to removes degenerate faces from the mesh. - Degenerate faces are faces that contains such a combination of indices, - that their final shape collapsed in a line or point.Before returning, this method also attempts to repair faces by juggling - vertex indices. - * @returns {number} The number of degenerate faces that were removed. - */ - cullDegenerateFaces(): number; - /** - * @description Gets a value indicating whether a face is hidden. - A face is hidden if, and only if, at least one of its vertices is hidden. - * @param {number} faceIndex A face index. - * @returns {boolean} true if hidden, false if fully visible. - */ - isHidden(faceIndex:number): boolean; - /** - * @description Returns true if at least one of the face edges are not topologically - connected to any other faces. - * @param {number} faceIndex A face index. - * @returns {boolean} true if that face makes the mesh open, otherwise false. - */ - hasNakedEdges(faceIndex:number): boolean; - } - - class MeshingParameters { - /** - * Gets or sets how and if textures will be packed. - */ - textureRange: number; - /** - * Gets or sets whether or not the mesh is allowed to have jagged seams. - * When this flag is set to true, meshes on either side of a Brep Edge will not match up. - */ - jaggedSeams: boolean; - /** - * Gets or sets a value indicating whether or not the sampling grid can be refined - * when certain tolerances are not met. - */ - refineGrid: boolean; - /** - * Gets or sets a value indicating whether or not planar areas are allowed - * to be meshed in a simplified manner. - */ - simplePlanes: boolean; - /** - * Gets or sets a value indicating whether or not surface curvature - * data will be embedded in the mesh. - */ - computeCurvature: boolean; - /** - * Gets or sets a value indicating whether or not to post process non-closed meshes - * that should be closed. If the Brep being meshed is closed, JaggedSeams = false, - * and ClosedObjectPostProcess = true, and the resulting mesh is not closed, then a - * post meshing process is applied to find and close gaps in the mesh. Typically the - * resulting mesh is not closed because the input Brep has a geometric flaw, like - * loops in trimming curve. - */ - closedObjectPostProcess: boolean; - /** - * Gets or sets the minimum number of grid quads in the initial sampling grid. - */ - gridMinCount: number; - /** - * Gets or sets the maximum number of grid quads in the initial sampling grid. - */ - gridMaxCount: number; - /** - * Gets or sets the maximum allowed angle difference (in radians) - * for a single sampling quad. The angle pertains to the surface normals. - */ - gridAngle: number; - /** - * Gets or sets the maximum allowed aspect ratio of sampling quads. - */ - gridAspectRatio: number; - /** - * Gets or sets the grid amplification factor. - * Values lower than 1.0 will decrease the number of initial quads, - * values higher than 1.0 will increase the number of initial quads. - */ - gridAmplification: number; - /** - * Gets or sets the maximum allowed edge deviation. - * This tolerance is measured between the center of the mesh edge and the surface. - */ - tolerance: number; - /** - * Gets or sets the minimum tolerance. - */ - minimumTolerance: number; - /** - * Gets or sets the relative tolerance. - */ - relativeTolerance: number; - /** - * Gets or sets the minimum allowed mesh edge length. - */ - minimumEdgeLength: number; - /** - * Gets or sets the maximum allowed mesh edge length. - */ - maximumEdgeLength: number; - /** - * Gets or sets the mesh parameter refine angle in radians. - */ - refineAngle: number; - - constructor(density: number); - - constructor(density: number, minimumEdgeLength: number); - /** ... */ - static default(): void; - /** ... */ - static fastRenderMesh(): void; - /** ... */ - static qualityRenderMesh(): void; - /** ... */ - static defaultAnalysisMesh(): void; - /** ... */ - toJSON(): void; - /** ... */ - encode(): void; - /** ... */ - static decode(): void; - } - - class MeshNormalList { - /** - */ - count: any; - /** ... */ - get(): void; - /** ... */ - set(): void; - /** ... */ - clear(): void; - /** ... */ - destroy(): void; - /** ... */ - add(): void; - /** ... */ - computeNormals(): void; - /** ... */ - unitizeNormals(): void; - /** ... */ - flip(): void; - } - - class MeshTextureCoordinateList { - /** - * Gets or sets the number of texture coordinates. - */ - count: number; - /** ... */ - get(): void; - /** ... */ - set(): void; - /** - * @description Adds a new texture coordinate to the end of the Texture list. - * @param {number} s S component of new texture coordinate. - * @param {number} t T component of new texture coordinate. - * @returns {number} The index of the newly added texture coordinate. - */ - add(s:number,t:number): number; - } - - class MeshTopologyEdgeList { - /** - * Gets the amount of edges in this list. - */ - count: number; - /** - * @description Gets the 3d line along an edge. - * @param {number} topologyEdgeIndex The topology edge index. - * @returns {Line} Line along edge. If input is not valid, an Invalid Line is returned. - */ - edgeLine(topologyEdgeIndex:number): Line; - } - - class MeshVertexColorList { - /** - * Gets or sets the number of mesh colors. - */ - count: number; - /** - * Gets or sets the total number of vertex colors the internal data structure can hold without resizing. - */ - capacity: number; - /** ... */ - get(): void; - /** ... */ - set(): void; - /** - * @description Clears the vertex color list on the mesh. - * @returns {void} - */ - clear(): void; - /** - * @description Adds a new vertex color to the end of the color list. - * @param {number} red Red component of color, must be in the 0~255 range. - * @param {number} green Green component of color, must be in the 0~255 range. - * @param {number} blue Blue component of color, must be in the 0~255 range. - * @returns {number} The index of the newly added color. - */ - add(red:number,green:number,blue:number): number; - } - - class MeshVertexList { - /** - * Gets or sets the number of mesh vertices. - */ - count: number; - /** - * Set to true if the vertices should be stored in double precision - */ - useDoublePrecisionVertices: boolean; - /** ... */ - setCount(): void; - /** ... */ - get(): void; - /** ... */ - set(): void; - /** - * @description Clears the Vertex list on the mesh. - * @returns {void} - */ - clear(): void; - /** - * @description Releases all memory allocated to store faces. The list capacity will be 0 after this call. - Subsequent calls can add new items. - * @returns {void} - */ - destroy(): void; - /** - * @description Adds a new vertex to the end of the Vertex list. - * @param {number} x X component of new vertex coordinate. - * @param {number} y Y component of new vertex coordinate. - * @param {number} z Z component of new vertex coordinate. - * @returns {number} The index of the newly added vertex. - */ - add(x:number,y:number,z:number): number; - /** - * @description Gets a value indicating whether or not a vertex is hidden. - * @param {number} vertexIndex Index of vertex to query. - * @returns {boolean} true if the vertex is hidden, false if it is not. - */ - isHidden(vertexIndex:number): boolean; - /** - * @description Hides the vertex at the given index. - * @param {number} vertexIndex Index of vertex to hide. - * @returns {void} - */ - hide(vertexIndex:number): void; - /** - * @description Shows the vertex at the given index. - * @param {number} vertexIndex Index of vertex to show. - * @returns {void} - */ - show(vertexIndex:number): void; - /** - * @description Hides all vertices in the mesh. - * @returns {void} - */ - hideAll(): void; - /** - * @description Shows all vertices in the mesh. - * @returns {void} - */ - showAll(): void; - /** - * @description Removes all vertices that are currently not used by the Face list. - * @returns {number} The number of unused vertices that were removed. - */ - cullUnused(): number; - /** - * @description Merges identical vertices. - * @param {boolean} ignoreNormals If true, vertex normals will not be taken into consideration when comparing vertices. - * @param {boolean} ignoreAdditional If true, texture coordinates, colors, and principal curvatures - will not be taken into consideration when comparing vertices. - * @returns {boolean} true if the mesh is changed, in which case the mesh will have fewer vertices than before. - */ - combineIdentical(ignoreNormals:boolean,ignoreAdditional:boolean): boolean; - } - - class ModelComponent extends CommonObject { - /** - * True if this model component is a system constant. - * An incomplete list of system constant model components is below:ON_ModelComponent::Unset - * ON_InstanceDefinition::Empty - * ON_Linetype::UnsetON_Linetype::ContinuousON_Linetype::ByLayerON_Linetype::ByParent - * ON_Layer::UnsetON_Layer::Default - * ON_TextStyle::UnsetON_TextStyle::DefaultON_TextStyle::ByLayerON_TextStyle::ByParent - * ON_DimStyle::UnsetON_DimStyle::DefaultON_DimStyle::DefaultInchDecimalON_DimStyle::DefaultInchFractionalON_DimStyle::DefaultFootInchArchitectureON_DimStyle::DefaultMillimeterSmallON_DimStyle::DefaultMillimeterLargeON_DimStyle::DefaultMillimeterArchitecture - */ - isSystemComponent: boolean; - /** - * Gets or sets the ID of the current instance. - */ - id: string; - /** - * @description Increments the Cyclic Redundancy Check value by this instance. - * @param {number} currentRemainder The current remainder value. - * @returns {number} The updated remainder value. - */ - dataCRC(currentRemainder:number): number; - /** - * @description Resets the HasId property of the model component to false, if possible. - * @returns {void} - */ - clearId(): void; - } - - class NurbsCurve extends Curve { - /** - * Gets the order of the curve. Order = Degree + 1. - */ - order: number; - /** - * Gets a value indicating whether or not the curve is rational. - * Rational curves have control-points with custom weights. - */ - isRational: boolean; - /** - * Returns true if the NURBS curve has Bezier spans (all distinct knots have multiplicity = degree) - */ - hasBezierSpans: boolean; - - constructor(degree: number, pointCount: number); - - constructor(dimension: number, rational: boolean, order: number, pointCount: number); - /** - * @description Gets a non-rational, degree 1 NURBS curve representation of the line. - * @returns {NurbsCurve} Curve on success, null on failure. - */ - static createFromLine(): NurbsCurve; - /** - * @description Gets a rational degree 2 NURBS curve representation - of the arc. Note that the parameterization of NURBS curve - does not match arc's transcendental parameterization. - * @returns {NurbsCurve} Curve on success, null on failure. - */ - static createFromArc(): NurbsCurve; - /** - * @description Gets a rational degree 2 NURBS curve representation - of the circle. Note that the parameterization of NURBS curve - does not match circle's transcendental parameterization. - Use GetRadianFromNurbFormParameter() and - GetParameterFromRadian() to convert between the NURBS curve - parameter and the transcendental parameter. - * @returns {NurbsCurve} Curve on success, null on failure. - */ - static createFromCircle(): NurbsCurve; - /** - * @description Gets a rational degree 2 NURBS curve representation of the ellipse. - Note that the parameterization of the NURBS curve does not match - with the transcendental parameterization of the ellipsis. - * @returns {NurbsCurve} A NURBS curve representation of this ellipse or null if no such representation could be made. - */ - static createFromEllipse(): NurbsCurve; - /** - * @description Constructs a 3D NURBS curve from a list of control points. - * @param {boolean} periodic If true, create a periodic uniform curve. If false, create a clamped uniform curve. - * @param {number} degree (>=1) degree=order-1. - * @param {Point3dList} points control vertex locations. - * @returns {NurbsCurve} new NURBS curve on success - null on error. - */ - static create(periodic:boolean,degree:number,points:Point3dList): NurbsCurve; - /** - * @description Increase the degree of this curve. - * @param {number} desiredDegree The desired degree. - Degrees should be number between and including 1 and 11. - * @returns {boolean} true on success, false on failure. - */ - increaseDegree(desiredDegree:number): boolean; - /** - * @description Clamps ends and adds knots so the NURBS curve has Bezier spans - (all distinct knots have multiplicity = degree). - * @param {boolean} setEndWeightsToOne If true and the first or last weight is not one, then the first and - last spans are re-parameterized so that the end weights are one. - * @returns {boolean} true on success, false on failure. - */ - makePiecewiseBezier(setEndWeightsToOne:boolean): boolean; - /** - * @description Use a linear fractional transformation to re-parameterize the NURBS curve. - This does not change the curve's domain. - * @param {number} c re-parameterization constant (generally speaking, c should be > 0). The - control points and knots are adjusted so that - output_nurbs(t) = input_nurbs(lambda(t)), where lambda(t) = c*t/( (c-1)*t + 1 ). - Note that lambda(0) = 0, lambda(1) = 1, lambda'(t) > 0, - lambda'(0) = c and lambda'(1) = 1/c. - * @returns {boolean} true if successful. - */ - reparameterize(c:number): boolean; - /** - * @description Gets the greville (edit point) parameter that belongs - to the control point at the specified index. - * @param {number} index Index of Greville (Edit) point. - * @returns {number} - */ - grevilleParameter(index:number): number; - /** - * @description Gets the Greville parameter that belongs - to the control point at the specified index. - * @param {number} index Index of Greville point. - * @returns {number[]} - */ - grevillePoint(index:number): number[]; - /** - * @description Converts a span of the NURBS curve into a Bezier. - * @param {number} spanIndex The span index, where (0 <= spanIndex <= Points.Count - Order). - * @returns {BezierCurve} Bezier curve if successful, null otherwise. - */ - convertSpanToBezier(spanIndex:number): BezierCurve; - /** ... */ - points(): void; - /** ... */ - knots(): void; - } - - class NurbsCurveKnotList { - /** - * Total number of knots in this curve. - */ - count: number; - /** - * Gets a value indicating whether or not the knot vector is clamped at the start of the curve. - * Clamped curves start at the first control-point. This requires fully multiple knots. - */ - isClampedStart: boolean; - /** - * Gets a value indicating whether or not the knot vector is clamped at the end of the curve. - * Clamped curves are coincident with the first and last control-point. This requires fully multiple knots. - */ - isClampedEnd: boolean; - /** ... */ - get(): void; - /** ... */ - set(): void; - /** ... */ - toList(): void; - /** - * @description Inserts a knot and update control point locations. - Does not change parameterization or locus of curve. - * @param {number} value Knot value to insert. - * @returns {boolean} true on success, false on failure. - */ - insertKnot(value:number): boolean; - /** - * @description Get knot multiplicity. - * @param {number} index Index of knot to query. - * @returns {number} The multiplicity (valence) of the knot. - */ - knotMultiplicity(index:number): number; - /** - * @description Compute a clamped, uniform knot vector based on the current - degree and control point count. Does not change values of control - vertices. - * @param {number} knotSpacing Spacing of subsequent knots. - * @returns {boolean} true on success, false on failure. - */ - createUniformKnots(knotSpacing:number): boolean; - /** - * @description Compute a clamped, uniform, periodic knot vector based on the current - degree and control point count. Does not change values of control - vertices. - * @param {number} knotSpacing Spacing of subsequent knots. - * @returns {boolean} true on success, false on failure. - */ - createPeriodicKnots(knotSpacing:number): boolean; - /** - * @description Computes the knots that are superfluous because they are not used in NURBs evaluation. - These make it appear so that the first and last curve spans are different from interior spans. - http://wiki.mcneel.com/developer/onsuperfluousknot - * @param {boolean} start true if the query targets the first knot. Otherwise, the last knot. - * @returns {number} A component. - */ - superfluousKnot(start:boolean): number; - } - - class NurbsCurvePointList { - /** - * Gets the number of control points in this curve. - */ - count: number; - /** - * Gets the length of the polyline connecting all control points. - */ - controlPolygonLength: number; - /** ... */ - get(): void; - /** ... */ - set(): void; - /** - * @description Use a combination of scaling and reparameterization to change the end weights to the specified values. - * @param {number} w0 Weight for first control point. - * @param {number} w1 Weight for last control point. - * @returns {boolean} true on success, false on failure. - */ - changeEndWeights(w0:number,w1:number): boolean; - /** - * @description Converts the curve to a Rational NURBS curve. Rational NURBS curves have weighted control points. - * @returns {boolean} true on success, false on failure. - */ - makeRational(): boolean; - /** - * @description Converts the curve to a Non-rational NURBS curve. Non-rational curves have unweighted control points. - * @returns {boolean} true on success, false on failure. - */ - makeNonRational(): boolean; - } - - class NurbsSurface extends Surface { - /** - * Gets a value indicating whether or not the NURBS surface is rational. - */ - isRational: boolean; - /** - * Gets the order in the U direction. - */ - orderU: number; - /** - * Gets the order in the V direction. - */ - orderV: number; - /** - * @description Constructs a new NURBS surface with internal uninitialized arrays. - * @param {number} dimension The number of dimensions.>= 1. This value is usually 3. - * @param {boolean} isRational true to make a rational NURBS. - * @param {number} order0 The order in U direction.>= 2. - * @param {number} order1 The order in V direction.>= 2. - * @param {number} controlPointCount0 Control point count in U direction.>= order0. - * @param {number} controlPointCount1 Control point count in V direction.>= order1. - * @returns {NurbsSurface} A new NURBS surface, or null on error. - */ - static create(dimension:number,isRational:boolean,order0:number,order1:number,controlPointCount0:number,controlPointCount1:number): NurbsSurface; - /** - * @description Constructs a new NURBS surfaces from cone data. - * @param {Cone} cone A cone value. - * @returns {NurbsSurface} A new NURBS surface, or null on error. - */ - static createFromCone(cone:Cone): NurbsSurface; - /** - * @description Constructs a new NURBS surfaces from sphere data. - * @param {Sphere} sphere A sphere value. - * @returns {NurbsSurface} A new NURBS surface, or null on error. - */ - static createFromSphere(sphere:Sphere): NurbsSurface; - /** - * @description Constructs a new NURBS surfaces from cylinder data. - * @param {Cylinder} cylinder A cylinder value. - * @returns {NurbsSurface} A new NURBS surface, or null on error. - */ - static createFromCylinder(cylinder:Cylinder): NurbsSurface; - /** - * @description Constructs a ruled surface between two curves. Curves must share the same knot-vector. - * @param {Curve} curveA First curve. - * @param {Curve} curveB Second curve. - * @returns {NurbsSurface} A ruled surface on success or null on failure. - */ - static createRuledSurface(curveA:Curve,curveB:Curve): NurbsSurface; - /** - * @description Makes this surface rational. - * @returns {boolean} true if the operation succeeded; otherwise, false. - */ - makeRational(): boolean; - /** - * @description Makes this surface non-rational. - * @returns {boolean} true if the operation succeeded; otherwise, false. - */ - makeNonRational(): boolean; - /** - * @description Increase the degree of this surface in U direction. - * @param {number} desiredDegree The desired degree. - Degrees should be number between and including 1 and 11. - * @returns {boolean} true on success, false on failure. - */ - increaseDegreeU(desiredDegree:number): boolean; - /** - * @description Increase the degree of this surface in V direction. - * @param {number} desiredDegree The desired degree. - Degrees should be number between and including 1 and 11. - * @returns {boolean} true on success, false on failure. - */ - increaseDegreeV(desiredDegree:number): boolean; - /** ... */ - knotsU(): void; - /** ... */ - knotsV(): void; - /** ... */ - points(): void; - } - - class NurbsSurfaceKnotList { - /** - * Gets the total number of knots in this curve. - */ - count: number; - /** - */ - isClampedStart: any; - /** - */ - isClampedEnd: any; - /** ... */ - get(): void; - /** ... */ - set(): void; - /** ... */ - toList(): void; - /** - * @description Inserts a knot and update control point locations. - Does not change parameterization or locus of curve. - * @param {number} value Knot value to insert. - * @returns {boolean} true on success, false on failure. - */ - insertKnot(value:number): boolean; - /** - * @description Get knot multiplicity. - * @param {number} index Index of knot to query. - * @returns {number} The multiplicity (valence) of the knot. - */ - knotMultiplicity(index:number): number; - /** - * @description Compute a clamped, uniform knot vector based on the current - degree and control point count. Does not change values of control - vertices. - * @param {number} knotSpacing Spacing of subsequent knots. - * @returns {boolean} true on success, false on failure. - */ - createUniformKnots(knotSpacing:number): boolean; - /** - * @description Compute a clamped, uniform, periodic knot vector based on the current - degree and control point count. Does not change values of control - vertices. - * @param {number} knotSpacing Spacing of subsequent knots. - * @returns {boolean} true on success, false on failure. - */ - createPeriodicKnots(knotSpacing:number): boolean; - /** - * @description Computes the knots that are superfluous because they are not used in NURBs evaluation. - These make it appear so that the first and last surface spans are different from interior spans. - http://wiki.mcneel.com/developer/onsuperfluousknot - * @param {boolean} start true if the query targets the first knot. Otherwise, the last knot. - * @returns {number} A component. - */ - superfluousKnot(start:boolean): number; - } - - class NurbsSurfacePointList { - /** - */ - count: any; - /** - * Gets the number of control points in the U direction of this surface. - */ - countU: number; - /** - * Gets the number of control points in the V direction of this surface. - */ - countV: number; - /** ... */ - get(): void; - /** - * @description Gets a world 3-D, or Euclidean, control point at the given (u, v) index. - The 4-D representation is (x, y, z, 1.0). - * @param {number} u Index of control point in the surface U direction. - * @param {number} v Index of control point in the surface V direction. - * @returns {Array} [boolean, number[]] - * (boolean) true on success, false on failure. - * (number[]) Coordinate of control point. - */ - getPoint(u:number,v:number): object; - /** ... */ - set(): void; - /** ... */ - makeRational(): void; - /** ... */ - makeNonRational(): void; - } - - class ObjectAttributes extends CommonObject { - /** - * An object must be in one of three modes: normal, locked or hidden. - * If an object is in normal mode, then the object's layer controls visibility - * and selectability. If an object is locked, then the object's layer controls - * visibility by the object cannot be selected. If the object is hidden, it is - * not visible and it cannot be selected. - */ - mode: ObjectMode; - /** - * Use this query to determine if an object is part of an instance definition. - */ - isInstanceDefinitionObject: boolean; - /** - * Gets or sets an object's visibility. - */ - visible: boolean; - /** - * Gets or sets an object optional text name. - * More than one object in a model can have the same name and - * some objects may have no name. - */ - name: string; - /** - * Gets or sets an object's casts shadows property, or whether or not an object casts shadows on other objects and a ground plane. - */ - castsShadows: boolean; - /** - * Gets or sets an object's receives shadows property, or whether or not an object receives shadows from other objects. - */ - receivesShadows: boolean; - /** - * The Linetype used to display an object is specified in one of two ways. - * If LinetypeSource is ON::linetype_from_layer, then the object's layer ON_Layer::Linetype() is used. - * If LinetypeSource is ON::linetype_from_object, then value of m_linetype is used. - */ - linetypeSource: ObjectLinetypeSource; - /** - * The color used to display an object is specified in one of three ways. - * If ColorSource is ON::color_from_layer, then the object's layer ON_Layer::Color() is used. - * If ColorSource is ON::color_from_object, then value of m_color is used. - * If ColorSource is ON::color_from_material, then the diffuse color of the object's - * render material is used. See ON_3dmObjectAttributes::MaterialSource() to - * determine where to get the definition of the object's render material. - */ - colorSource: ObjectColorSource; - /** - * The color used to plot an object on paper is specified in one of three ways. - * If PlotColorSource is ON::plot_color_from_layer, then the object's layer ON_Layer::PlotColor() is used. - * If PlotColorSource is ON::plot_color_from_object, then value of PlotColor() is used. - */ - plotColorSource: ObjectPlotColorSource; - /** - */ - plotWeightSource: ObjectPlotWeightSource; - /** - */ - id: any; - /** - * Objects may have an URL. There are no restrictions on what value this - * URL may have. As an example, if the object came from a commercial part - * library, the URL might point to the definition of that part. - */ - url: string; - /** - * Gets or sets an associated layer index. - * Layer definitions in an OpenNURBS model are stored in a layer table. - * The layer table is conceptually an array of ON_Layer classes. Every - * OpenNURBS object in a model is on some layer. The object's layer - * is specified by zero based indices into the ON_Layer array. - */ - layerIndex: number; - /** - * Gets or sets the material index. - * If you want something simple and fast, set the index of - * the rendering material. - */ - materialIndex: number; - /** - * Determines if the simple material should come from the object or from it's layer. - * High quality rendering plug-ins should use m_rendering_attributes. - */ - materialSource: ObjectMaterialSource; - /** - * If ON::color_from_object == ColorSource, then color is the object's display color. - */ - objectColor: number[]; - /** - * If plot_color_from_object == PlotColorSource, then PlotColor is the object's plotting color. - */ - plotColor: number[]; - /** - * Display order used to force objects to be drawn on top or behind each other. - * Larger numbers draw on top of smaller numbers. - * 0 = draw object in standard depth buffered order<0 = draw object behind "normal" draw order objects>0 = draw object on top of "normal" draw order objects - */ - displayOrder: number; - /** - * Plot weight in millimeters. - * =0.0 means use the default width - * <0.0 means don't plot (visible for screen display, but does not show on plot) - */ - plotWeight: number; - /** - * Used to indicate an object has a decoration (like an arrowhead on a curve) - */ - objectDecoration: ObjectDecoration; - /** - * When a surface object is displayed in wireframe, this controls - * how many isoparametric wires are used. - * value number of isoparametric wires - * -1 boundary wires (off) - * 0 boundary and knot wires - * 1 boundary and knot wires and, if there are no interior knots, a single interior wire. - * N>=2 boundary and knot wires and (N+1) interior wires. - */ - wireDensity: number; - /** - * If ViewportId is nil, the object is active in all viewports. If ViewportId is not nil, then - * this object is only active in a specific view. This field is primarily used to assign page - * space objects to a specific page, but it can also be used to restrict model space to a - * specific view. - */ - viewportId: string; - /** - */ - activeSpace: any; - /** - * number of groups object belongs to. - */ - groupCount: number; - /** - * @description Apply a transformation. - * @param {Transform} xform The transformation. - * @returns {boolean} true if successful, false otherwise. - */ - transform(xform:Transform): boolean; - /** - * @description Determines if an object has a display mode override for a given viewport. - * @param {string} viewportId Id of a Rhino Viewport. - * @returns {boolean} true if the object has a display mode override for the viewport; otherwise, false. - */ - hasDisplayModeOverride(viewportId:string): boolean; - /** ... */ - drawColor(): void; - /** ... */ - decals(): void; - /** ... */ - meshModifiers(): void; - /** - * @description Returns an array of GroupCount group indices. If GroupCount is zero, then GetGroupList() returns null. - * @returns {number[]} An array of group indices. null might be returned in place of an empty array. - */ - getGroupList(): number[]; - /** - * @description Adds object to the group with specified index by appending index to - group list. - If the object is already in group, nothing is changed. - * @param {number} groupIndex The index that will be added. - * @returns {void} - */ - addToGroup(groupIndex:number): void; - /** - * @description removes object from the group with specified index. - If the object is not in the group, nothing is changed. - * @param {number} groupIndex The index that will be removed. - * @returns {void} - */ - removeFromGroup(groupIndex:number): void; - /** - * @description Removes object from all groups. - * @returns {void} - */ - removeFromAllGroups(): void; - } - - class PhysicallyBasedMaterial { - /** - */ - supported: any; - /** - */ - subsurface: number; - /** - */ - subsurfaceScatteringRadius: number; - /** - */ - metallic: number; - /** - */ - specular: number; - /** - */ - reflectiveIOR: number; - /** - */ - specularTint: number; - /** - */ - roughness: number; - /** - */ - anisotropic: number; - /** - */ - anisotropicRotation: number; - /** - */ - sheen: number; - /** - */ - sheenTint: number; - /** - */ - clearcoat: number; - /** - */ - clearcoatRoughness: number; - /** - */ - opacityIOR: number; - /** - */ - opacity: number; - /** - */ - opacityRoughness: number; - /** - */ - baseColor: Rhino.Display.Color4f; - /** - */ - emissionColor: any; - /** - */ - subsurfaceScatteringColor: Rhino.Display.Color4f; - } - - class Plane { - /** ... */ - static worldXY(): void; - } - - class PlaneSurface extends Surface { - } - - class Point extends GeometryBase { - /** - * Gets or sets the location (position) of this point. - */ - location: number[]; - - constructor(location: number[]); - } - - class Point3d { - /** - * @description Transforms the present point in place. The transformation matrix acts on the left of the point. i.e., - result = transformation*point - * @param {Transform} xform Transformation to apply. - * @returns {void} - */ - static transform(xform:Transform): void; - } - - class Point3dList { - /** - */ - capacity: any; - /** - */ - count: any; - /** - * Even though this is a property, it is not a "fast" calculation. Every point is - * evaluated in order to get the bounding box of the list. - */ - boundingBox: BoundingBox; - - constructor(initialCapacity: number); - /** ... */ - get(): void; - /** ... */ - set(): void; - /** ... */ - clear(): void; - /** ... */ - insert(): void; - /** ... */ - removeAt(): void; - /** - * @description Adds a Point3d to the end of the list with given x,y,z coordinates. - * @param {number} x The X coordinate. - * @param {number} y The Y coordinate. - * @param {number} z The Z coordinate. - * @returns {void} - */ - add(x:number,y:number,z:number): void; - /** - * @description Applies a transform to all the points in the list. - * @param {Transform} xform Transform to apply. - * @returns {void} - */ - transform(xform:Transform): void; - /** - * @description Set all the X values for the points to a single value - * @returns {void} - */ - setAllX(): void; - /** - * @description Set all the Y values for the points to a single value - * @returns {void} - */ - setAllY(): void; - /** - * @description Set all the Z values for the points to a single value - * @returns {void} - */ - setAllZ(): void; - /** ... */ - append(): void; - } - - class PointCloud extends GeometryBase { - /** - * Gets the number of points in this point cloud. - */ - count: number; - /** - * Gets the number of points that have their Hidden flag set. - */ - hiddenPointCount: number; - /** - * Gets a value indicating whether or not the points in this - * point cloud have colors assigned to them. - */ - containsColors: boolean; - /** - * Gets a value indicating whether or not the points in this - * point cloud have normals assigned to them. - */ - containsNormals: boolean; - /** - */ - containsValues: any; - /** - * Gets a value indicating whether or not the points in this - * point cloud have hidden flags assigned to them. - */ - containsHiddenFlags: boolean; - /** - * @description Destroys the color information in this point cloud. - * @returns {void} - */ - clearColors(): void; - /** - * @description Destroys the normal vector information in this point cloud. - * @returns {void} - */ - clearNormals(): void; - /** - * @description Destroys the hidden flag information in this point cloud. - * @returns {void} - */ - clearHiddenFlags(): void; - /** - * @description Appends a new PointCloudItem to the end of this point cloud. - * @returns {PointCloudItem} The newly appended item. - */ - appendNew(): PointCloudItem; - /** - * @description Inserts a new at a specific position of the point cloud. - * @param {number} index Index of new item. - * @returns {PointCloudItem} The newly inserted item. - */ - insertNew(index:number): PointCloudItem; - /** - * @description Merges, or appends, a specified point cloud into this one. - * @param {PointCloud} other PointCloud to merge with this one. - * @returns {void} - */ - merge(other:PointCloud): void; - /** - * @description Append a new point to the end of the list. - * @param {number[]} point Point to append. - * @returns {void} - */ - add(point:number[]): void; - /** ... */ - addPointNormal(): void; - /** ... */ - addPointColor(): void; - /** ... */ - addPointNormalColor(): void; - /** ... */ - addPointValue(): void; - /** ... */ - addPointNormalColorValue(): void; - /** - * @description Appends a collection of points to this point cloud. - * @param {Point3d[]} points Points to append. - * @returns {void} - */ - addRange(points:Point3d[]): void; - /** ... */ - addRangePointNormal(): void; - /** ... */ - addRangePointColor(): void; - /** ... */ - addRangePointNormalColor(): void; - /** ... */ - addRangePointValue(): void; - /** ... */ - addRangePointNormalColorValue(): void; - /** - * @description Inserts a new point into the point list. - * @param {number} index Insertion index. - * @param {number[]} point Point to append. - * @returns {void} - */ - insert(index:number,point:number[]): void; - /** ... */ - insertPointNormal(): void; - /** ... */ - insertPointColor(): void; - /** ... */ - insertPointNormalColor(): void; - /** ... */ - insertPointValue(): void; - /** ... */ - insertPointNormalColorValue(): void; - /** - * @description Append a collection of points to this point cloud. - * @param {number} index Index at which to insert the new collection. - * @param {Point3d[]} points Points to append. - * @returns {void} - */ - insertRange(index:number,points:Point3d[]): void; - /** - * @description Remove the point at the given index. - * @param {number} index Index of point to remove. - * @returns {void} - */ - removeAt(index:number): void; - /** - * @description Copy all the point coordinates in this point cloud to an array. - * @returns {Point3d[]} An array containing all the points in this point cloud. - */ - getPoints(): Point3d[]; - /** - * @description Returns the location of the point at a specific index. - * @param {number} index The index. - * @returns {number[]} - */ - pointAt(index:number): number[]; - /** - * @description Copy all the normal vectors in this point cloud to an array. - * @returns {any[]} An array containing all the normals in this point cloud. - */ - getNormals(): any[]; - /** - * @description Copy all the point colors in this point cloud to an array. - * @returns {number[][]} An array containing all the colors in this point cloud. - */ - getColors(): number[][]; - /** ... */ - getValues(): void; - /** - * @description Returns index of the closest point in the point cloud to a given test point. - * @param {number[]} testPoint . - * @returns {number} Index of point in the point cloud on success. -1 on failure. - */ - closestPoint(testPoint:number[]): number; - /** ... */ - toThreejsJSON(): void; - } - - class PointCloudItem { - /** - * Gets or sets the location of this point cloud item. - */ - location: number[]; - /** - * Gets or sets the X component of this point cloud item location. - */ - x: number; - /** - * Gets or sets the Y component of this point cloud item location. - */ - y: number; - /** - * Gets or sets the Z component of this point cloud item location. - */ - z: number; - /** - * Gets or sets the normal vector for this point cloud item. - * If this point cloud item does not have a normal vector, - * Vector3d.Unset is returned. - */ - normal: number[]; - /** - * Gets or sets the color of this point cloud item. - * If this point cloud item does not have a color, System.Drawing.Color.Black is returned. - */ - color: number[]; - /** - * Gets or sets the hidden flag of this point cloud item. - * If this point cloud item does not have a hidden flag, false is returned. - */ - hidden: boolean; - /** - */ - value: any; - /** - * Gets the index of this point cloud item. - */ - index: number; - } - - class PointGrid extends GeometryBase { - } - - class PolyCurve extends Curve { - /** - * Gets the number of segments that make up this Polycurve. - */ - segmentCount: number; - /** - * Gets a value indicating whether or not a PolyCurve contains nested PolyCurves. - */ - isNested: boolean; - /** - * This is a quick way to see if the curve has gaps between the sub curve segments. - */ - hasGap: boolean; - /** - * @description Gets the segment curve at the given index. - * @param {number} index Index of segment to retrieve. - * @returns {Curve} The segment at the given index or null on failure. - */ - segmentCurve(index:number): Curve; - /** - * @description Explodes nested polycurve segments and reconstructs this curve from the shattered remains. - The result will have not have any PolyCurves as segments but it will have identical - locus and parameterization. - * @returns {boolean} true if any nested PolyCurve was found and absorbed, false if no PolyCurve segments could be found. - */ - removeNesting(): boolean; - /** - * @description Explodes this PolyCurve into a list of Curve segments. This will not explode nested polycurves. - Call first if you need all individual segments. - * @returns {Curve[]} An array of polycurve segments. - */ - explode(): Curve[]; - /** ... */ - appendLine(): void; - /** ... */ - appendArc(): void; - /** ... */ - appendCurve(): void; - /** - * @description Appends the curve to the polycurve without changing the new segment's geometry. - This function will fail if the PolyCurve is closed or if SegmentCount > 0 and the new segment is closed. - * @param {Curve} curve Segment to append. - * @returns {boolean} true on success, false on failure. - */ - appendSegment(curve:Curve): boolean; - /** - * @description Converts a polycurve parameter to a segment curve parameter. - * @param {number} polycurveParameter Parameter on PolyCurve to convert. - * @returns {number} Segment curve evaluation parameter or UnsetValue if the - segment curve parameter could not be computed. - */ - segmentCurveParameter(polycurveParameter:number): number; - /** - * @description Converts a segment curve parameter to a polycurve parameter. - * @param {number} segmentIndex Index of segment. - * @param {number} segmentCurveParameter Parameter on segment. - * @returns {number} Polycurve evaluation parameter or UnsetValue if the polycurve curve parameter could not be computed. - */ - polyCurveParameter(segmentIndex:number,segmentCurveParameter:number): number; - /** - * @description Returns the polycurve sub-domain assigned to a segment curve. - * @param {number} segmentIndex Index of segment. - * @returns {number[]} The polycurve sub-domain assigned to a segment curve. - Returns Interval.Unset if segment_index < 0 or segment_index >= Count(). - */ - segmentDomain(segmentIndex:number): number[]; - /** - * @description Finds the segment used for evaluation at polycurve_parameter. - * @param {number} polycurveParameter Parameter on polycurve for segment lookup. - * @returns {number} Index of the segment used for evaluation at polycurve_parameter. - If polycurve_parameter < Domain.Min(), then 0 is returned. - If polycurve_parameter > Domain.Max(), then Count()-1 is returned. - */ - segmentIndex(polycurveParameter:number): number; - } - - class Polyline extends Point3dList { - /** - * Gets a value that indicates whether this polyline is valid. - * Valid polylines have at least one segment, no Invalid points and no zero length segments.Closed polylines with only two segments are also not considered valid. - */ - isValid: boolean; - /** - * Gets the number of segments for this polyline. - */ - segmentCount: number; - /** - * Test a polyline to see if it is closed. - */ - isClosed: boolean; - /** - * Gets the total length of the polyline. - */ - length: number; - - constructor(initialCapacity: number); - /** - * @description Test a polyline to see if it is closed. - * @param {number} tolerance The tolerance. - * @returns {boolean} Returns true if polyline has 4 or more points, the distance between the - start and end points is <= tolerance, and there is a - point in the polyline whose distance from the start and end - points is > tolerance. - */ - isClosedWithinTolerance(tolerance:number): boolean; - /** - * @description Gets the point on the polyline at the given parameter. - The integer part of the parameter indicates the index of the segment. - * @param {number} t Polyline parameter. - * @returns {number[]} The point on the polyline at t. - */ - pointAt(t:number): number[]; - /** - * @description Gets the unit tangent vector along the polyline at the given parameter. - The integer part of the parameter indicates the index of the segment. - * @param {number} t Polyline parameter. - * @returns {number[]} The tangent along the polyline at t. - */ - tangentAt(t:number): number[]; - /** ... */ - closesPoint(): void; - /** - * @description Gets the parameter along the polyline which is closest to a test-point. - * @param {number[]} testPoint Point to approximate. - * @returns {number} The parameter along the polyline closest to testPoint. - */ - closestParameter(testPoint:number[]): number; - /** - * @description Constructs a nurbs curve representation of this polyline. - * @returns {NurbsCurve} A Nurbs curve shaped like this polyline or null on failure. - */ - toNurbsCurve(): NurbsCurve; - /** - * @description Constructs a polyline curve representation of this polyline. - * @returns {PolylineCurve} A curve shaped like this polyline or null on failure. - */ - toPolylineCurve(): PolylineCurve; - /** - * @description Constructs an array of line segments that make up the entire polyline. - * @returns {Line[]} An array of line segments or null if the polyline contains fewer than 2 points. - */ - getSegments(): Line[]; - /** - * @description Gets the line segment at the given index. - * @param {number} index Index of segment to retrieve. - * @returns {Line} Line segment at index or Line.Unset on failure. - */ - segmentAt(index:number): Line; - /** - * @description Create a regular polygon inscribed in a circle. The vertices of the polygon will be on the circle. - * @param {Circle} circle The circle. - * @param {number} sideCount The number of sides - * @returns {Polyline} A closed polyline if successful, null otherwise. - */ - static createInscribedPolygon(circle:Circle,sideCount:number): Polyline; - /** - * @description Create a regular polygon circumscribe about a circle. The midpoints of the polygon's edges will be tangent to the circle. - * @param {Circle} circle The circle. - * @param {number} sideCount The number of sides - * @returns {Polyline} A closed polyline if successful, null otherwise. - */ - static createCircumscribedPolygon(circle:Circle,sideCount:number): Polyline; - /** - * @description Create a regular star polygon. The star begins at circle.PointAt(0) and the vertices - alternate between being on circle and begin on a concentric circle of other_radius. - * @param {Circle} circle The circle. - * @param {number} radius The radius of other circle. - * @param {number} cornerCount The number of corners on the circle. There will be 2*cornerCount sides and 2*cornerCount vertices. - * @returns {Polyline} A closed polyline if successful, null otherwise. - */ - static createStarPolygon(circle:Circle,radius:number,cornerCount:number): Polyline; - /** ... */ - static createFromPoints(): void; - } - - class PolylineCurve extends Curve { - /** - * Gets the number of points in this polyline. - */ - pointCount: number; - /** - * @description Gets a point at a specified index in the polyline curve. - * @param {number} index An index. - * @returns {number[]} A point. - */ - point(index:number): number[]; - /** - * @description Sets a point at a specified index in the polyline curve. - * @param {number} index An index. - * @param {number[]} point A point location to set. - * @returns {void} - */ - setPoint(index:number,point:number[]): void; - /** - * @description Returns the underlying Polyline, or points. - * @returns {Polyline} The Polyline if successful, null of the curve has no points. - */ - ToPolyline(): Polyline; - } - - class PostEffect { - /** - */ - id: any; - /** - */ - type: any; - /** - */ - localName: any; - /** - */ - listable: any; - /** - */ - on: any; - /** - */ - shown: any; - /** ... */ - getParameter(): void; - /** ... */ - setParameter(): void; - } - - class RenderChannels { - /** - */ - mode: Modes; - /** - */ - customIds: any; - } - - class RenderContent extends ModelComponent { - /** - */ - kind: any; - /** - */ - isChild: any; - /** - */ - isTopLevel: any; - /** - */ - id: any; - /** - */ - typeName: any; - /** - */ - name: any; - /** - */ - typeId: any; - /** - */ - renderEngineId: any; - /** - */ - plugInId: any; - /** - */ - notes: any; - /** - */ - tags: any; - /** - */ - groupId: any; - /** - */ - hidden: any; - /** - */ - reference: any; - /** - */ - autoDelete: any; - /** - */ - childSlotName: any; - /** ... */ - getParent(): void; - /** ... */ - getFirstChild(): void; - /** ... */ - getNextSibling(): void; - /** ... */ - getTopLevel(): void; - /** ... */ - setTypeName(): void; - /** ... */ - childSlotOn(): void; - /** ... */ - setChildSlotOn(): void; - /** ... */ - childSlotAmount(): void; - /** ... */ - setChildSlotAmount(): void; - /** ... */ - getXML(): void; - /** ... */ - setXML(): void; - /** ... */ - setChild(): void; - /** ... */ - findChild(): void; - /** ... */ - deleteChild(): void; - /** ... */ - getParameter(): void; - /** ... */ - setParameter(): void; - } - - class RenderEnvironment extends File3dmRenderContent { - /** ... */ - toEnvironment(): void; - } - - class RenderEnvironments { - /** - */ - backgroundId: any; - /** - */ - skylightingId: any; - /** - */ - skylightingOverride: any; - /** - */ - reflectionId: any; - /** - */ - reflectionOverride: any; - /** - */ - backgroundId: any; - /** - */ - skylightingId: any; - /** - */ - skylightingOverride: any; - /** - */ - reflectionId: any; - /** - */ - reflectionOverride: any; - } - - class RenderMaterial extends File3dmRenderContent { - /** ... */ - toMaterial(): void; - } - - class RenderSettings extends CommonObject { - /** - * Gets or sets the ambient light color used in rendering. - */ - ambientLight: number[]; - /** - * Gets or sets the background top color used in rendering. - * Sets also the background color if a solid background color is set. - */ - backgroundColorTop: number[]; - /** - * Gets or sets the background bottom color used in rendering. - */ - backgroundColorBottom: number[]; - /** - * Gets or sets a value indicating whether to render using lights that are on layers that are off. - */ - useHiddenLights: boolean; - /** - * Gets or sets a value indicating whether to render using depth cues. - * These are clues to help the perception of position and orientation of objects in the image. - */ - depthCue: boolean; - /** - * Gets or sets a value indicating whether to render using flat shading. - */ - flatShade: boolean; - /** - * Gets or sets a value indicating whether to render back faces. - */ - renderBackFaces: boolean; - /** - * Gets or sets a value indicating whether to instruct the rendering engine to show points. - */ - renderPoints: boolean; - /** - * Gets or sets a value indicating whether to instruct the rendering engine to show curves. - */ - renderCurves: boolean; - /** - * Gets or sets a value indicating whether to instruct the rendering engine to show isocurves. - */ - renderIsoParams: boolean; - /** - * Gets or sets a value indicating whether to instruct the rendering engine to show mesh edges. - */ - renderMeshEdges: boolean; - /** - * Gets or sets a value indicating whether to instruct the rendering engine to show annotations, - * such as linear dimensions or angular dimensions. - */ - renderAnnotations: boolean; - /** - * Gets or sets a value indicating whether to use the resolution of the - * viewport being rendered or ImageSize when rendering - */ - useViewportSize: boolean; - /** - * Gets or sets a value indicating whether to scale the wallpaper in the - * background or not. This is meaningful only if the viewport has a wallpaper - * and render settings are set to render Wallpaper into the background. - */ - scaleBackgroundToFit: boolean; - /** - * Gets or sets whether rendering should be done with transparent background. - */ - transparentBackground: boolean; - /** - * Number of dots/inch (dots=pixels) to use when printing and saving - * bitmaps. The default is 72.0 dots/inch. - */ - imageDpi: number; - /** - * 0=none, 1=normal, 2=best. - */ - shadowMapLevel: number; - /** - * Get or set the given named view - */ - namedView: string; - /** - * Set or get the given snapshot view - */ - snapShot: string; - /** - * Set or get the given specific viewport - */ - specificViewport: string; - /** - * If this object is associated with a document, this gets the document ground plane. - * If this object is associated with a File3dm, this gets the File3dm's ground plane. - * Otherwise it gets a 'free-floating' ground plane object. - */ - groundPlane: GroundPlane; - /** - * If this object is associated with a document, this gets the document safe-frame. - * If this object is associated with a File3dm, this gets the File3dm's safe-frame. - * Otherwise it gets a 'free-floating' safe-frame object. - */ - safeFrame: SafeFrame; - /** - * If this object is associated with a document, this gets the document dithering. - * If this object is associated with a File3dm, this gets the File3dm's dithering. - * Otherwise it gets a 'free-floating' dithering object. - */ - dithering: Dithering; - /** - * If this object is associated with a document, this gets the document skylight. - * If this object is associated with a File3dm, this gets the File3dm's skylight. - * Otherwise it gets a 'free-floating' skylight object. - */ - skylight: Skylight; - /** - * If this object is associated with a document, this gets the document linear workflow. - * If this object is associated with a File3dm, this gets the File3dm's linear workflow. - * Otherwise it gets a 'free-floating' linear workflow object. - */ - linearWorkflow: LinearWorkflow; - /** - * If this object is associated with a document, this gets the document render channels. - * Otherwise it gets a 'free-floating' render channels object. - */ - renderChannels: RenderChannels; - /** - * If this object is associated with a document, this gets the document sun. - * If this object is associated with a File3dm, this gets the File3dm's sun. - * Otherwise it gets a 'free-floating' sun object. - */ - sun: Sun; - /** - */ - renderEnvironments: any; - /** - * If this object is associated with a document, this gets the document post effect data collection. - * If this object is associated with a File3dm, this gets the File3dm's post effect data collection. - * Otherwise it gets a 'free-floating' post effect data collection object. - */ - postEffects: PostEffectCollection; - } - - class RenderTexture extends File3dmRenderContent { - /** - */ - fileName: any; - /** ... */ - toTexture(): void; - /** ... */ - setFilename(): void; - } - - class RevSurface extends Surface { - /** - * @description Constructs a new surface of revolution from a generatrix curve and an axis. - This overload accepts a slice start and end angles. - * @param {Curve} revoluteCurve A generatrix. - * @param {Line} axisOfRevolution An axis. - * @param {number} startAngleRadians An angle in radians for the start. - * @param {number} endAngleRadians An angle in radians for the end. - * @returns {RevSurface} A new surface of revolution, or null if any of the inputs is invalid or on error. - */ - static create(revoluteCurve:Curve,axisOfRevolution:Line,startAngleRadians:number,endAngleRadians:number): RevSurface; - } - - class SafeFrame { - /** - * Determines whether the safe-frame is enabled. - */ - enabled: boolean; - /** - * Show the safe-frame only in perspective views. - */ - perspectiveOnly: boolean; - /** - */ - fieldGridOn: any; - /** - * Turn on the live area, which shows the size of the rendered view as a yellow frame - * in the viewport. - */ - liveFrameOn: boolean; - /** - * Turn on the user specified action area, which shown with blue frames. - */ - actionFrameOn: boolean; - /** - * Action Frame Linked, On = Use the same scale for X and Y. Off = use - * different scales for X and Y. - */ - actionFrameLinked: boolean; - /** - * Action Frame X-scale. - * This value should be in the range 0..1 but it is not clamped. - * It is displayed in the UI in the range 0..100. - */ - actionFrameXScale: number; - /** - * Action Frame Y-scale. - * This value should be in the range 0..1 but it is not clamped. - * It is displayed in the UI in the range 0..100. - */ - actionFrameYScale: number; - /** - * Show a user specified title area frame in orange. - */ - titleFrameOn: boolean; - /** - * Title Frame Linked, On = Use the same scale for X and Y. Off = use - * different scales for X and Y. - */ - titleFrameLinked: boolean; - /** - * Title Frame X-scale. - * This value should be in the range 0..1 but it is not clamped. - * It is displayed in the UI in the range 0..100. - */ - titleFrameXScale: number; - /** - * Title Frame Y-scale. - * This value should be in the range 0..1 but it is not clamped. - * It is displayed in the UI in the range 0..100. - */ - titleFrameYScale: number; - } - - class ShutLining { - /** - */ - on: any; - /** - */ - faceted: any; - /** - */ - autoUpdate: any; - /** - */ - forceUpdate: any; - /** - */ - curves: any; - /** ... */ - deleteAllCurves(): void; - } - - class ShutLiningCurve { - /** - */ - id: any; - /** - */ - radius: any; - /** - */ - profile: any; - /** - */ - enabled: any; - /** - */ - pull: any; - /** - */ - isBump: any; - } - - class Skylight { - /** - */ - enabled: boolean; - /** - * ShadowIntensity is currently unused. - */ - shadowIntensity: number; - } - - class Sphere { - /** - * Gets a value that indicates whether the sphere is valid. - */ - isValid: boolean; - /** - * Gets or sets the diameter for this sphere. - */ - diameter: number; - /** - * Gets or sets the Radius for this sphere. - */ - radius: number; - /** - * Gets or sets the center point of the sphere. - */ - center: number[]; - /** - * Gets the point at the North Pole of the sphere. - * This is the parameterization singularity that can be obtained, - * at V value +Math.Pi/2. - */ - northPole: number[]; - /** - * Gets the point at the South Pole of the sphere. - * This is the parameterization singularity that can be obtained, - * at V value -Math.Pi/2. - */ - southPole: number[]; - - constructor(center: number[], radius: number); - /** - * @description Computes the parallel at a specific latitude angle. - The angle is specified in radians. - * @param {number} radians An angle in radians for the parallel. - * @returns {Circle} A circle. - */ - latitudeRadians(radians:number): Circle; - /** - * @description Computes the parallel at a specific latitude angle. - The angle is specified in degrees. - * @param {number} degrees An angle in degrees for the meridian. - * @returns {Circle} A circle. - */ - latitudeDegrees(degrees:number): Circle; - /** - * @description Computes the meridian at a specific longitude angle. - The angle is specified in radians. - * @param {number} radians An angle in radians. - * @returns {Circle} A circle. - */ - longitudeRadians(radians:number): Circle; - /** - * @description Computes the meridian at a specific longitude angle. - The angle is specified in degrees. - * @param {number} degrees An angle in degrees. - * @returns {Circle} A circle. - */ - longitudeDegrees(degrees:number): Circle; - /** - * @description Evaluates the sphere at specific longitude and latitude angles. - * @param {number} longitudeRadians A number within the interval [0, 2pi]. - * @param {number} latitudeRadians A number within the interval [-pi/2,pi/2]. - * @returns {number[]} A point value. - */ - pointAt(longitudeRadians:number,latitudeRadians:number): number[]; - /** - * @description Computes the normal at a specific angular location on the sphere. - * @param {number} longitudeRadians A number within the interval [0, 2pi]. - * @param {number} latitudeRadians A number within the interval [-pi/2, pi/2]. - * @returns {number[]} A vector. - */ - normalAt(longitudeRadians:number,latitudeRadians:number): number[]; - /** - * @description Returns point on sphere that is closest to given point. - * @param {number[]} testPoint Point to project onto Sphere. - * @returns {number[]} Point on sphere surface closest to testPoint. - */ - closestPoint(testPoint:number[]): number[]; - /** - * @description Finds the angle parameters on this sphere that are closest to a test point. - * @param {number[]} testPoint Point to project onto the sphere. - * @returns {Array} [boolean, number, number] - * (boolean) true on success, false on failure. This function will fail if the point it coincident with the sphere center. - * (number) The longitudinal angle (in radians; 0.0 to 2pi) where the sphere approaches testPoint best. - * (number) The latitudinal angle (in radians; -0.5pi to +0.5pi) where the sphere approaches testPoint best. - */ - closestParameter(testPoint:number[]): object; - /** - * @description Converts this sphere is it Brep representation - * @returns {Brep} - */ - toBrep(): Brep; - /** - * @description Converts this sphere to its NurbsSurface representation. - This is synonymous with calling NurbsSurface.CreateFromSphere(). - * @returns {NurbsSurface} A nurbs surface representation of this sphere or null. - */ - toNurbsSurface(): NurbsSurface; - /** ... */ - encode(): void; - /** ... */ - toJSON(): void; - /** ... */ - static decode(): void; - } - - class SubD extends GeometryBase { - /** - * Test SubD to see if the active level is a solid. - * A "solid" is a closed oriented manifold, or a closed oriented manifold. - */ - isSolid: boolean; - /** - * @description Clear cached information that depends on the location of vertex control points - * @returns {void} - */ - clearEvaluationCache(): void; - /** - * @description Updates vertex tag, edge tag, and edge coefficient values on the active - level. After completing custom editing operations that modify the - topology of the SubD control net or changing values of vertex or edge - tags, the tag and sector coefficients information on nearby components - in the edited areas need to be updated. - * @returns {number} Number of vertices and edges that were changed during the update. - */ - updateAllTagsAndSectorCoefficients(): number; - /** - * @description Apply the Catmull-Clark subdivision algorithm and save the results in this SubD. - * @returns {boolean} true on success - */ - subdivide(): boolean; - } - - class Sun { - /** - */ - minYear: any; - /** - */ - maxYear: any; - /** - */ - vector: Vector3d; - /** - */ - enableAllowed: any; - /** - */ - enableOn: any; - /** - */ - manualControlAllowed: any; - /** - * Manual control 'on' state. When true, allows the user to set the sun - * azimuth and altitude directly. When false, the values are computed. - */ - manualControlOn: boolean; - /** - * Angle in degrees on world X-Y plane that should be considered north in the model. - * The angle is measured starting at the x-axis and increases anti-clockwise. The y-axis - * corresponds to a 'north' angle of 90 degrees. - */ - north: number; - /** - * The sun's azimuth in degrees. The value increases Eastwards with North as zero. - * Setting this value will also set the sun to manual control mode. - * Note: This value is not affected by the direction of north. - */ - azimuth: number; - /** - * The sun's altitude above the horizon in degrees in the range -90 to +90. - * Setting this value will also set the sun to manual control mode. - */ - altitude: number; - /** - * The observer's latitude. - */ - latitude: number; - /** - * The observer's longitude. - */ - longitude: number; - /** - * The observer's time zone measured in hours relative to UTC. - */ - timeZone: number; - /** - * Daylight saving time 'on' state - */ - daylightSavingOn: boolean; - /** - * Daylight saving time in minutes - */ - daylightSavingMinutes: number; - /** - */ - year: any; - /** - */ - month: any; - /** - */ - day: any; - /** - */ - hours: any; - /** - * Sun intensity. - */ - intensity: number; - /** - */ - isValid: any; - /** - * Get a Light which represents the sun. If manual control is in effect, no sun calculation - * is performed; the function uses the last known values of azimuth and altitude. - * If manual control is not in effect, the observer's position, date, time, time zone and - * daylight saving values are used to calculate the position of the sun. - */ - light: Light; - /** ... */ - static sunColorFromAltitude(): void; - } - - class Surface extends GeometryBase { - /** - * Gets a values indicating whether a surface is solid. - */ - isSolid: boolean; - /** - * @description Sets the domain in a direction. - * @param {number} direction 0 sets first parameter's domain, 1 sets second parameter's domain. - * @param {number[]} domain A new domain to be assigned. - * @returns {boolean} true if setting succeeded, otherwise false. - */ - setDomain(direction:number,domain:number[]): boolean; - /** - * @description Returns the maximum algebraic degree of any span - (or a good estimate if curve spans are not algebraic). - * @param {number} direction 0 gets first parameter's domain, 1 gets second parameter's domain. - * @returns {number} The maximum degree. - */ - degree(direction:number): number; - /** - * @description Gets number of smooth nonempty spans in the parameter direction. - * @param {number} direction 0 gets first parameter's domain, 1 gets second parameter's domain. - * @returns {number} The span count. - */ - spanCount(direction:number): number; - /** - * @description Evaluates a point at a given parameter. - * @param {number} u evaluation parameters. - * @param {number} v evaluation parameters. - * @returns {number[]} Point3d.Unset on failure. - */ - pointAt(u:number,v:number): number[]; - /** - * @description Gets the domain in a direction. - * @param {number} direction 0 gets first parameter, 1 gets second parameter. - * @returns {number[]} An interval value. - */ - domain(direction:number): number[]; - /** - * @description Gets array of span "knots". - * @param {number} direction 0 gets first parameter's domain, 1 gets second parameter's domain. - * @returns {number[]} An array with span vectors; or null on error. - */ - getSpanVector(direction:number): number[]; - /** - * @description Computes the surface normal at a point. - This is the simple evaluation call - it does not support error handling. - * @param {number} u A U parameter. - * @param {number} v A V parameter. - * @returns {number[]} The normal. - */ - normalAt(u:number,v:number): number[]; - /** - * @description Computes the orient plane on a surface given a U and V parameter. - This is the simple evaluation call with no error handling. - * @param {number} u A first parameter. - * @param {number} v A second parameter. - * @returns {Array} [boolean, Plane] - * (boolean) true if this operation succeeded; otherwise false. - * (Plane) A frame plane that will be computed during this call. - */ - frameAt(u:number,v:number): object; - /** - * @description Gets a value indicating if the surface is closed in a direction. - * @param {number} direction 0 = U, 1 = V. - * @returns {boolean} The indicating boolean value. - */ - isClosed(direction:number): boolean; - /** - * @description Gets a value indicating if the surface is periodic in a direction (default is false). - * @param {number} direction 0 = U, 1 = V. - * @returns {boolean} The indicating boolean value. - */ - isPeriodic(direction:number): boolean; - /** - * @description true if surface side is collapsed to a point. - * @param {number} side side of parameter space to test - 0 = south, 1 = east, 2 = north, 3 = west. - * @returns {boolean} True if this specific side of the surface is singular; otherwise, false. - */ - isSingular(side:number): boolean; - /** - * @description Tests if a surface parameter value is at a singularity. - * @param {number} u Surface u parameter to test. - * @param {number} v Surface v parameter to test. - * @param {boolean} exact If true, test if (u,v) is exactly at a singularity. - If false, test if close enough to cause numerical problems. - * @returns {boolean} true if surface is singular at (s,t) - */ - isAtSingularity(u:number,v:number,exact:boolean): boolean; - /** - * @description Tests if a surface parameter value is at a seam. - * @param {number} u Surface u parameter to test. - * @param {number} v Surface v parameter to test. - * @returns {number} 0 if not a seam, - 1 if u == Domain(0)[i] and srf(u, v) == srf(Domain(0)[1-i], v) - 2 if v == Domain(1)[i] and srf(u, v) == srf(u, Domain(1)[1-i]) - 3 if 1 and 2 are true. - */ - isAtSeam(u:number,v:number): number; - /** - * @description Gets isoparametric curve. - * @param {number} direction 0 first parameter varies and second parameter is constant - e.g., point on IsoCurve(0,c) at t is srf(t,c) - This is a horizontal line from left to right - 1 first parameter is constant and second parameter varies - e.g., point on IsoCurve(1,c) at t is srf(c,t - This is a vertical line from bottom to top. - * @param {number} constantParameter The parameter that was constant on the original surface. - * @returns {Curve} An isoparametric curve or null on error. - */ - isoCurve(direction:number,constantParameter:number): Curve; - /** - * @description Gets a NURBS surface representation of this surface. Default - tolerance of 0.0 is used. - * @returns {NurbsSurface} NurbsSurface on success, null on failure. - */ - toNurbsSurface(): NurbsSurface; - /** ... */ - toNurbsSurfaceTolerance(): void; - /** - * @description Tests a surface to see if it is planar to zero tolerance. - * @returns {boolean} true if the surface is planar (flat) to within RhinoMath.ZeroTolerance units (1e-12). - */ - isPlanar(): boolean; - /** - * @description Determines if the surface is a portion of a sphere within RhinoMath.ZeroTolerance. - * @returns {boolean} true if the surface is a portion of a sphere. - */ - isSphere(): boolean; - /** - * @description Determines if the surface is a portion of a cylinder within RhinoMath.ZeroTolerance. - * @returns {boolean} true if the surface is a portion of a cylinder. - */ - isCylinder(): boolean; - /** - * @description Determines if the surface is a portion of a cone within RhinoMath.ZeroTolerance. - * @returns {boolean} true if the surface is a portion of a cone. - */ - isCone(): boolean; - /** - * @description Determines if the surface is a portion of a torus within RhinoMath.ZeroTolerance. - * @returns {boolean} true if the surface is a portion of a torus. - */ - isTorus(): boolean; - /** - * @description Translates a parameter from a value on the surface returned by to the current surface. - * @param {number} nurbsS The parameter in the S, or sometimes U, direction of the NURBS form surface. - * @param {number} nurbsT The parameter in the T, or sometimes V, direction of the NURBS form surface. - * @returns {Array} [boolean, number, number] - * (boolean) True if the operation succeeded; otherwise, false. - * (number) S on this surface. - * (number) T o n this surface. - */ - getSurfaceParameterFromNurbsFormParameter(nurbsS:number,nurbsT:number): object; - /** - * @description Translates a parameter from the current surface to the parameter space of the surface returned by . - * @param {number} surfaceS The parameter in the S, or sometimes U, direction, of this surface. - * @param {number} surfaceT The parameter in the T, or sometimes V, direction of this surface. - * @returns {Array} [boolean, number, number] - * (boolean) True if the operation succeeded; otherwise, false. - * (number) S on the NURBS form. - * (number) T on the NURBS form. - */ - getNurbsFormParameterFromSurfaceParameter(surfaceS:number,surfaceT:number): object; - } - - class SurfaceProxy extends Surface { - } - - class TextDot extends GeometryBase { - /** - * Gets or sets the position of the text dot. - */ - point: number[]; - /** - * Gets or sets the primary text of the text dot. - */ - text: string; - /** - * Gets or sets the secondary text of the text dot. - */ - secondaryText: string; - /** - * Height of font used for displaying the dot - */ - fontHeight: number; - /** - * Font face used for displaying the dot - */ - fontFace: string; - } - - class Texture { - /** - * Gets or sets a file name that is used by this texture. - * NOTE: We are moving away from string-based FileName, and suggest - * the usage of the new FileReference class.Also, this filename may well not be a path that makes sense - * on a user's computer because it was a path initially set on - * a different user's computer. If you want to get a workable path - * for this user, use the BitmapTable.Find function using this - * property. - */ - fileName: string; - /** - * Texture wrapping mode in the U direction - */ - wrapU: TextureUvwWrapping; - /** - * Texture wrapping mode in the V direction - */ - wrapV: TextureUvwWrapping; - /** - * Texture wrapping mode in the W direction - */ - wrapW: TextureUvwWrapping; - /** - * Transform to be applied to each instance of this texture - * if ApplyUvw is true - */ - uvwTransform: Transform; - /** - * Gets the globally unique identifier of this texture. - */ - id: string; - /** - * If the texture is enabled then it will be visible in the rendered - * display otherwise it will not. - */ - enabled: boolean; - /** - * Controls how the pixels in the bitmap are interpreted - */ - textureType: TextureType; - /** - * Helper for access to the repeat value encoded in UvwTransform - */ - repeat: Vector2d; - /** - * Helper for access to the offset value encoded in UvwTransform - */ - offset: Vector2d; - /** - * Helper for access to the rotation value encoded in UvwTransform - */ - rotation: number; - /** ... */ - fileReference(): void; - } - - class TextureMapping extends CommonObject { - /** - */ - requiresVertexNormals: any; - /** - */ - isPeriodic: any; - /** - * @description Create a mapping that will convert surface parameters into normalized(0,1)x(0,1) texture coordinates. - * @returns {TextureMapping} TextureMapping instance or null if failed. - */ - static createSurfaceParameterMapping(): TextureMapping; - /** - * @description Create a planar UV projection texture mapping - * @param {Plane} plane A plane to use for mapping. - * @param {number[]} dx portion of the plane's x axis that is mapped to [0,1] (can be a decreasing interval) - * @param {number[]} dy portion of the plane's y axis that is mapped to [0,1] (can be a decreasing interval) - * @param {number[]} dz portion of the plane's z axis that is mapped to [0,1] (can be a decreasing interval) - * @returns {TextureMapping} TextureMapping instance if input is valid - */ - static createPlaneMapping(plane:Plane,dx:number[],dy:number[],dz:number[]): TextureMapping; - /** - * @description Create a cylindrical projection texture mapping. - * @param {Cylinder} cylinder cylinder in world space used to define a cylindrical coordinate system. - The angular parameter maps (0,2pi) to texture "u" (0,1), The height - parameter maps (height[0],height[1]) to texture "v" (0,1), and the - radial parameter maps (0,r) to texture "w" (0,1). - * @param {boolean} capped If true, the cylinder is treated as a finite capped cylinder - * @returns {TextureMapping} TextureMapping instance if input is valid - */ - static createCylinderMapping(cylinder:Cylinder,capped:boolean): TextureMapping; - /** - * @description Create a spherical projection texture mapping. - * @param {Sphere} sphere sphere in world space used to define a spherical coordinate system. - The longitude parameter maps (0,2pi) to texture "u" (0,1). - The latitude parameter maps (-pi/2,+pi/2) to texture "v" (0,1). - The radial parameter maps (0,r) to texture "w" (0,1). - * @returns {TextureMapping} TextureMapping instance if input is valid - */ - static createSphereMapping(sphere:Sphere): TextureMapping; - /** - * @description Create a box projection texture mapping. - * @param {Plane} plane The sides of the box the box are parallel to the plane's coordinate - planes. The dx, dy, dz intervals determine the location of the sides. - * @param {number[]} dx Determines the location of the front and back planes. The vector - plane.xaxis is perpendicular to these planes and they pass through - plane.PointAt(dx[0],0,0) and plane.PointAt(dx[1],0,0), respectively. - * @param {number[]} dy Determines the location of the left and right planes. The vector - plane.yaxis is perpendicular to these planes and they pass through - plane.PointAt(0,dy[0],0) and plane.PointAt(0,dy[1],0), respectively. - * @param {number[]} dz Determines the location of the top and bottom planes. The vector - plane.zaxis is perpendicular to these planes and they pass through - plane.PointAt(0,0,dz[0]) and plane.PointAt(0,0,dz[1]), respectively. - * @param {boolean} capped If true, the box is treated as a finite capped box. - * @returns {TextureMapping} TextureMapping instance if input is valid - */ - static CreateBoxMapping(plane:Plane,dx:number[],dy:number[],dz:number[],capped:boolean): TextureMapping; - /** - * @description Get a cylindrical projection parameters from this texture mapping. - * @returns {boolean} Returns true if a valid cylinder is returned. - */ - tryGetMappingCylinder(): object; - /** - * @description Get a spherical projection parameters from this texture mapping. - * @returns {boolean} Returns true if a valid sphere is returned. - */ - tryGetMappingSphere(): object; - /** ... */ - reverseTextureCoordinate(): void; - /** ... */ - swapTextureCoordinate(): void; - /** ... */ - tileTextureCoordinate(): void; - /** - * @description Evaluate the mapping to get a texture coordinate - * @param {number[]} p Vertex location - * @param {number[]} n If the mapping projection is ray_projection, then this - is the vertex unit normal. Otherwise n is ignored. - * @returns {Array} [number, number[]] - * (number) Nonzero if evaluation is successful. When the mapping is a box or - capped cylinder mapping, the value indicates which side was evaluated. - Cylinder mapping: 1 = cylinder wall, 2 = bottom cap, 3 = top cap - Box mapping: 1 = front, 2 = right, 3 = back, 4 = left, 5 = bottom, 6 = top - * (number[]) Texture coordinate (u,v,w) - */ - evaluate(p:number[],n:number[]): object; - } - - class Thickening { - /** - */ - on: any; - /** - */ - distance: any; - /** - */ - solid: any; - /** - */ - offsetOnly: any; - /** - */ - bothSides: any; - } - - class Transform { - /** - * Tests for an affine transformation. - * A transformation is affine if it is valid and its last row is [0, 0, 0, 1]. - * An affine transformation can be broken into a linear transformation and a translation. - */ - isAffine: boolean; - /** - * Return true if this Transform is the identity transform - */ - isIdentity: boolean; - /** - * Tests for a linear transformation. - * A transformation is affine if it is valid and its last row is [0, 0, 0, 1]. - * If in addition its last column is ( 0, 0, 0, 1)^T then it is linear. - * An affine transformation can be broken into a linear transformation and a translation. - */ - isLinear: boolean; - /** - * Returns true if this is a proper rotation. - */ - isRotation: boolean; - /** - * Gets a value indicating whether or not this Transform is a valid matrix. - * A valid transform matrix is not allowed to have any invalid numbers. - */ - isValid: boolean; - /** - * True if matrix is Zero4x4, ZeroTransformation, or some other type of - * zero. The value xform[3][3] can be anything. - */ - isZero: boolean; - /** - * True if all values are 0 - */ - isZero4x4: boolean; - /** - * True if all values are 0, except for M33 which is 1. - */ - isZeroTransformation: boolean; - /** - * Gets a value indicating whether or not the Transform is rigid. - * A rigid transformation can be broken into a proper rotation and a translation, - * while an isometry transformation could also include a reflection. - */ - rigidType: TransformRigidType; - /** - * Gets a value indicating whether or not the Transform maintains similarity. - * The easiest way to think of Similarity is that any circle, when transformed, - * remains a circle. Whereas a non-similarity Transform deforms circles into ellipses. - */ - similarityType: TransformSimilarityType; - /** - * Gets or sets this[0,0]. - */ - m00: number; - /** - * Gets or sets this[0,1]. - */ - m01: number; - /** - * Gets or sets this[0,2]. - */ - m02: number; - /** - * Gets or sets this[0,3]. - */ - m03: number; - /** - * Gets or sets this[1,0]. - */ - m10: number; - /** - * Gets or sets this[1,1]. - */ - m11: number; - /** - * Gets or sets this[1,2]. - */ - m12: number; - /** - * Gets or sets this[1,3]. - */ - m13: number; - /** - * Gets or sets this[2,0]. - */ - m20: number; - /** - * Gets or sets this[2,1]. - */ - m21: number; - /** - * Gets or sets this[2,2]. - */ - m22: number; - /** - * Gets or sets this[2,3]. - */ - m23: number; - /** - * Gets or sets this[3,0]. - */ - m30: number; - /** - * Gets or sets this[3,1]. - */ - m31: number; - /** - * Gets or sets this[3,2]. - */ - m32: number; - /** - * Gets or sets this[3,3]. - */ - m33: number; - - constructor(diagonalValue: number); - /** ... */ - static identity(): void; - /** ... */ - static zeroTransformation(): void; - /** ... */ - static unset(): void; - /** ... */ - static translationXYZ(): void; - /** ... */ - static translationVector(): void; - /** - * @description Constructs a new uniform scaling transformation with a specified scaling anchor point. - * @param {number[]} anchor Defines the anchor point of the scaling operation. - * @param {number} scaleFactor Scaling factor in all directions. - * @returns {Transform} A transform matrix which scales geometry uniformly around the anchor point. - */ - static scale(anchor:number[],scaleFactor:number): Transform; - /** - * @description Constructs a new rotation transformation with specified angle, rotation center and rotation axis. - * @param {number} sinAngle Sine of the rotation angle. - * @param {number} cosAngle Cosine of the rotation angle. - * @param {number[]} rotationAxis 3D unit axis of rotation. - * @param {number[]} rotationCenter 3D center of rotation. - * @returns {Transform} A rotation transformation matrix. - */ - static rotation(sinAngle:number,cosAngle:number,rotationAxis:number[],rotationCenter:number[]): Transform; - /** ... */ - static rotationVectors(): void; - /** - * @description Create mirror transformation matrix - The mirror transform maps a point Q to - Q - (2*(Q-P)oN)*N, where - P = pointOnMirrorPlane and N = normalToMirrorPlane. - * @param {number[]} pointOnMirrorPlane Point on the mirror plane. - * @param {number[]} normalToMirrorPlane Normal vector to the mirror plane. - * @returns {Transform} A transformation matrix which mirrors geometry in a specified plane. - */ - static mirror(pointOnMirrorPlane:number[],normalToMirrorPlane:number[]): Transform; - /** ... */ - static mirrorPlane(): void; - /** - * @description Create a rotation transformation that orients plane0 to plane1. If you want to orient objects from - one plane to another, use this form of transformation. - * @param {Plane} plane0 The plane to orient from. - * @param {Plane} plane1 the plane to orient to. - * @returns {Transform} The translation transformation if successful, Transform.Unset on failure. - */ - static planeToPlane(plane0:Plane,plane1:Plane): Transform; - /** - * @description Constructs a Shear transformation. - * @param {Plane} plane Base plane for shear. - * @param {number[]} x Shearing vector along plane x-axis. - * @param {number[]} y Shearing vector along plane y-axis. - * @param {number[]} z Shearing vector along plane z-axis. - * @returns {Transform} A transformation matrix which shear geometry. - */ - static shear(plane:Plane,x:number[],y:number[],z:number[]): Transform; - /** - * @description Multiplies (combines) two transformations. - This is the same as the * operator between two transformations. - * @param {Transform} a First transformation. - * @param {Transform} b Second transformation. - * @returns {Transform} A transformation matrix that combines the effect of both input transformations. - The resulting Transform gives the same result as though you'd first apply B then A. - */ - static multiply(a:Transform,b:Transform): Transform; - /** ... */ - determinant(): void; - /** - * @description Attempts to get the inverse transform of this transform. - * @returns {Array} [boolean, Transform] - * (boolean) true on success. - If false is returned and this Transform is Invalid, inserveTransform will be set to this Transform. - If false is returned and this Transform is Valid, inverseTransform will be set to a pseudo inverse. - * (Transform) The inverse transform. This out reference will be assigned during this call. - */ - tryGetInverse(): object; - /** - * @description Computes a new bounding box that is the smallest axis aligned - bounding box that contains the transformed result of its 8 original corner - points. - * @returns {BoundingBox} A new bounding box. - */ - transformBoundingBox(): BoundingBox; - /** - * @description Flip row/column values - * @returns {Transform} - */ - transpose(): Transform; - /** - * @description Return the matrix as a linear array of 16 float values. - * @param {boolean} rowDominant If true, returns { M00, M01, M02...}. - If false, returns { M00, M10, M20...}. - * @returns {number[]} An array of 16 floats. - */ - toFloatArray(rowDominant:boolean): number[]; - } - - class ViewInfo { - /** - * Gets or sets the name of the view. - */ - name: string; - /** - */ - wallpaperName: any; - /** - * True if wallpaper (if any) is to be shown in gray scale in this view. - */ - showWallpaperInGrayScale: boolean; - /** - * True if wallpaper (if any) is to be hidden from this view. - */ - wallpaperHidden: boolean; - /** - * Gets or sets the Focal blur distance of the active viewport - */ - focalBlurDistance: number; - /** - * Gets or sets the Focal blur aperture of the active viewport - */ - focalBlurAperture: number; - /** - * Gets or sets the Focal blur jitter of the active viewport - */ - focalBlurJitter: number; - /** - * Gets or sets the Focal blur sample count of the active viewport - */ - focalBlurSampleCount: number; - /** ... */ - getViewport(): void; - /** ... */ - setViewport(): void; - } - - class ViewportInfo extends CommonObject { - /** - */ - isValidCameraFrame: any; - /** - * Gets a value that indicates whether the camera is valid. - */ - isValidCamera: boolean; - /** - * Gets a value that indicates whether the frustum is valid. - */ - isValidFrustum: boolean; - /** - * Get or set whether this projection is parallel. - */ - isParallelProjection: boolean; - /** - * Get or set whether this projection is perspective. - */ - isPerspectiveProjection: boolean; - /** - * Gets a value that indicates whether this projection is a two-point perspective. - */ - isTwoPointPerspectiveProjection: boolean; - /** - * Gets the camera location (position) point. - */ - cameraLocation: number[]; - /** - * Gets the direction that the camera faces. - */ - cameraDirection: number[]; - /** - * Gets the camera up vector. - */ - cameraUp: number[]; - /** - * Gets the unit "to the right" vector. - */ - cameraX: number[]; - /** - * Gets the unit "up" vector. - */ - cameraY: number[]; - /** - * Gets the unit vector in -CameraDirection. - */ - cameraZ: number[]; - /** - * Get or set the screen port. and - */ - screenPort: number[]; - /** - * Gets the screen aspect ratio. - * This is width / height. - */ - screenPortAspect: number; - /** - * Gets or sets the 1/2 smallest angle. See for more information. - */ - cameraAngle: number; - /** - * This property assumes the camera is horizontal and crop the - * film rather than the image when the aspect of the frustum - * is not 36/24. (35mm film is 36mm wide and 24mm high.) - * Setting preserves camera location, - * changes the frustum, but maintains the frustum's aspect. - */ - camera35mmLensLength: number; - /** - * The current value of the target point. This point does not play - * a role in the view projection calculations. It can be used as a - * fixed point when changing the camera so the visible regions of the - * before and after frustums both contain the region of interest. - * The default constructor sets this point on ON_3dPoint::UnsetPoint. - * You must explicitly call one SetTargetPoint() functions to set - * the target point. - */ - targetPoint: number[]; - /** - * Sets the viewport's id to the value used to - * uniquely identify this viewport. - * There is no approved way to change the viewport - * id once it is set in order to maintain consistency - * across multiple viewports and those routines that - * manage them. - */ - id: string; - /** ... */ - static defaultTop(): void; - /** ... */ - static defaultPerspective(): void; - /** - * @description Use this function to change projections of valid viewports - from parallel to perspective. It will make common additional - adjustments to the frustum and camera location so the resulting - views are similar. The camera direction and target point are - not be changed. - If the current projection is parallel and symmetricFrustum, - FrustumIsLeftRightSymmetric() and FrustumIsTopBottomSymmetric() - are all equal, then no changes are made and true is returned. - * @param {boolean} symmetricFrustum true if you want the resulting frustum to be symmetric. - * @returns {boolean} true if the operation succeeded; otherwise, false. - */ - changeToParallelProjection(symmetricFrustum:boolean): boolean; - /** - * @description Use this function to change projections of valid viewports - from parallel to perspective. It will make common additional - adjustments to the frustum and camera location so the resulting - views are similar. The camera direction and target point are - not changed. - If the current projection is perspective and symmetricFrustum, - IsFrustumIsLeftRightSymmetric, and IsFrustumIsTopBottomSymmetric - are all equal, then no changes are made and true is returned. - * @param {number} targetDistance If RhinoMath.UnsetValue this parameter is ignored. - Otherwise it must be > 0 and indicates which plane in the current view frustum should be preserved. - * @param {boolean} symmetricFrustum true if you want the resulting frustum to be symmetric. - * @param {number} lensLength (pass 50.0 when in doubt) - 35 mm lens length to use when changing from parallel - to perspective projections. If the current projection - is perspective or lens_length is <= 0.0, - then this parameter is ignored. - * @returns {boolean} true if the operation succeeded; otherwise, false. - */ - changeToPerspectiveProjection(targetDistance:number,symmetricFrustum:boolean,lensLength:number): boolean; - /** - * @description Changes projections of valid viewports - to a two point perspective. It will make common additional - adjustments to the frustum and camera location and direction - so the resulting views are similar. - If the current projection is perspective and - IsFrustumIsLeftRightSymmetric is true and - IsFrustumIsTopBottomSymmetric is false, then no changes are - made and true is returned. - * @param {number} targetDistance If RhinoMath.UnsetValue this parameter is ignored. Otherwise - it must be > 0 and indicates which plane in the current - view frustum should be preserved. - * @param {number[]} up The locked up direction. Pass Vector3d.Zero if you want to use the world - axis direction that is closest to the current up direction. - Pass CameraY() if you want to preserve the current up direction. - * @param {number} lensLength (pass 50.0 when in doubt) - 35 mm lens length to use when changing from parallel - to perspective projections. If the current projection - is perspective or lens_length is <= 0.0, - then this parameter is ignored. - * @returns {boolean} true if the operation succeeded; otherwise, false. - */ - changeToTwoPointPerspectiveProjection(targetDistance:number,up:number[],lensLength:number): boolean; - /** - * @description Sets the camera location (position) point. - * @returns {boolean} true if the operation succeeded; otherwise, false. - */ - setCameraLocation(): boolean; - /** - * @description Sets the direction that the camera faces. - * @param {number[]} direction A new direction. - * @returns {boolean} true if the direction was set; otherwise false. - */ - setCameraDirection(direction:number[]): boolean; - /** - * @description Sets the camera up vector. - * @param {number[]} up A new direction. - * @returns {boolean} true if the direction was set; otherwise false. - */ - setCameraUp(up:number[]): boolean; - /** - * @description Sets the view frustum. If FrustumSymmetryIsLocked() is true - and left != -right or bottom != -top, then they will be - adjusted so the resulting frustum is symmetric. - * @param {number} left A new left value. - * @param {number} right A new right value. - * @param {number} bottom A new bottom value. - * @param {number} top A new top value. - * @param {number} nearDistance A new near distance value. - * @param {number} farDistance A new far distance value. - * @returns {boolean} true if operation succeeded; otherwise, false. - */ - setFrustum(left:number,right:number,bottom:number,top:number,nearDistance:number,farDistance:number): boolean; - /** - * @description Gets the view frustum. - * @returns {Array} [boolean, number, number, number, number, number, number] - * (boolean) true if operation succeeded; otherwise, false. - * (number) A left value that will be filled during the call. - * (number) A right value that will be filled during the call. - * (number) A bottom value that will be filled during the call. - * (number) A top value that will be filled during the call. - * (number) A near distance value that will be filled during the call. - * (number) A far distance value that will be filled during the call. - */ - getFrustum(): object; - /** - * @description Computes a transform from a coordinate system to another. - * @param {CoordinateSystem} sourceSystem The coordinate system to map from. - * @param {CoordinateSystem} destinationSystem The coordinate system to map into. - * @returns {Transform} The 4x4 transformation matrix (acts on the left). - */ - getXform(sourceSystem:CoordinateSystem,destinationSystem:CoordinateSystem): Transform; - /** - * @description Extends this viewport view to include a bounding box. - Use Extents() as a quick way to set a viewport to so that bounding - volume is inside of a viewports frustum. - The view angle is used to determine the position of the camera. - * @param {number} halfViewAngleRadians 1/2 smallest subtended view angle in radians. - * @param {BoundingBox} bbox A bounding box in 3d world coordinates. - * @returns {boolean} true if the operation succeeded; otherwise, false. - */ - extents(halfViewAngleRadians:number,bbox:BoundingBox): boolean; - /** - * @description Dolly the camera location and so that the view frustum contains - all of the document objects that can be seen in view. - If the projection is perspective, the camera angle is not changed. - * @param {number} border If border > 1.0, then the frustum in enlarged by this factor - to provide a border around the view. 1.1 works well for - parallel projections; 0.0 is suggested for perspective projections. - * @returns {boolean} True if successful. - */ - dollyExtents(border:number): boolean; - /** - * @description Return a point on the central axis of the view frustum. - This point is a good choice for a general purpose target point. - * @param {number} targetDistance If targetDistance > 0.0, then the distance from the returned - point to the camera plane will be targetDistance. Note that - if the frustum is not symmetric, the distance from the - returned point to the camera location will be larger than - targetDistance. - If targetDistance == ON_UNSET_VALUE and the frustum - is valid with near > 0.0, then 0.5*(near + far) will be used - as the targetDistance. - * @returns {number[]} A point on the frustum's central axis. If the viewport or input - is not valid, then ON_3dPoint::UnsetPoint is returned. - */ - frustumCenterPoint(targetDistance:number): number[]; - /** - * @description Gets the distance from the target point to the camera plane. - Note that if the frustum is not symmetric, then this distance - is shorter than the distance from the target to the camera location. - * @param {boolean} useFrustumCenterFallback If bUseFrustumCenterFallback is false and the target point is - not valid, then ON_UNSET_VALUE is returned. - If bUseFrustumCenterFallback is true and the frustum is valid - and current target point is not valid or is behind the camera, - then 0.5*(near + far) is returned. - * @returns {number} Shortest signed distance from camera plane to target point. - If the target point is on the visible side of the camera, - a positive value is returned. ON_UNSET_VALUE is returned - when the input of view is not valid. - */ - targetDistance(useFrustumCenterFallback:boolean): number; - } -} diff --git a/public/assets/lib/vendor/three/rhino3dm/rhino3dm.js b/public/assets/lib/vendor/three/rhino3dm/rhino3dm.js deleted file mode 100644 index 8b417057..00000000 --- a/public/assets/lib/vendor/three/rhino3dm/rhino3dm.js +++ /dev/null @@ -1,21 +0,0 @@ - -var rhino3dm = (() => { - var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined; - if (typeof __filename !== 'undefined') _scriptDir = _scriptDir || __filename; - return ( -function(config) { - var rhino3dm = config || {}; - -var Module=typeof rhino3dm!="undefined"?rhino3dm:{};var readyPromiseResolve,readyPromiseReject;Module["ready"]=new Promise(function(resolve,reject){readyPromiseResolve=resolve;readyPromiseReject=reject});var moduleOverrides=Object.assign({},Module);var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var ENVIRONMENT_IS_WEB=typeof window=="object";var ENVIRONMENT_IS_WORKER=typeof importScripts=="function";var ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string";var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var read_,readAsync,readBinary,setWindowTitle;function logExceptionOnExit(e){if(e instanceof ExitStatus)return;let toLog=e;err("exiting due to exception: "+toLog)}if(ENVIRONMENT_IS_NODE){var fs=require("fs");var nodePath=require("path");if(ENVIRONMENT_IS_WORKER){scriptDirectory=nodePath.dirname(scriptDirectory)+"/"}else{scriptDirectory=__dirname+"/"}read_=(filename,binary)=>{filename=isFileURI(filename)?new URL(filename):nodePath.normalize(filename);return fs.readFileSync(filename,binary?undefined:"utf8")};readBinary=filename=>{var ret=read_(filename,true);if(!ret.buffer){ret=new Uint8Array(ret)}return ret};readAsync=(filename,onload,onerror)=>{filename=isFileURI(filename)?new URL(filename):nodePath.normalize(filename);fs.readFile(filename,function(err,data){if(err)onerror(err);else onload(data.buffer)})};if(process["argv"].length>1){thisProgram=process["argv"][1].replace(/\\/g,"/")}arguments_=process["argv"].slice(2);process["on"]("uncaughtException",function(ex){if(!(ex instanceof ExitStatus)){throw ex}});process["on"]("unhandledRejection",function(reason){throw reason});quit_=(status,toThrow)=>{if(keepRuntimeAlive()){process["exitCode"]=status;throw toThrow}logExceptionOnExit(toThrow);process["exit"](status)};Module["inspect"]=function(){return"[Emscripten Module object]"}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER){scriptDirectory=self.location.href}else if(typeof document!="undefined"&&document.currentScript){scriptDirectory=document.currentScript.src}if(_scriptDir){scriptDirectory=_scriptDir}if(scriptDirectory.indexOf("blob:")!==0){scriptDirectory=scriptDirectory.substr(0,scriptDirectory.replace(/[?#].*/,"").lastIndexOf("/")+1)}else{scriptDirectory=""}{read_=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.send(null);return xhr.responseText};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=(url,onload,onerror)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){onload(xhr.response);return}onerror()};xhr.onerror=onerror;xhr.send(null)}}setWindowTitle=title=>document.title=title}else{}var out=Module["print"]||console.log.bind(console);var err=Module["printErr"]||console.warn.bind(console);Object.assign(Module,moduleOverrides);moduleOverrides=null;if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["quit"])quit_=Module["quit"];var POINTER_SIZE=4;var wasmBinary;if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];var noExitRuntime=Module["noExitRuntime"]||true;if(typeof WebAssembly!="object"){abort("no native wasm support detected")}var wasmMemory;var ABORT=false;var EXITSTATUS;function assert(condition,text){if(!condition){abort(text)}}var UTF8Decoder=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):undefined;function UTF8ArrayToString(heapOrArray,idx,maxBytesToRead){var endIdx=idx+maxBytesToRead;var endPtr=idx;while(heapOrArray[endPtr]&&!(endPtr>=endIdx))++endPtr;if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx>10,56320|ch&1023)}}return str}function UTF8ToString(ptr,maxBytesToRead){return ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead):""}function stringToUTF8Array(str,heap,outIdx,maxBytesToWrite){if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i=55296&&u<=57343){var u1=str.charCodeAt(++i);u=65536+((u&1023)<<10)|u1&1023}if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}}heap[outIdx]=0;return outIdx-startIdx}function stringToUTF8(str,outPtr,maxBytesToWrite){return stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite)}function lengthBytesUTF8(str){var len=0;for(var i=0;i=55296&&c<=57343){len+=4;++i}else{len+=3}}return len}var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;function updateMemoryViews(){var b=wasmMemory.buffer;Module["HEAP8"]=HEAP8=new Int8Array(b);Module["HEAP16"]=HEAP16=new Int16Array(b);Module["HEAP32"]=HEAP32=new Int32Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);Module["HEAPU16"]=HEAPU16=new Uint16Array(b);Module["HEAPU32"]=HEAPU32=new Uint32Array(b);Module["HEAPF32"]=HEAPF32=new Float32Array(b);Module["HEAPF64"]=HEAPF64=new Float64Array(b)}var INITIAL_MEMORY=Module["INITIAL_MEMORY"]||16777216;var wasmTable;var __ATPRERUN__=[];var __ATINIT__=[];var __ATPOSTRUN__=[];var runtimeInitialized=false;function keepRuntimeAlive(){return noExitRuntime}function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=true;SOCKFS.root=FS.mount(SOCKFS,{},null);if(!Module["noFSInit"]&&!FS.init.initialized)FS.init();FS.ignorePermissions=false;TTY.init();callRuntimeCallbacks(__ATINIT__)}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(cb){__ATPRERUN__.unshift(cb)}function addOnInit(cb){__ATINIT__.unshift(cb)}function addOnPostRun(cb){__ATPOSTRUN__.unshift(cb)}var runDependencies=0;var runDependencyWatcher=null;var dependenciesFulfilled=null;function getUniqueRunDependency(id){return id}function addRunDependency(id){runDependencies++;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}}function removeRunDependency(id){runDependencies--;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}if(runDependencies==0){if(runDependencyWatcher!==null){clearInterval(runDependencyWatcher);runDependencyWatcher=null}if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}function abort(what){if(Module["onAbort"]){Module["onAbort"](what)}what="Aborted("+what+")";err(what);ABORT=true;EXITSTATUS=1;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject(e);throw e}var dataURIPrefix="data:application/octet-stream;base64,";function isDataURI(filename){return filename.startsWith(dataURIPrefix)}function isFileURI(filename){return filename.startsWith("file://")}var wasmBinaryFile;wasmBinaryFile="rhino3dm.wasm";if(!isDataURI(wasmBinaryFile)){wasmBinaryFile=locateFile(wasmBinaryFile)}function getBinary(file){try{if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}catch(err){abort(err)}}function getBinaryPromise(){if(!wasmBinary&&(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)){if(typeof fetch=="function"&&!isFileURI(wasmBinaryFile)){return fetch(wasmBinaryFile,{credentials:"same-origin"}).then(function(response){if(!response["ok"]){throw"failed to load wasm binary file at '"+wasmBinaryFile+"'"}return response["arrayBuffer"]()}).catch(function(){return getBinary(wasmBinaryFile)})}else{if(readAsync){return new Promise(function(resolve,reject){readAsync(wasmBinaryFile,function(response){resolve(new Uint8Array(response))},reject)})}}}return Promise.resolve().then(function(){return getBinary(wasmBinaryFile)})}function createWasm(){var info={"a":asmLibraryArg};function receiveInstance(instance,module){var exports=instance.exports;Module["asm"]=exports;wasmMemory=Module["asm"]["oa"];updateMemoryViews();wasmTable=Module["asm"]["qa"];addOnInit(Module["asm"]["pa"]);removeRunDependency("wasm-instantiate")}addRunDependency("wasm-instantiate");function receiveInstantiationResult(result){receiveInstance(result["instance"])}function instantiateArrayBuffer(receiver){return getBinaryPromise().then(function(binary){return WebAssembly.instantiate(binary,info)}).then(function(instance){return instance}).then(receiver,function(reason){err("failed to asynchronously prepare wasm: "+reason);abort(reason)})}function instantiateAsync(){if(!wasmBinary&&typeof WebAssembly.instantiateStreaming=="function"&&!isDataURI(wasmBinaryFile)&&!isFileURI(wasmBinaryFile)&&!ENVIRONMENT_IS_NODE&&typeof fetch=="function"){return fetch(wasmBinaryFile,{credentials:"same-origin"}).then(function(response){var result=WebAssembly.instantiateStreaming(response,info);return result.then(receiveInstantiationResult,function(reason){err("wasm streaming compile failed: "+reason);err("falling back to ArrayBuffer instantiation");return instantiateArrayBuffer(receiveInstantiationResult)})})}else{return instantiateArrayBuffer(receiveInstantiationResult)}}if(Module["instantiateWasm"]){try{var exports=Module["instantiateWasm"](info,receiveInstance);return exports}catch(e){err("Module.instantiateWasm callback failed with error: "+e);readyPromiseReject(e)}}instantiateAsync().catch(readyPromiseReject);return{}}var tempDouble;var tempI64;function ExitStatus(status){this.name="ExitStatus";this.message="Program terminated with exit("+status+")";this.status=status}function callRuntimeCallbacks(callbacks){while(callbacks.length>0){callbacks.shift()(Module)}}function ExceptionInfo(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24;this.set_type=function(type){HEAPU32[this.ptr+4>>2]=type};this.get_type=function(){return HEAPU32[this.ptr+4>>2]};this.set_destructor=function(destructor){HEAPU32[this.ptr+8>>2]=destructor};this.get_destructor=function(){return HEAPU32[this.ptr+8>>2]};this.set_refcount=function(refcount){HEAP32[this.ptr>>2]=refcount};this.set_caught=function(caught){caught=caught?1:0;HEAP8[this.ptr+12>>0]=caught};this.get_caught=function(){return HEAP8[this.ptr+12>>0]!=0};this.set_rethrown=function(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13>>0]=rethrown};this.get_rethrown=function(){return HEAP8[this.ptr+13>>0]!=0};this.init=function(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor);this.set_refcount(0);this.set_caught(false);this.set_rethrown(false)};this.add_ref=function(){var value=HEAP32[this.ptr>>2];HEAP32[this.ptr>>2]=value+1};this.release_ref=function(){var prev=HEAP32[this.ptr>>2];HEAP32[this.ptr>>2]=prev-1;return prev===1};this.set_adjusted_ptr=function(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr};this.get_adjusted_ptr=function(){return HEAPU32[this.ptr+16>>2]};this.get_exception_ptr=function(){var isPointer=___cxa_is_pointer_type(this.get_type());if(isPointer){return HEAPU32[this.excPtr>>2]}var adjusted=this.get_adjusted_ptr();if(adjusted!==0)return adjusted;return this.excPtr}}var exceptionLast=0;var uncaughtExceptionCount=0;function ___cxa_throw(ptr,type,destructor){var info=new ExceptionInfo(ptr);info.init(type,destructor);exceptionLast=ptr;uncaughtExceptionCount++;throw ptr}function getRandomDevice(){if(typeof crypto=="object"&&typeof crypto["getRandomValues"]=="function"){var randomBuffer=new Uint8Array(1);return()=>{crypto.getRandomValues(randomBuffer);return randomBuffer[0]}}else if(ENVIRONMENT_IS_NODE){try{var crypto_module=require("crypto");return()=>crypto_module["randomBytes"](1)[0]}catch(e){}}return()=>abort("randomDevice")}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.substr(-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.substr(0,dir.length-1)}return root+dir},basename:path=>{if(path==="/")return"/";path=PATH.normalize(path);path=path.replace(/\/$/,"");var lastSlash=path.lastIndexOf("/");if(lastSlash===-1)return path;return path.substr(lastSlash+1)},join:function(){var paths=Array.prototype.slice.call(arguments);return PATH.normalize(paths.join("/"))},join2:(l,r)=>{return PATH.normalize(l+"/"+r)}};var PATH_FS={resolve:function(){var resolvedPath="",resolvedAbsolute=false;for(var i=arguments.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?arguments[i]:FS.cwd();if(typeof path!="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!path){return""}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=PATH.isAbs(path)}resolvedPath=PATH.normalizeArray(resolvedPath.split("/").filter(p=>!!p),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."},relative:(from,to)=>{from=PATH_FS.resolve(from).substr(1);to=PATH_FS.resolve(to).substr(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;i0?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 TTY={ttys:[],init:function(){},shutdown:function(){},register:function(dev,ops){TTY.ttys[dev]={input:[],output:[],ops:ops};FS.registerDevice(dev,TTY.stream_ops)},stream_ops:{open:function(stream){var tty=TTY.ttys[stream.node.rdev];if(!tty){throw new FS.ErrnoError(43)}stream.tty=tty;stream.seekable=false},close:function(stream){stream.tty.ops.fsync(stream.tty)},fsync:function(stream){stream.tty.ops.fsync(stream.tty)},read:function(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.get_char){throw new FS.ErrnoError(60)}var bytesRead=0;for(var i=0;i0){result=buf.slice(0,bytesRead).toString("utf-8")}else{result=null}}else if(typeof window!="undefined"&&typeof window.prompt=="function"){result=window.prompt("Input: ");if(result!==null){result+="\n"}}else if(typeof readline=="function"){result=readline();if(result!==null){result+="\n"}}if(!result){return null}tty.input=intArrayFromString(result,true)}return tty.input.shift()},put_char:function(tty,val){if(val===null||val===10){out(UTF8ArrayToString(tty.output,0));tty.output=[]}else{if(val!=0)tty.output.push(val)}},fsync:function(tty){if(tty.output&&tty.output.length>0){out(UTF8ArrayToString(tty.output,0));tty.output=[]}}},default_tty1_ops:{put_char:function(tty,val){if(val===null||val===10){err(UTF8ArrayToString(tty.output,0));tty.output=[]}else{if(val!=0)tty.output.push(val)}},fsync:function(tty){if(tty.output&&tty.output.length>0){err(UTF8ArrayToString(tty.output,0));tty.output=[]}}}};function mmapAlloc(size){abort()}var MEMFS={ops_table:null,mount:function(mount){return MEMFS.createNode(null,"/",16384|511,0)},createNode:function(parent,name,mode,dev){if(FS.isBlkdev(mode)||FS.isFIFO(mode)){throw new FS.ErrnoError(63)}if(!MEMFS.ops_table){MEMFS.ops_table={dir:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,lookup:MEMFS.node_ops.lookup,mknod:MEMFS.node_ops.mknod,rename:MEMFS.node_ops.rename,unlink:MEMFS.node_ops.unlink,rmdir:MEMFS.node_ops.rmdir,readdir:MEMFS.node_ops.readdir,symlink:MEMFS.node_ops.symlink},stream:{llseek:MEMFS.stream_ops.llseek}},file:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:{llseek:MEMFS.stream_ops.llseek,read:MEMFS.stream_ops.read,write:MEMFS.stream_ops.write,allocate:MEMFS.stream_ops.allocate,mmap:MEMFS.stream_ops.mmap,msync:MEMFS.stream_ops.msync}},link:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,readlink:MEMFS.node_ops.readlink},stream:{}},chrdev:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:FS.chrdev_stream_ops}}}var node=FS.createNode(parent,name,mode,dev);if(FS.isDir(node.mode)){node.node_ops=MEMFS.ops_table.dir.node;node.stream_ops=MEMFS.ops_table.dir.stream;node.contents={}}else if(FS.isFile(node.mode)){node.node_ops=MEMFS.ops_table.file.node;node.stream_ops=MEMFS.ops_table.file.stream;node.usedBytes=0;node.contents=null}else if(FS.isLink(node.mode)){node.node_ops=MEMFS.ops_table.link.node;node.stream_ops=MEMFS.ops_table.link.stream}else if(FS.isChrdev(node.mode)){node.node_ops=MEMFS.ops_table.chrdev.node;node.stream_ops=MEMFS.ops_table.chrdev.stream}node.timestamp=Date.now();if(parent){parent.contents[name]=node;parent.timestamp=node.timestamp}return node},getFileDataAsTypedArray:function(node){if(!node.contents)return new Uint8Array(0);if(node.contents.subarray)return node.contents.subarray(0,node.usedBytes);return new Uint8Array(node.contents)},expandFileStorage:function(node,newCapacity){var prevCapacity=node.contents?node.contents.length:0;if(prevCapacity>=newCapacity)return;var CAPACITY_DOUBLING_MAX=1024*1024;newCapacity=Math.max(newCapacity,prevCapacity*(prevCapacity>>0);if(prevCapacity!=0)newCapacity=Math.max(newCapacity,256);var oldContents=node.contents;node.contents=new Uint8Array(newCapacity);if(node.usedBytes>0)node.contents.set(oldContents.subarray(0,node.usedBytes),0)},resizeFileStorage:function(node,newSize){if(node.usedBytes==newSize)return;if(newSize==0){node.contents=null;node.usedBytes=0}else{var oldContents=node.contents;node.contents=new Uint8Array(newSize);if(oldContents){node.contents.set(oldContents.subarray(0,Math.min(newSize,node.usedBytes)))}node.usedBytes=newSize}},node_ops:{getattr:function(node){var attr={};attr.dev=FS.isChrdev(node.mode)?node.id:1;attr.ino=node.id;attr.mode=node.mode;attr.nlink=1;attr.uid=0;attr.gid=0;attr.rdev=node.rdev;if(FS.isDir(node.mode)){attr.size=4096}else if(FS.isFile(node.mode)){attr.size=node.usedBytes}else if(FS.isLink(node.mode)){attr.size=node.link.length}else{attr.size=0}attr.atime=new Date(node.timestamp);attr.mtime=new Date(node.timestamp);attr.ctime=new Date(node.timestamp);attr.blksize=4096;attr.blocks=Math.ceil(attr.size/attr.blksize);return attr},setattr:function(node,attr){if(attr.mode!==undefined){node.mode=attr.mode}if(attr.timestamp!==undefined){node.timestamp=attr.timestamp}if(attr.size!==undefined){MEMFS.resizeFileStorage(node,attr.size)}},lookup:function(parent,name){throw FS.genericErrors[44]},mknod:function(parent,name,mode,dev){return MEMFS.createNode(parent,name,mode,dev)},rename:function(old_node,new_dir,new_name){if(FS.isDir(old_node.mode)){var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(new_node){for(var i in new_node.contents){throw new FS.ErrnoError(55)}}}delete old_node.parent.contents[old_node.name];old_node.parent.timestamp=Date.now();old_node.name=new_name;new_dir.contents[new_name]=old_node;new_dir.timestamp=old_node.parent.timestamp;old_node.parent=new_dir},unlink:function(parent,name){delete parent.contents[name];parent.timestamp=Date.now()},rmdir:function(parent,name){var node=FS.lookupNode(parent,name);for(var i in node.contents){throw new FS.ErrnoError(55)}delete parent.contents[name];parent.timestamp=Date.now()},readdir:function(node){var entries=[".",".."];for(var key in node.contents){if(!node.contents.hasOwnProperty(key)){continue}entries.push(key)}return entries},symlink:function(parent,newname,oldpath){var node=MEMFS.createNode(parent,newname,511|40960,0);node.link=oldpath;return node},readlink:function(node){if(!FS.isLink(node.mode)){throw new FS.ErrnoError(28)}return node.link}},stream_ops:{read:function(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=stream.node.usedBytes)return 0;var size=Math.min(stream.node.usedBytes-position,length);if(size>8&&contents.subarray){buffer.set(contents.subarray(position,position+size),offset)}else{for(var i=0;i0||position+length{assert(arrayBuffer,'Loading data file "'+url+'" failed (no arrayBuffer).');onload(new Uint8Array(arrayBuffer));if(dep)removeRunDependency(dep)},event=>{if(onerror){onerror()}else{throw'Loading data file "'+url+'" failed.'}});if(dep)addRunDependency(dep)}var FS={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:false,ignorePermissions:true,ErrnoError:null,genericErrors:{},filesystems:null,syncFSRequests:0,lookupPath:(path,opts={})=>{path=PATH_FS.resolve(path);if(!path)return{path:"",node:null};var defaults={follow_mount:true,recurse_count:0};opts=Object.assign(defaults,opts);if(opts.recurse_count>8){throw new FS.ErrnoError(32)}var parts=path.split("/").filter(p=>!!p);var current=FS.root;var current_path="/";for(var i=0;i40){throw new FS.ErrnoError(32)}}}}return{path:current_path,node:current}},getPath:node=>{var path;while(true){if(FS.isRoot(node)){var mount=node.mount.mountpoint;if(!path)return mount;return mount[mount.length-1]!=="/"?mount+"/"+path:mount+path}path=path?node.name+"/"+path:node.name;node=node.parent}},hashName:(parentid,name)=>{var hash=0;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,parent)}var hash=FS.hashName(parent.id,name);for(var node=FS.nameTable[hash];node;node=node.name_next){var nodeName=node.name;if(node.parent.id===parent.id&&nodeName===name){return node}}return FS.lookup(parent,name)},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},flagModes:{"r":0,"r+":2,"w":577,"w+":578,"a":1089,"a+":1090},modeStringToFlags:str=>{var flags=FS.flagModes[str];if(typeof flags=="undefined"){throw new Error("Unknown file open mode: "+str)}return flags},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}else if(perms.includes("w")&&!(node.mode&146)){return 2}else if(perms.includes("x")&&!(node.mode&73)){return 2}return 0},mayLookup:dir=>{var errCode=FS.nodePermissions(dir,"x");if(errCode)return errCode;if(!dir.node_ops.lookup)return 2;return 0},mayCreate:(dir,name)=>{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}else if(FS.isDir(node.mode)){if(FS.flagsToPermissionString(flags)!=="r"||flags&512){return 31}}return FS.nodePermissions(node,FS.flagsToPermissionString(flags))},MAX_OPEN_FDS:4096,nextfd:(fd_start=0,fd_end=FS.MAX_OPEN_FDS)=>{for(var fd=fd_start;fd<=fd_end;fd++){if(!FS.streams[fd]){return fd}}throw new FS.ErrnoError(33)},getStream:fd=>FS.streams[fd],createStream:(stream,fd_start,fd_end)=>{if(!FS.FSStream){FS.FSStream=function(){this.shared={}};FS.FSStream.prototype={};Object.defineProperties(FS.FSStream.prototype,{object:{get:function(){return this.node},set:function(val){this.node=val}},isRead:{get:function(){return(this.flags&2097155)!==1}},isWrite:{get:function(){return(this.flags&2097155)!==0}},isAppend:{get:function(){return this.flags&1024}},flags:{get:function(){return this.shared.flags},set:function(val){this.shared.flags=val}},position:{get:function(){return this.shared.position},set:function(val){this.shared.position=val}}})}stream=Object.assign(new FS.FSStream,stream);var fd=FS.nextfd(fd_start,fd_end);stream.fd=fd;FS.streams[fd]=stream;return stream},closeStream:fd=>{FS.streams[fd]=null},chrdev_stream_ops:{open:stream=>{var device=FS.getDevice(stream.node.rdev);stream.stream_ops=device.stream_ops;if(stream.stream_ops.open){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.apply(check,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)}}mounts.forEach(mount=>{if(!mount.type.syncfs){return done(null)}mount.type.syncfs(mount,populate,done)})},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:type,opts:opts,mountpoint: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);Object.keys(FS.nameTable).forEach(hash=>{var current=FS.nameTable[hash];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||name==="."||name===".."){throw new FS.ErrnoError(28)}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)},create:(path,mode)=>{mode=mode!==undefined?mode:438;mode&=4095;mode|=32768;return FS.mknod(path,mode,0)},mkdir:(path,mode)=>{mode=mode!==undefined?mode:511;mode&=511|512;mode|=16384;return FS.mknod(path,mode,0)},mkdirTree:(path,mode)=>{var dirs=path.split("/");var d="";for(var i=0;i{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)}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;if(!node.node_ops.readdir){throw new FS.ErrnoError(54)}return node.node_ops.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 PATH_FS.resolve(FS.getPath(link.parent),link.node_ops.readlink(link))},stat:(path,dontFollow)=>{var lookup=FS.lookupPath(path,{follow:!dontFollow});var node=lookup.node;if(!node){throw new FS.ErrnoError(44)}if(!node.node_ops.getattr){throw new FS.ErrnoError(63)}return node.node_ops.getattr(node)},lstat:path=>{return FS.stat(path,true)},chmod:(path,mode,dontFollow)=>{var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}if(!node.node_ops.setattr){throw new FS.ErrnoError(63)}node.node_ops.setattr(node,{mode:mode&4095|node.mode&~4095,timestamp:Date.now()})},lchmod:(path,mode)=>{FS.chmod(path,mode,true)},fchmod:(fd,mode)=>{var stream=FS.getStream(fd);if(!stream){throw new FS.ErrnoError(8)}FS.chmod(stream.node,mode)},chown:(path,uid,gid,dontFollow)=>{var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}if(!node.node_ops.setattr){throw new FS.ErrnoError(63)}node.node_ops.setattr(node,{timestamp:Date.now()})},lchown:(path,uid,gid)=>{FS.chown(path,uid,gid,true)},fchown:(fd,uid,gid)=>{var stream=FS.getStream(fd);if(!stream){throw new FS.ErrnoError(8)}FS.chown(stream.node,uid,gid)},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}if(!node.node_ops.setattr){throw new FS.ErrnoError(63)}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)}node.node_ops.setattr(node,{size:len,timestamp:Date.now()})},ftruncate:(fd,len)=>{var stream=FS.getStream(fd);if(!stream){throw new FS.ErrnoError(8)}if((stream.flags&2097155)===0){throw new FS.ErrnoError(28)}FS.truncate(stream.node,len)},utime:(path,atime,mtime)=>{var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;node.node_ops.setattr(node,{timestamp:Math.max(atime,mtime)})},open:(path,flags,mode)=>{if(path===""){throw new FS.ErrnoError(44)}flags=typeof flags=="string"?FS.modeStringToFlags(flags):flags;mode=typeof mode=="undefined"?438:mode;if(flags&64){mode=mode&4095|32768}else{mode=0}var node;if(typeof path=="object"){node=path}else{path=PATH.normalize(path);try{var lookup=FS.lookupPath(path,{follow:!(flags&131072)});node=lookup.node}catch(e){}}var created=false;if(flags&64){if(node){if(flags&128){throw new FS.ErrnoError(20)}}else{node=FS.mknod(path,mode,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:node,path:FS.getPath(node),flags:flags,seekable:true,position:0,stream_ops:node.stream_ops,ungotten:[],error:false});if(stream.stream_ops.open){stream.stream_ops.open(stream)}if(Module["logReadFiles"]&&!(flags&1)){if(!FS.readFiles)FS.readFiles={};if(!(path in FS.readFiles)){FS.readFiles[path]=1}}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},allocate:(stream,offset,length)=>{if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(offset<0||length<=0){throw new FS.ErrnoError(28)}if((stream.flags&2097155)===0){throw new FS.ErrnoError(8)}if(!FS.isFile(stream.node.mode)&&!FS.isDir(stream.node.mode)){throw new FS.ErrnoError(43)}if(!stream.stream_ops.allocate){throw new FS.ErrnoError(138)}stream.stream_ops.allocate(stream,offset,length)},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)}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)},munmap:stream=>0,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"){throw new Error('Invalid encoding type "'+opts.encoding+'"')}var ret;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"){ret=UTF8ArrayToString(buf,0)}else if(opts.encoding==="binary"){ret=buf}FS.close(stream);return ret},writeFile:(path,data,opts={})=>{opts.flags=opts.flags||577;var stream=FS.open(path,opts.flags,opts.mode);if(typeof data=="string"){var buf=new Uint8Array(lengthBytesUTF8(data)+1);var actualNumBytes=stringToUTF8Array(data,buf,0,buf.length);FS.write(stream,buf,0,actualNumBytes,undefined,opts.canOwn)}else if(ArrayBuffer.isView(data)){FS.write(stream,data,0,data.byteLength,undefined,opts.canOwn)}else{throw new Error("Unsupported data type")}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});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 random_device=getRandomDevice();FS.createDevice("/dev","random",random_device);FS.createDevice("/dev","urandom",random_device);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",16384|511,73);node.node_ops={lookup:(parent,name)=>{var fd=+name;var stream=FS.getStream(fd);if(!stream)throw new FS.ErrnoError(8);var ret={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>stream.path}};ret.parent=ret;return ret}};return node}},{},"/proc/self/fd")},createStandardStreams:()=>{if(Module["stdin"]){FS.createDevice("/dev","stdin",Module["stdin"])}else{FS.symlink("/dev/tty","/dev/stdin")}if(Module["stdout"]){FS.createDevice("/dev","stdout",null,Module["stdout"])}else{FS.symlink("/dev/tty","/dev/stdout")}if(Module["stderr"]){FS.createDevice("/dev","stderr",null,Module["stderr"])}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)},ensureErrnoError:()=>{if(FS.ErrnoError)return;FS.ErrnoError=function ErrnoError(errno,node){this.node=node;this.setErrno=function(errno){this.errno=errno};this.setErrno(errno);this.message="FS error"};FS.ErrnoError.prototype=new Error;FS.ErrnoError.prototype.constructor=FS.ErrnoError;[44].forEach(code=>{FS.genericErrors[code]=new FS.ErrnoError(code);FS.genericErrors[code].stack=""})},staticInit:()=>{FS.ensureErrnoError();FS.nameTable=new Array(4096);FS.mount(MEMFS,{},"/");FS.createDefaultDirectories();FS.createDefaultDevices();FS.createSpecialDirectories();FS.filesystems={"MEMFS":MEMFS}},init:(input,output,error)=>{FS.init.initialized=true;FS.ensureErrnoError();Module["stdin"]=input||Module["stdin"];Module["stdout"]=output||Module["stdout"];Module["stderr"]=error||Module["stderr"];FS.createStandardStreams()},quit:()=>{FS.init.initialized=false;for(var i=0;i{var mode=0;if(canRead)mode|=292|73;if(canWrite)mode|=146;return mode},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){}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){if(typeof data=="string"){var arr=new Array(data.length);for(var i=0,len=data.length;i{var path=PATH.join2(typeof parent=="string"?parent:FS.getPath(parent),name);var mode=FS.getMode(!!input,!!output);if(!FS.createDevice.major)FS.createDevice.major=64;var dev=FS.makedev(FS.createDevice.major++,0);FS.registerDevice(dev,{open:stream=>{stream.seekable=false},close:stream=>{if(output&&output.buffer&&output.buffer.length){output(10)}},read:(stream,buffer,offset,length,pos)=>{var bytesRead=0;for(var i=0;i{for(var i=0;i{if(obj.isDevice||obj.isFolder||obj.link||obj.contents)return true;if(typeof XMLHttpRequest!="undefined"){throw new Error("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.")}else if(read_){try{obj.contents=intArrayFromString(read_(obj.url),true);obj.usedBytes=obj.contents.length}catch(e){throw new FS.ErrnoError(29)}}else{throw new Error("Cannot load without read() or XMLHttpRequest.")}},createLazyFile:(parent,name,url,canRead,canWrite)=>{function LazyUint8Array(){this.lengthKnown=false;this.chunks=[]}LazyUint8Array.prototype.get=function LazyUint8Array_get(idx){if(idx>this.length-1||idx<0){return undefined}var chunkOffset=idx%this.chunkSize;var chunkNum=idx/this.chunkSize|0;return this.getter(chunkNum)[chunkOffset]};LazyUint8Array.prototype.setDataGetter=function LazyUint8Array_setDataGetter(getter){this.getter=getter};LazyUint8Array.prototype.cacheLength=function LazyUint8Array_cacheLength(){var xhr=new XMLHttpRequest;xhr.open("HEAD",url,false);xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))throw new Error("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)throw new Error("invalid range ("+from+", "+to+") or no bytes requested!");if(to>datalength-1)throw new Error("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))throw new Error("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")throw new Error("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};if(typeof XMLHttpRequest!="undefined"){if(!ENVIRONMENT_IS_WORKER)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var lazyArray=new LazyUint8Array;Object.defineProperties(lazyArray,{length:{get:function(){if(!this.lengthKnown){this.cacheLength()}return this._length}},chunkSize:{get:function(){if(!this.lengthKnown){this.cacheLength()}return this._chunkSize}}});var properties={isDevice:false,contents:lazyArray}}else{var properties={isDevice:false,url: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={};var keys=Object.keys(node.stream_ops);keys.forEach(key=>{var fn=node.stream_ops[key];stream_ops[key]=function forceLoadLazyFile(){FS.forceLoadFile(node);return fn.apply(null,arguments)}});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:ptr,allocated:true}};node.stream_ops=stream_ops;return node},createPreloadedFile:(parent,name,url,canRead,canWrite,onload,onerror,dontCreateFile,canOwn,preFinish)=>{var fullname=name?PATH_FS.resolve(PATH.join2(parent,name)):parent;var dep=getUniqueRunDependency("cp "+fullname);function processData(byteArray){function finish(byteArray){if(preFinish)preFinish();if(!dontCreateFile){FS.createDataFile(parent,name,byteArray,canRead,canWrite,canOwn)}if(onload)onload();removeRunDependency(dep)}if(Browser.handledByPreloadPlugin(byteArray,fullname,finish,()=>{if(onerror)onerror();removeRunDependency(dep)})){return}finish(byteArray)}addRunDependency(dep);if(typeof url=="string"){asyncLoad(url,byteArray=>processData(byteArray),onerror)}else{processData(url)}},indexedDB:()=>{return window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB},DB_NAME:()=>{return"EM_FS_"+window.location.pathname},DB_VERSION:20,DB_STORE_NAME:"FILE_DATA",saveFilesToDB:(paths,onload,onerror)=>{onload=onload||(()=>{});onerror=onerror||(()=>{});var indexedDB=FS.indexedDB();try{var openRequest=indexedDB.open(FS.DB_NAME(),FS.DB_VERSION)}catch(e){return onerror(e)}openRequest.onupgradeneeded=()=>{out("creating db");var db=openRequest.result;db.createObjectStore(FS.DB_STORE_NAME)};openRequest.onsuccess=()=>{var db=openRequest.result;var transaction=db.transaction([FS.DB_STORE_NAME],"readwrite");var files=transaction.objectStore(FS.DB_STORE_NAME);var ok=0,fail=0,total=paths.length;function finish(){if(fail==0)onload();else onerror()}paths.forEach(path=>{var putRequest=files.put(FS.analyzePath(path).object.contents,path);putRequest.onsuccess=()=>{ok++;if(ok+fail==total)finish()};putRequest.onerror=()=>{fail++;if(ok+fail==total)finish()}});transaction.onerror=onerror};openRequest.onerror=onerror},loadFilesFromDB:(paths,onload,onerror)=>{onload=onload||(()=>{});onerror=onerror||(()=>{});var indexedDB=FS.indexedDB();try{var openRequest=indexedDB.open(FS.DB_NAME(),FS.DB_VERSION)}catch(e){return onerror(e)}openRequest.onupgradeneeded=onerror;openRequest.onsuccess=()=>{var db=openRequest.result;try{var transaction=db.transaction([FS.DB_STORE_NAME],"readonly")}catch(e){onerror(e);return}var files=transaction.objectStore(FS.DB_STORE_NAME);var ok=0,fail=0,total=paths.length;function finish(){if(fail==0)onload();else onerror()}paths.forEach(path=>{var getRequest=files.get(path);getRequest.onsuccess=()=>{if(FS.analyzePath(path).exists){FS.unlink(path)}FS.createDataFile(PATH.dirname(path),PATH.basename(path),getRequest.result,true,true,true);ok++;if(ok+fail==total)finish()};getRequest.onerror=()=>{fail++;if(ok+fail==total)finish()}});transaction.onerror=onerror};openRequest.onerror=onerror}};var SOCKFS={mount:function(mount){Module["websocket"]=Module["websocket"]&&"object"===typeof Module["websocket"]?Module["websocket"]:{};Module["websocket"]._callbacks={};Module["websocket"]["on"]=function(event,callback){if("function"===typeof callback){this._callbacks[event]=callback}return this};Module["websocket"].emit=function(event,param){if("function"===typeof this._callbacks[event]){this._callbacks[event].call(this,param)}};return FS.createNode(null,"/",16384|511,0)},createSocket:function(family,type,protocol){type&=~526336;var streaming=type==1;if(streaming&&protocol&&protocol!=6){throw new FS.ErrnoError(66)}var sock={family:family,type:type,protocol:protocol,server:null,error:null,peers:{},pending:[],recv_queue:[],sock_ops:SOCKFS.websocket_sock_ops};var name=SOCKFS.nextname();var node=FS.createNode(SOCKFS.root,name,49152,0);node.sock=sock;var stream=FS.createStream({path:name,node:node,flags:2,seekable:false,stream_ops:SOCKFS.stream_ops});sock.stream=stream;return sock},getSocket:function(fd){var stream=FS.getStream(fd);if(!stream||!FS.isSocket(stream.node.mode)){return null}return stream.node.sock},stream_ops:{poll:function(stream){var sock=stream.node.sock;return sock.sock_ops.poll(sock)},ioctl:function(stream,request,varargs){var sock=stream.node.sock;return sock.sock_ops.ioctl(sock,request,varargs)},read:function(stream,buffer,offset,length,position){var sock=stream.node.sock;var msg=sock.sock_ops.recvmsg(sock,length);if(!msg){return 0}buffer.set(msg.buffer,offset);return msg.buffer.length},write:function(stream,buffer,offset,length,position){var sock=stream.node.sock;return sock.sock_ops.sendmsg(sock,buffer,offset,length)},close:function(stream){var sock=stream.node.sock;sock.sock_ops.close(sock)}},nextname:function(){if(!SOCKFS.nextname.current){SOCKFS.nextname.current=0}return"socket["+SOCKFS.nextname.current+++"]"},websocket_sock_ops:{createPeer:function(sock,addr,port){var ws;if(typeof addr=="object"){ws=addr;addr=null;port=null}if(ws){if(ws._socket){addr=ws._socket.remoteAddress;port=ws._socket.remotePort}else{var result=/ws[s]?:\/\/([^:]+):(\d+)/.exec(ws.url);if(!result){throw new Error("WebSocket URL must be in the format ws(s)://address:port")}addr=result[1];port=parseInt(result[2],10)}}else{try{var runtimeConfig=Module["websocket"]&&"object"===typeof Module["websocket"];var url="ws:#".replace("#","//");if(runtimeConfig){if("string"===typeof Module["websocket"]["url"]){url=Module["websocket"]["url"]}}if(url==="ws://"||url==="wss://"){var parts=addr.split("/");url=url+parts[0]+":"+port+"/"+parts.slice(1).join("/")}var subProtocols="binary";if(runtimeConfig){if("string"===typeof Module["websocket"]["subprotocol"]){subProtocols=Module["websocket"]["subprotocol"]}}var opts=undefined;if(subProtocols!=="null"){subProtocols=subProtocols.replace(/^ +| +$/g,"").split(/ *, */);opts=subProtocols}if(runtimeConfig&&null===Module["websocket"]["subprotocol"]){subProtocols="null";opts=undefined}var WebSocketConstructor;if(ENVIRONMENT_IS_NODE){WebSocketConstructor=require("ws")}else{WebSocketConstructor=WebSocket}ws=new WebSocketConstructor(url,opts);ws.binaryType="arraybuffer"}catch(e){throw new FS.ErrnoError(23)}}var peer={addr:addr,port:port,socket:ws,dgram_send_queue:[]};SOCKFS.websocket_sock_ops.addPeer(sock,peer);SOCKFS.websocket_sock_ops.handlePeerEvents(sock,peer);if(sock.type===2&&typeof sock.sport!="undefined"){peer.dgram_send_queue.push(new Uint8Array([255,255,255,255,"p".charCodeAt(0),"o".charCodeAt(0),"r".charCodeAt(0),"t".charCodeAt(0),(sock.sport&65280)>>8,sock.sport&255]))}return peer},getPeer:function(sock,addr,port){return sock.peers[addr+":"+port]},addPeer:function(sock,peer){sock.peers[peer.addr+":"+peer.port]=peer},removePeer:function(sock,peer){delete sock.peers[peer.addr+":"+peer.port]},handlePeerEvents:function(sock,peer){var first=true;var handleOpen=function(){Module["websocket"].emit("open",sock.stream.fd);try{var queued=peer.dgram_send_queue.shift();while(queued){peer.socket.send(queued);queued=peer.dgram_send_queue.shift()}}catch(e){peer.socket.close()}};function handleMessage(data){if(typeof data=="string"){var encoder=new TextEncoder;data=encoder.encode(data)}else{assert(data.byteLength!==undefined);if(data.byteLength==0){return}data=new Uint8Array(data)}var wasfirst=first;first=false;if(wasfirst&&data.length===10&&data[0]===255&&data[1]===255&&data[2]===255&&data[3]===255&&data[4]==="p".charCodeAt(0)&&data[5]==="o".charCodeAt(0)&&data[6]==="r".charCodeAt(0)&&data[7]==="t".charCodeAt(0)){var newport=data[8]<<8|data[9];SOCKFS.websocket_sock_ops.removePeer(sock,peer);peer.port=newport;SOCKFS.websocket_sock_ops.addPeer(sock,peer);return}sock.recv_queue.push({addr:peer.addr,port:peer.port,data:data});Module["websocket"].emit("message",sock.stream.fd)}if(ENVIRONMENT_IS_NODE){peer.socket.on("open",handleOpen);peer.socket.on("message",function(data,isBinary){if(!isBinary){return}handleMessage(new Uint8Array(data).buffer)});peer.socket.on("close",function(){Module["websocket"].emit("close",sock.stream.fd)});peer.socket.on("error",function(error){sock.error=14;Module["websocket"].emit("error",[sock.stream.fd,sock.error,"ECONNREFUSED: Connection refused"])})}else{peer.socket.onopen=handleOpen;peer.socket.onclose=function(){Module["websocket"].emit("close",sock.stream.fd)};peer.socket.onmessage=function peer_socket_onmessage(event){handleMessage(event.data)};peer.socket.onerror=function(error){sock.error=14;Module["websocket"].emit("error",[sock.stream.fd,sock.error,"ECONNREFUSED: Connection refused"])}}},poll:function(sock){if(sock.type===1&&sock.server){return sock.pending.length?64|1:0}var mask=0;var dest=sock.type===1?SOCKFS.websocket_sock_ops.getPeer(sock,sock.daddr,sock.dport):null;if(sock.recv_queue.length||!dest||dest&&dest.socket.readyState===dest.socket.CLOSING||dest&&dest.socket.readyState===dest.socket.CLOSED){mask|=64|1}if(!dest||dest&&dest.socket.readyState===dest.socket.OPEN){mask|=4}if(dest&&dest.socket.readyState===dest.socket.CLOSING||dest&&dest.socket.readyState===dest.socket.CLOSED){mask|=16}return mask},ioctl:function(sock,request,arg){switch(request){case 21531:var bytes=0;if(sock.recv_queue.length){bytes=sock.recv_queue[0].data.length}HEAP32[arg>>2]=bytes;return 0;default:return 28}},close:function(sock){if(sock.server){try{sock.server.close()}catch(e){}sock.server=null}var peers=Object.keys(sock.peers);for(var i=0;i>2]=value;return value}function inetNtop4(addr){return(addr&255)+"."+(addr>>8&255)+"."+(addr>>16&255)+"."+(addr>>24&255)}function inetNtop6(ints){var str="";var word=0;var longest=0;var lastzero=0;var zstart=0;var len=0;var i=0;var parts=[ints[0]&65535,ints[0]>>16,ints[1]&65535,ints[1]>>16,ints[2]&65535,ints[2]>>16,ints[3]&65535,ints[3]>>16];var hasipv4=true;var v4part="";for(i=0;i<5;i++){if(parts[i]!==0){hasipv4=false;break}}if(hasipv4){v4part=inetNtop4(parts[6]|parts[7]<<16);if(parts[5]===-1){str="::ffff:";str+=v4part;return str}if(parts[5]===0){str="::";if(v4part==="0.0.0.0")v4part="";if(v4part==="0.0.0.1")v4part="1";str+=v4part;return str}}for(word=0;word<8;word++){if(parts[word]===0){if(word-lastzero>1){len=0}lastzero=word;len++}if(len>longest){longest=len;zstart=word-longest+1}}for(word=0;word<8;word++){if(longest>1){if(parts[word]===0&&word>=zstart&&word>1];var port=_ntohs(HEAPU16[sa+2>>1]);var addr;switch(family){case 2:if(salen!==16){return{errno:28}}addr=HEAP32[sa+4>>2];addr=inetNtop4(addr);break;case 10:if(salen!==28){return{errno:28}}addr=[HEAP32[sa+8>>2],HEAP32[sa+12>>2],HEAP32[sa+16>>2],HEAP32[sa+20>>2]];addr=inetNtop6(addr);break;default:return{errno:5}}return{family:family,addr:addr,port:port}}function 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}function jstoi_q(str){return parseInt(str)}function 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]=jstoi_q(words[words.length-4])+jstoi_q(words[words.length-3])*256;words[words.length-3]=jstoi_q(words[words.length-2])+jstoi_q(words[words.length-1])*256;words=words.slice(0,words.length-2)}else{words=str.split(":")}offset=0;z=0;for(w=0;w>2]=stat.dev;HEAP32[buf+8>>2]=stat.ino;HEAP32[buf+12>>2]=stat.mode;HEAPU32[buf+16>>2]=stat.nlink;HEAP32[buf+20>>2]=stat.uid;HEAP32[buf+24>>2]=stat.gid;HEAP32[buf+28>>2]=stat.rdev;tempI64=[stat.size>>>0,(tempDouble=stat.size,+Math.abs(tempDouble)>=1?tempDouble>0?(Math.min(+Math.floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+40>>2]=tempI64[0],HEAP32[buf+44>>2]=tempI64[1];HEAP32[buf+48>>2]=4096;HEAP32[buf+52>>2]=stat.blocks;var atime=stat.atime.getTime();var mtime=stat.mtime.getTime();var ctime=stat.ctime.getTime();tempI64=[Math.floor(atime/1e3)>>>0,(tempDouble=Math.floor(atime/1e3),+Math.abs(tempDouble)>=1?tempDouble>0?(Math.min(+Math.floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+56>>2]=tempI64[0],HEAP32[buf+60>>2]=tempI64[1];HEAPU32[buf+64>>2]=atime%1e3*1e3;tempI64=[Math.floor(mtime/1e3)>>>0,(tempDouble=Math.floor(mtime/1e3),+Math.abs(tempDouble)>=1?tempDouble>0?(Math.min(+Math.floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+72>>2]=tempI64[0],HEAP32[buf+76>>2]=tempI64[1];HEAPU32[buf+80>>2]=mtime%1e3*1e3;tempI64=[Math.floor(ctime/1e3)>>>0,(tempDouble=Math.floor(ctime/1e3),+Math.abs(tempDouble)>=1?tempDouble>0?(Math.min(+Math.floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+88>>2]=tempI64[0],HEAP32[buf+92>>2]=tempI64[1];HEAPU32[buf+96>>2]=ctime%1e3*1e3;tempI64=[stat.ino>>>0,(tempDouble=stat.ino,+Math.abs(tempDouble)>=1?tempDouble>0?(Math.min(+Math.floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+104>>2]=tempI64[0],HEAP32[buf+108>>2]=tempI64[1];return 0},doMsync:function(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)},varargs:undefined,get:function(){SYSCALLS.varargs+=4;var ret=HEAP32[SYSCALLS.varargs-4>>2];return ret},getStr:function(ptr){var ret=UTF8ToString(ptr);return ret},getStreamFromFD:function(fd){var stream=FS.getStream(fd);if(!stream)throw new FS.ErrnoError(8);return stream}};function ___syscall_connect(fd,addr,addrlen){try{var sock=getSocketFromFD(fd);var info=getSocketAddress(addr,addrlen);sock.sock_ops.connect(sock,info.addr,info.port);return 0}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function ___syscall_faccessat(dirfd,path,amode,flags){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 instanceof FS.ErrnoError))throw e;return-e.errno}}function ___syscall_fcntl64(fd,cmd,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(cmd){case 0:{var arg=SYSCALLS.get();if(arg<0){return-28}var newStream;newStream=FS.createStream(stream,arg);return newStream.fd}case 1:case 2:return 0;case 3:return stream.flags;case 4:{var arg=SYSCALLS.get();stream.flags|=arg;return 0}case 5:{var arg=SYSCALLS.get();var offset=0;HEAP16[arg+offset>>1]=2;return 0}case 6:case 7:return 0;case 16:case 8:return-28;case 9:setErrNo(28);return-1;default:{return-28}}}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function ___syscall_fstat64(fd,buf){try{var stream=SYSCALLS.getStreamFromFD(fd);return SYSCALLS.doStat(FS.stat,stream.path,buf)}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function convertI32PairToI53Checked(lo,hi){return hi+2097152>>>0<4194305-!!lo?(lo>>>0)+hi*4294967296:NaN}function ___syscall_ftruncate64(fd,length_low,length_high){try{var length=convertI32PairToI53Checked(length_low,length_high);if(isNaN(length))return-61;FS.ftruncate(fd,length);return 0}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function ___syscall_ioctl(fd,op,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(op){case 21509:case 21505:{if(!stream.tty)return-59;return 0}case 21510:case 21511:case 21512:case 21506:case 21507:case 21508:{if(!stream.tty)return-59;return 0}case 21519:{if(!stream.tty)return-59;var argp=SYSCALLS.get();HEAP32[argp>>2]=0;return 0}case 21520:{if(!stream.tty)return-59;return-28}case 21531:{var argp=SYSCALLS.get();return FS.ioctl(stream,op,argp)}case 21523:{if(!stream.tty)return-59;return 0}case 21524:{if(!stream.tty)return-59;return 0}default:return-28}}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function ___syscall_lstat64(path,buf){try{path=SYSCALLS.getStr(path);return SYSCALLS.doStat(FS.lstat,path,buf)}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function ___syscall_newfstatat(dirfd,path,buf,flags){try{path=SYSCALLS.getStr(path);var nofollow=flags&256;var allowEmpty=flags&4096;flags=flags&~6400;path=SYSCALLS.calculateAt(dirfd,path,allowEmpty);return SYSCALLS.doStat(nofollow?FS.lstat:FS.stat,path,buf)}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function ___syscall_openat(dirfd,path,flags,varargs){SYSCALLS.varargs=varargs;try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);var mode=varargs?SYSCALLS.get():0;return FS.open(path,flags,mode).fd}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function ___syscall_socket(domain,type,protocol){try{var sock=SOCKFS.createSocket(domain,type,protocol);return sock.stream.fd}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function ___syscall_stat64(path,buf){try{path=SYSCALLS.getStr(path);return SYSCALLS.doStat(FS.stat,path,buf)}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}var tupleRegistrations={};function runDestructors(destructors){while(destructors.length){var ptr=destructors.pop();var del=destructors.pop();del(ptr)}}function simpleReadValueFromPointer(pointer){return this["fromWireType"](HEAP32[pointer>>2])}var awaitingDependencies={};var registeredTypes={};var typeDependencies={};var char_0=48;var char_9=57;function makeLegalFunctionName(name){if(undefined===name){return"_unknown"}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 createNamedFunction(name,body){name=makeLegalFunctionName(name);return new Function("body","return function "+name+"() {\n"+' "use strict";'+" return body.apply(this, arguments);\n"+"};\n")(body)}function extendError(baseErrorType,errorName){var errorClass=createNamedFunction(errorName,function(message){this.name=errorName;this.message=message;var stack=new Error(message).stack;if(stack!==undefined){this.stack=this.toString()+"\n"+stack.replace(/^Error(:[^\n]*)?\n/,"")}});errorClass.prototype=Object.create(baseErrorType.prototype);errorClass.prototype.constructor=errorClass;errorClass.prototype.toString=function(){if(this.message===undefined){return this.name}else{return this.name+": "+this.message}};return errorClass}var InternalError=undefined;function throwInternalError(message){throw new InternalError(message)}function whenDependentTypesAreResolved(myTypes,dependentTypes,getTypeConverters){myTypes.forEach(function(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{if(registeredTypes.hasOwnProperty(dt)){typeConverters[i]=registeredTypes[dt]}else{unregisteredTypes.push(dt);if(!awaitingDependencies.hasOwnProperty(dt)){awaitingDependencies[dt]=[]}awaitingDependencies[dt].push(()=>{typeConverters[i]=registeredTypes[dt];++registered;if(registered===unregisteredTypes.length){onComplete(typeConverters)}})}});if(0===unregisteredTypes.length){onComplete(typeConverters)}}function __embind_finalize_value_array(rawTupleType){var reg=tupleRegistrations[rawTupleType];delete tupleRegistrations[rawTupleType];var elements=reg.elements;var elementsLength=elements.length;var elementTypes=elements.map(function(elt){return elt.getterReturnType}).concat(elements.map(function(elt){return elt.setterArgumentType}));var rawConstructor=reg.rawConstructor;var rawDestructor=reg.rawDestructor;whenDependentTypesAreResolved([rawTupleType],elementTypes,function(elementTypes){elements.forEach((elt,i)=>{var getterReturnType=elementTypes[i];var getter=elt.getter;var getterContext=elt.getterContext;var setterArgumentType=elementTypes[i+elementsLength];var setter=elt.setter;var setterContext=elt.setterContext;elt.read=ptr=>{return getterReturnType["fromWireType"](getter(getterContext,ptr))};elt.write=(ptr,o)=>{var destructors=[];setter(setterContext,ptr,setterArgumentType["toWireType"](destructors,o));runDestructors(destructors)}});return[{name:reg.name,"fromWireType":function(ptr){var rv=new Array(elementsLength);for(var i=0;ifield.getterReturnType).concat(fieldRecords.map(field=>field.setterArgumentType));whenDependentTypesAreResolved([structType],fieldTypes,fieldTypes=>{var fields={};fieldRecords.forEach((field,i)=>{var fieldName=field.fieldName;var getterReturnType=fieldTypes[i];var getter=field.getter;var getterContext=field.getterContext;var setterArgumentType=fieldTypes[i+fieldRecords.length];var setter=field.setter;var setterContext=field.setterContext;fields[fieldName]={read:ptr=>{return getterReturnType["fromWireType"](getter(getterContext,ptr))},write:(ptr,o)=>{var destructors=[];setter(setterContext,ptr,setterArgumentType["toWireType"](destructors,o));runDestructors(destructors)}}});return[{name:reg.name,"fromWireType":function(ptr){var rv={};for(var i in fields){rv[i]=fields[i].read(ptr)}rawDestructor(ptr);return rv},"toWireType":function(destructors,o){for(var fieldName in fields){if(!(fieldName in o)){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},"argPackAdvance":8,"readValueFromPointer":simpleReadValueFromPointer,destructorFunction:rawDestructor}]})}function __embind_register_bigint(primitiveType,name,size,minRange,maxRange){}function getShiftFromSize(size){switch(size){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError("Unknown type size: "+size)}}function embind_init_charCodes(){var codes=new Array(256);for(var i=0;i<256;++i){codes[i]=String.fromCharCode(i)}embind_charCodes=codes}var embind_charCodes=undefined;function readLatin1String(ptr){var ret="";var c=ptr;while(HEAPU8[c]){ret+=embind_charCodes[HEAPU8[c++]]}return ret}var BindingError=undefined;function throwBindingError(message){throw new BindingError(message)}function registerType(rawType,registeredInstance,options={}){if(!("argPackAdvance"in registeredInstance)){throw new TypeError("registerType registeredInstance requires argPackAdvance")}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 __embind_register_bool(rawType,name,size,trueValue,falseValue){var shift=getShiftFromSize(size);name=readLatin1String(name);registerType(rawType,{name:name,"fromWireType":function(wt){return!!wt},"toWireType":function(destructors,o){return o?trueValue:falseValue},"argPackAdvance":8,"readValueFromPointer":function(pointer){var heap;if(size===1){heap=HEAP8}else if(size===2){heap=HEAP16}else if(size===4){heap=HEAP32}else{throw new TypeError("Unknown boolean type size: "+name)}return this["fromWireType"](heap[pointer>>shift])},destructorFunction:null})}function ClassHandle_isAliasOf(other){if(!(this instanceof ClassHandle)){return false}if(!(other instanceof ClassHandle)){return false}var leftClass=this.$$.ptrType.registeredClass;var left=this.$$.ptr;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}function shallowCopyInternalPointer(o){return{count:o.count,deleteScheduled:o.deleteScheduled,preservePointerOnDelete:o.preservePointerOnDelete,ptr:o.ptr,ptrType:o.ptrType,smartPtr:o.smartPtr,smartPtrType:o.smartPtrType}}function throwInstanceAlreadyDeleted(obj){function getInstanceTypeName(handle){return handle.$$.ptrType.registeredClass.name}throwBindingError(getInstanceTypeName(obj)+" instance already deleted")}var finalizationRegistry=false;function detachFinalizer(handle){}function runDestructor($$){if($$.smartPtr){$$.smartPtrType.rawDestructor($$.smartPtr)}else{$$.ptrType.registeredClass.rawDestructor($$.ptr)}}function releaseClassHandle($$){$$.count.value-=1;var toDelete=0===$$.count.value;if(toDelete){runDestructor($$)}}function 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 registeredPointers={};function getInheritedInstanceCount(){return Object.keys(registeredInstances).length}function getLiveInheritedInstances(){var rv=[];for(var k in registeredInstances){if(registeredInstances.hasOwnProperty(k)){rv.push(registeredInstances[k])}}return rv}var deletionQueue=[];function flushPendingDeletes(){while(deletionQueue.length){var obj=deletionQueue.pop();obj.$$.deleteScheduled=false;obj["delete"]()}}var delayFunction=undefined;function setDelayFunction(fn){delayFunction=fn;if(deletionQueue.length&&delayFunction){delayFunction(flushPendingDeletes)}}function init_embind(){Module["getInheritedInstanceCount"]=getInheritedInstanceCount;Module["getLiveInheritedInstances"]=getLiveInheritedInstances;Module["flushPendingDeletes"]=flushPendingDeletes;Module["setDelayFunction"]=setDelayFunction}var registeredInstances={};function getBasestPointer(class_,ptr){if(ptr===undefined){throwBindingError("ptr should not be undefined")}while(class_.baseClass){ptr=class_.upcast(ptr);class_=class_.baseClass}return ptr}function getInheritedInstance(class_,ptr){ptr=getBasestPointer(class_,ptr);return registeredInstances[ptr]}function 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}}))}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: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})}}function attachFinalizer(handle){if("undefined"===typeof 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)}function ClassHandle_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}}function ClassHandle_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}}function ClassHandle_isDeleted(){return!this.$$.ptr}function ClassHandle_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}function init_ClassHandle(){ClassHandle.prototype["isAliasOf"]=ClassHandle_isAliasOf;ClassHandle.prototype["clone"]=ClassHandle_clone;ClassHandle.prototype["delete"]=ClassHandle_delete;ClassHandle.prototype["isDeleted"]=ClassHandle_isDeleted;ClassHandle.prototype["deleteLater"]=ClassHandle_deleteLater}function ClassHandle(){}function ensureOverloadTable(proto,methodName,humanName){if(undefined===proto[methodName].overloadTable){var prevFunc=proto[methodName];proto[methodName]=function(){if(!proto[methodName].overloadTable.hasOwnProperty(arguments.length)){throwBindingError("Function '"+humanName+"' called with an invalid number of arguments ("+arguments.length+") - expects one of ("+proto[methodName].overloadTable+")!")}return proto[methodName].overloadTable[arguments.length].apply(this,arguments)};proto[methodName].overloadTable=[];proto[methodName].overloadTable[prevFunc.argCount]=prevFunc}}function 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.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;if(undefined!==numArguments){Module[name].numArguments=numArguments}}}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=[]}function 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}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.$$){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(function(){clonedHandle["delete"]()}));if(destructors!==null){destructors.push(this.rawDestructor,ptr)}}break;default:throwBindingError("Unsupporting 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}function RegisteredPointer_getPointee(ptr){if(this.rawGetPointee){ptr=this.rawGetPointee(ptr)}return ptr}function RegisteredPointer_destructor(ptr){if(this.rawDestructor){this.rawDestructor(ptr)}}function RegisteredPointer_deleteObject(handle){if(handle!==null){handle["delete"]()}}function init_RegisteredPointer(){RegisteredPointer.prototype.getPointee=RegisteredPointer_getPointee;RegisteredPointer.prototype.destructor=RegisteredPointer_destructor;RegisteredPointer.prototype["argPackAdvance"]=8;RegisteredPointer.prototype["readValueFromPointer"]=simpleReadValueFromPointer;RegisteredPointer.prototype["deleteObject"]=RegisteredPointer_deleteObject;RegisteredPointer.prototype["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}}function replacePublicSymbol(name,value,numArguments){if(!Module.hasOwnProperty(name)){throwInternalError("Replacing nonexistant public symbol")}if(undefined!==Module[name].overloadTable&&undefined!==numArguments){Module[name].overloadTable[numArguments]=value}else{Module[name]=value;Module[name].argCount=numArguments}}function dynCallLegacy(sig,ptr,args){var f=Module["dynCall_"+sig];return args&&args.length?f.apply(null,[ptr].concat(args)):f.call(null,ptr)}function getWasmTableEntry(funcPtr){return wasmTable.get(funcPtr)}function dynCall(sig,ptr,args){if(sig.includes("j")){return dynCallLegacy(sig,ptr,args)}var rtn=getWasmTableEntry(ptr).apply(null,args);return rtn}function getDynCaller(sig,ptr){var argCache=[];return function(){argCache.length=0;Object.assign(argCache,arguments);return dynCall(sig,ptr,argCache)}}function embind__requireFunction(signature,rawFunction){signature=readLatin1String(signature);function makeDynCaller(){if(signature.includes("j")){return getDynCaller(signature,rawFunction)}return getWasmTableEntry(rawFunction)}var fp=makeDynCaller();if(typeof fp!="function"){throwBindingError("unknown function pointer with signature "+signature+": "+rawFunction)}return fp}var UnboundTypeError=undefined;function getTypeName(type){var ptr=___getTypeName(type);var rv=readLatin1String(ptr);_free(ptr);return rv}function 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){name=readLatin1String(name);getActualType=embind__requireFunction(getActualTypeSignature,getActualType);if(upcast){upcast=embind__requireFunction(upcastSignature,upcast)}if(downcast){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]:[],function(base){base=base[0];var baseClass;var basePrototype;if(baseClassRawType){baseClass=base.registeredClass;basePrototype=baseClass.instancePrototype}else{basePrototype=ClassHandle.prototype}var constructor=createNamedFunction(legalFunctionName,function(){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[arguments.length];if(undefined===body){throw new BindingError("Tried to invoke ctor of "+name+" with invalid number of parameters ("+arguments.length+") - expected ("+Object.keys(registeredClass.constructor_body).toString()+") parameters instead!")}return body.apply(this,arguments)});var instancePrototype=Object.create(basePrototype,{constructor:{value:constructor}});constructor.prototype=instancePrototype;var registeredClass=new RegisteredClass(name,constructor,instancePrototype,rawDestructor,baseClass,getActualType,upcast,downcast);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]})}function new_(constructor,argumentList){if(!(constructor instanceof Function)){throw new TypeError("new_ called with constructor type "+typeof constructor+" which is not a function")}var dummy=createNamedFunction(constructor.name||"unknownFunctionName",function(){});dummy.prototype=constructor.prototype;var obj=new dummy;var r=constructor.apply(obj,argumentList);return r instanceof Object?r:obj}function craftInvokerFunction(humanName,argTypes,classType,cppInvokerFunc,cppTargetFunc){var argCount=argTypes.length;if(argCount<2){throwBindingError("argTypes array size mismatch! Must at least get return value and 'this' types!")}var isClassMethodFunc=argTypes[1]!==null&&classType!==null;var needsDestructorStack=false;for(var i=1;i0?", ":"")+argsListWired}invokerFnBody+=(returns?"var rv = ":"")+"invoker(fn"+(argsListWired.length>0?", ":"")+argsListWired+");\n";if(needsDestructorStack){invokerFnBody+="runDestructors(destructors);\n"}else{for(var i=isClassMethodFunc?1:2;i>2])}return array}function __embind_register_class_class_function(rawClassType,methodName,argCount,rawArgTypesAddr,invokerSignature,rawInvoker,fn){var rawArgTypes=heap32VectorToArray(argCount,rawArgTypesAddr);methodName=readLatin1String(methodName);rawInvoker=embind__requireFunction(invokerSignature,rawInvoker);whenDependentTypesAreResolved([],[rawClassType],function(classType){classType=classType[0];var humanName=classType.name+"."+methodName;function unboundTypesHandler(){throwUnboundTypeError("Cannot call "+humanName+" due to unbound types",rawArgTypes)}if(methodName.startsWith("@@")){methodName=Symbol[methodName.substring(2)]}var proto=classType.registeredClass.constructor;if(undefined===proto[methodName]){unboundTypesHandler.argCount=argCount-1;proto[methodName]=unboundTypesHandler}else{ensureOverloadTable(proto,methodName,humanName);proto[methodName].overloadTable[argCount-1]=unboundTypesHandler}whenDependentTypesAreResolved([],rawArgTypes,function(argTypes){var invokerArgsArray=[argTypes[0],null].concat(argTypes.slice(1));var func=craftInvokerFunction(humanName,invokerArgsArray,null,rawInvoker,fn);if(undefined===proto[methodName].overloadTable){func.argCount=argCount-1;proto[methodName]=func}else{proto[methodName].overloadTable[argCount-1]=func}return[]});return[]})}function __embind_register_class_constructor(rawClassType,argCount,rawArgTypesAddr,invokerSignature,invoker,rawConstructor){assert(argCount>0);var rawArgTypes=heap32VectorToArray(argCount,rawArgTypesAddr);invoker=embind__requireFunction(invokerSignature,invoker);whenDependentTypesAreResolved([],[rawClassType],function(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,function(argTypes){argTypes.splice(1,0,null);classType.registeredClass.constructor_body[argCount-1]=craftInvokerFunction(humanName,argTypes,null,invoker,rawConstructor);return[]});return[]})}function __embind_register_class_function(rawClassType,methodName,argCount,rawArgTypesAddr,invokerSignature,rawInvoker,context,isPureVirtual){var rawArgTypes=heap32VectorToArray(argCount,rawArgTypesAddr);methodName=readLatin1String(methodName);rawInvoker=embind__requireFunction(invokerSignature,rawInvoker);whenDependentTypesAreResolved([],[rawClassType],function(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,function(argTypes){var memberFunction=craftInvokerFunction(humanName,argTypes,classType,rawInvoker,context);if(undefined===proto[methodName].overloadTable){memberFunction.argCount=argCount-2;proto[methodName]=memberFunction}else{proto[methodName].overloadTable[argCount-2]=memberFunction}return[]});return[]})}function 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)}function __embind_register_class_property(classType,fieldName,getterReturnType,getterSignature,getter,getterContext,setterArgumentType,setterSignature,setter,setterContext){fieldName=readLatin1String(fieldName);getter=embind__requireFunction(getterSignature,getter);whenDependentTypesAreResolved([],[classType],function(classType){classType=classType[0];var humanName=classType.name+"."+fieldName;var desc={get:function(){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],function(types){var getterReturnType=types[0];var desc={get:function(){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_free_list=[];var emval_handle_array=[{},{value:undefined},{value:null},{value:true},{value:false}];function __emval_decref(handle){if(handle>4&&0===--emval_handle_array[handle].refcount){emval_handle_array[handle]=undefined;emval_free_list.push(handle)}}function count_emval_handles(){var count=0;for(var i=5;i{if(!handle){throwBindingError("Cannot use deleted val. handle = "+handle)}return emval_handle_array[handle].value},toHandle:value=>{switch(value){case undefined:return 1;case null:return 2;case true:return 3;case false:return 4;default:{var handle=emval_free_list.length?emval_free_list.pop():emval_handle_array.length;emval_handle_array[handle]={refcount:1,value:value};return handle}}}};function __embind_register_emval(rawType,name){name=readLatin1String(name);registerType(rawType,{name:name,"fromWireType":function(handle){var rv=Emval.toValue(handle);__emval_decref(handle);return rv},"toWireType":function(destructors,value){return Emval.toHandle(value)},"argPackAdvance":8,"readValueFromPointer":simpleReadValueFromPointer,destructorFunction:null})}function enumReadValueFromPointer(name,shift,signed){switch(shift){case 0:return function(pointer){var heap=signed?HEAP8:HEAPU8;return this["fromWireType"](heap[pointer])};case 1:return function(pointer){var heap=signed?HEAP16:HEAPU16;return this["fromWireType"](heap[pointer>>1])};case 2:return function(pointer){var heap=signed?HEAP32:HEAPU32;return this["fromWireType"](heap[pointer>>2])};default:throw new TypeError("Unknown integer type: "+name)}}function __embind_register_enum(rawType,name,size,isSigned){var shift=getShiftFromSize(size);name=readLatin1String(name);function ctor(){}ctor.values={};registerType(rawType,{name:name,constructor:ctor,"fromWireType":function(c){return this.constructor.values[c]},"toWireType":function(destructors,c){return c.value},"argPackAdvance":8,"readValueFromPointer":enumReadValueFromPointer(name,shift,isSigned),destructorFunction:null});exposePublicSymbol(name,ctor)}function requireRegisteredType(rawType,humanName){var impl=registeredTypes[rawType];if(undefined===impl){throwBindingError(humanName+" has unknown type "+getTypeName(rawType))}return impl}function __embind_register_enum_value(rawEnumType,name,enumValue){var enumType=requireRegisteredType(rawEnumType,"enum");name=readLatin1String(name);var Enum=enumType.constructor;var Value=Object.create(enumType.constructor.prototype,{value:{value:enumValue},constructor:{value:createNamedFunction(enumType.name+"_"+name,function(){})}});Enum.values[enumValue]=Value;Enum[name]=Value}function 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 floatReadValueFromPointer(name,shift){switch(shift){case 2:return function(pointer){return this["fromWireType"](HEAPF32[pointer>>2])};case 3:return function(pointer){return this["fromWireType"](HEAPF64[pointer>>3])};default:throw new TypeError("Unknown float type: "+name)}}function __embind_register_float(rawType,name,size){var shift=getShiftFromSize(size);name=readLatin1String(name);registerType(rawType,{name:name,"fromWireType":function(value){return value},"toWireType":function(destructors,value){return value},"argPackAdvance":8,"readValueFromPointer":floatReadValueFromPointer(name,shift),destructorFunction:null})}function integerReadValueFromPointer(name,shift,signed){switch(shift){case 0:return signed?function readS8FromPointer(pointer){return HEAP8[pointer]}:function readU8FromPointer(pointer){return HEAPU8[pointer]};case 1:return signed?function readS16FromPointer(pointer){return HEAP16[pointer>>1]}:function readU16FromPointer(pointer){return HEAPU16[pointer>>1]};case 2:return signed?function readS32FromPointer(pointer){return HEAP32[pointer>>2]}:function readU32FromPointer(pointer){return HEAPU32[pointer>>2]};default:throw new TypeError("Unknown integer type: "+name)}}function __embind_register_integer(primitiveType,name,size,minRange,maxRange){name=readLatin1String(name);if(maxRange===-1){maxRange=4294967295}var shift=getShiftFromSize(size);var fromWireType=value=>value;if(minRange===0){var bitshift=32-8*size;fromWireType=value=>value<>>bitshift}var isUnsignedType=name.includes("unsigned");var checkAssertions=(value,toTypeName)=>{};var toWireType;if(isUnsignedType){toWireType=function(destructors,value){checkAssertions(value,this.name);return value>>>0}}else{toWireType=function(destructors,value){checkAssertions(value,this.name);return value}}registerType(primitiveType,{name:name,"fromWireType":fromWireType,"toWireType":toWireType,"argPackAdvance":8,"readValueFromPointer":integerReadValueFromPointer(name,shift,minRange!==0),destructorFunction:null})}function __embind_register_memory_view(rawType,dataTypeIndex,name){var typeMapping=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];var TA=typeMapping[dataTypeIndex];function decodeMemoryView(handle){handle=handle>>2;var heap=HEAPU32;var size=heap[handle];var data=heap[handle+1];return new TA(heap.buffer,data,size)}name=readLatin1String(name);registerType(rawType,{name:name,"fromWireType":decodeMemoryView,"argPackAdvance":8,"readValueFromPointer":decodeMemoryView},{ignoreDuplicateRegistrations:true})}function __embind_register_std_string(rawType,name){name=readLatin1String(name);var stdStringIsUTF8=name==="std::string";registerType(rawType,{name:name,"fromWireType":function(value){var length=HEAPU32[value>>2];var payload=value+4;var str;if(stdStringIsUTF8){var decodeStartPtr=payload;for(var i=0;i<=length;++i){var currentBytePtr=payload+i;if(i==length||HEAPU8[currentBytePtr]==0){var maxRead=currentBytePtr-decodeStartPtr;var stringSegment=UTF8ToString(decodeStartPtr,maxRead);if(str===undefined){str=stringSegment}else{str+=String.fromCharCode(0);str+=stringSegment}decodeStartPtr=currentBytePtr+1}}}else{var a=new Array(length);for(var i=0;i>2]=length;if(stdStringIsUTF8&&valueIsOfTypeString){stringToUTF8(value,ptr,length+1)}else{if(valueIsOfTypeString){for(var i=0;i255){_free(ptr);throwBindingError("String has UTF-16 code units that do not fit in 8 bits")}HEAPU8[ptr+i]=charCode}}else{for(var i=0;i>1;var maxIdx=idx+maxBytesToRead/2;while(!(idx>=maxIdx)&&HEAPU16[idx])++idx;endPtr=idx<<1;if(endPtr-ptr>32&&UTF16Decoder)return UTF16Decoder.decode(HEAPU8.subarray(ptr,endPtr));var str="";for(var i=0;!(i>=maxBytesToRead/2);++i){var codeUnit=HEAP16[ptr+i*2>>1];if(codeUnit==0)break;str+=String.fromCharCode(codeUnit)}return str}function stringToUTF16(str,outPtr,maxBytesToWrite){if(maxBytesToWrite===undefined){maxBytesToWrite=2147483647}if(maxBytesToWrite<2)return 0;maxBytesToWrite-=2;var startPtr=outPtr;var numCharsToWrite=maxBytesToWrite>1]=codeUnit;outPtr+=2}HEAP16[outPtr>>1]=0;return outPtr-startPtr}function lengthBytesUTF16(str){return str.length*2}function UTF32ToString(ptr,maxBytesToRead){var i=0;var str="";while(!(i>=maxBytesToRead/4)){var utf32=HEAP32[ptr+i*4>>2];if(utf32==0)break;++i;if(utf32>=65536){var ch=utf32-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}else{str+=String.fromCharCode(utf32)}}return str}function stringToUTF32(str,outPtr,maxBytesToWrite){if(maxBytesToWrite===undefined){maxBytesToWrite=2147483647}if(maxBytesToWrite<4)return 0;var startPtr=outPtr;var endPtr=startPtr+maxBytesToWrite-4;for(var i=0;i=55296&&codeUnit<=57343){var trailSurrogate=str.charCodeAt(++i);codeUnit=65536+((codeUnit&1023)<<10)|trailSurrogate&1023}HEAP32[outPtr>>2]=codeUnit;outPtr+=4;if(outPtr+4>endPtr)break}HEAP32[outPtr>>2]=0;return outPtr-startPtr}function lengthBytesUTF32(str){var len=0;for(var i=0;i=55296&&codeUnit<=57343)++i;len+=4}return len}function __embind_register_std_wstring(rawType,charSize,name){name=readLatin1String(name);var decodeString,encodeString,getHeap,lengthBytesUTF,shift;if(charSize===2){decodeString=UTF16ToString;encodeString=stringToUTF16;lengthBytesUTF=lengthBytesUTF16;getHeap=()=>HEAPU16;shift=1}else if(charSize===4){decodeString=UTF32ToString;encodeString=stringToUTF32;lengthBytesUTF=lengthBytesUTF32;getHeap=()=>HEAPU32;shift=2}registerType(rawType,{name:name,"fromWireType":function(value){var length=HEAPU32[value>>2];var HEAP=getHeap();var str;var decodeStartPtr=value+4;for(var i=0;i<=length;++i){var currentBytePtr=value+4+i*charSize;if(i==length||HEAP[currentBytePtr>>shift]==0){var maxReadBytes=currentBytePtr-decodeStartPtr;var stringSegment=decodeString(decodeStartPtr,maxReadBytes);if(str===undefined){str=stringSegment}else{str+=String.fromCharCode(0);str+=stringSegment}decodeStartPtr=currentBytePtr+charSize}}_free(value);return str},"toWireType":function(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]=length>>shift;encodeString(value,ptr+4,length+charSize);if(destructors!==null){destructors.push(_free,ptr)}return ptr},"argPackAdvance":8,"readValueFromPointer":simpleReadValueFromPointer,destructorFunction:function(ptr){_free(ptr)}})}function __embind_register_value_array(rawType,name,constructorSignature,rawConstructor,destructorSignature,rawDestructor){tupleRegistrations[rawType]={name:readLatin1String(name),rawConstructor:embind__requireFunction(constructorSignature,rawConstructor),rawDestructor:embind__requireFunction(destructorSignature,rawDestructor),elements:[]}}function __embind_register_value_array_element(rawTupleType,getterReturnType,getterSignature,getter,getterContext,setterArgumentType,setterSignature,setter,setterContext){tupleRegistrations[rawTupleType].elements.push({getterReturnType:getterReturnType,getter:embind__requireFunction(getterSignature,getter),getterContext:getterContext,setterArgumentType:setterArgumentType,setter:embind__requireFunction(setterSignature,setter),setterContext:setterContext})}function __embind_register_value_object(rawType,name,constructorSignature,rawConstructor,destructorSignature,rawDestructor){structRegistrations[rawType]={name:readLatin1String(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){structRegistrations[structType].fields.push({fieldName:readLatin1String(fieldName),getterReturnType:getterReturnType,getter:embind__requireFunction(getterSignature,getter),getterContext:getterContext,setterArgumentType:setterArgumentType,setter:embind__requireFunction(setterSignature,setter),setterContext:setterContext})}function __embind_register_void(rawType,name){name=readLatin1String(name);registerType(rawType,{isVoid:true,name:name,"argPackAdvance":0,"fromWireType":function(){return undefined},"toWireType":function(destructors,o){return undefined}})}function __emval_as(handle,returnType,destructorsRef){handle=Emval.toValue(handle);returnType=requireRegisteredType(returnType,"emval::as");var destructors=[];var rd=Emval.toHandle(destructors);HEAPU32[destructorsRef>>2]=rd;return returnType["toWireType"](destructors,handle)}function emval_allocateDestructors(destructorsRef){var destructors=[];HEAPU32[destructorsRef>>2]=Emval.toHandle(destructors);return destructors}var emval_symbols={};function getStringOrSymbol(address){var symbol=emval_symbols[address];if(symbol===undefined){return readLatin1String(address)}return symbol}var emval_methodCallers=[];function __emval_call_method(caller,handle,methodName,destructorsRef,args){caller=emval_methodCallers[caller];handle=Emval.toValue(handle);methodName=getStringOrSymbol(methodName);return caller(handle,methodName,emval_allocateDestructors(destructorsRef),args)}function __emval_call_void_method(caller,handle,methodName,args){caller=emval_methodCallers[caller];handle=Emval.toValue(handle);methodName=getStringOrSymbol(methodName);caller(handle,methodName,null,args)}function __emval_equals(first,second){first=Emval.toValue(first);second=Emval.toValue(second);return first==second}function emval_get_global(){if(typeof globalThis=="object"){return globalThis}return function(){return Function}()("return this")()}function __emval_get_global(name){if(name===0){return Emval.toHandle(emval_get_global())}else{name=getStringOrSymbol(name);return Emval.toHandle(emval_get_global()[name])}}function emval_addMethodCaller(caller){var id=emval_methodCallers.length;emval_methodCallers.push(caller);return id}function emval_lookupTypes(argCount,argTypes){var a=new Array(argCount);for(var i=0;i>2],"parameter "+i)}return a}var emval_registeredMethods=[];function __emval_get_method_caller(argCount,argTypes){var types=emval_lookupTypes(argCount,argTypes);var retType=types[0];var signatureName=retType.name+"_$"+types.slice(1).map(function(t){return t.name}).join("_")+"$";var returnId=emval_registeredMethods[signatureName];if(returnId!==undefined){return returnId}var params=["retType"];var args=[retType];var argsList="";for(var i=0;i4){emval_handle_array[handle].refcount+=1}}function __emval_instanceof(object,constructor){object=Emval.toValue(object);constructor=Emval.toValue(constructor);return object instanceof constructor}function __emval_is_number(handle){handle=Emval.toValue(handle);return typeof handle=="number"}function __emval_is_string(handle){handle=Emval.toValue(handle);return typeof handle=="string"}function craftEmvalAllocator(argCount){var argsList="";for(var i=0;iHEAPU32;var functionBody="return function emval_allocator_"+argCount+"(constructor, argTypes, args) {\n"+" var HEAPU32 = getMemory();\n";for(var i=0;i>2)], 'parameter "+i+"');\n"+"var arg"+i+" = argType"+i+".readValueFromPointer(args);\n"+"args += argType"+i+"['argPackAdvance'];\n"+"argTypes += 4;\n"}functionBody+="var obj = new constructor("+argsList+");\n"+"return valueToHandle(obj);\n"+"}\n";return new Function("requireRegisteredType","Module","valueToHandle","getMemory",functionBody)(requireRegisteredType,Module,Emval.toHandle,getMemory)}var emval_newers={};function __emval_new(handle,argCount,argTypes,args){handle=Emval.toValue(handle);var newer=emval_newers[argCount];if(!newer){newer=craftEmvalAllocator(argCount);emval_newers[argCount]=newer}return newer(handle,argTypes,args)}function __emval_new_array(){return Emval.toHandle([])}function __emval_new_cstring(v){return Emval.toHandle(getStringOrSymbol(v))}function __emval_new_object(){return Emval.toHandle({})}function __emval_run_destructors(handle){var destructors=Emval.toValue(handle);runDestructors(destructors);__emval_decref(handle)}function __emval_set_property(handle,key,value){handle=Emval.toValue(handle);key=Emval.toValue(key);value=Emval.toValue(value);handle[key]=value}function __emval_take_value(type,arg){type=requireRegisteredType(type,"_emval_take_value");var v=type["readValueFromPointer"](arg);return Emval.toHandle(v)}function readI53FromI64(ptr){return HEAPU32[ptr>>2]+HEAP32[ptr+4>>2]*4294967296}function __gmtime_js(time,tmPtr){var date=new Date(readI53FromI64(time)*1e3);HEAP32[tmPtr>>2]=date.getUTCSeconds();HEAP32[tmPtr+4>>2]=date.getUTCMinutes();HEAP32[tmPtr+8>>2]=date.getUTCHours();HEAP32[tmPtr+12>>2]=date.getUTCDate();HEAP32[tmPtr+16>>2]=date.getUTCMonth();HEAP32[tmPtr+20>>2]=date.getUTCFullYear()-1900;HEAP32[tmPtr+24>>2]=date.getUTCDay();var start=Date.UTC(date.getUTCFullYear(),0,1,0,0,0,0);var yday=(date.getTime()-start)/(1e3*60*60*24)|0;HEAP32[tmPtr+28>>2]=yday}function __isLeapYear(year){return 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];function __yday_from_date(date){var isLeapYear=__isLeapYear(date.getFullYear());var monthDaysCumulative=isLeapYear?__MONTH_DAYS_LEAP_CUMULATIVE:__MONTH_DAYS_REGULAR_CUMULATIVE;var yday=monthDaysCumulative[date.getMonth()]+date.getDate()-1;return yday}function __localtime_js(time,tmPtr){var date=new Date(readI53FromI64(time)*1e3);HEAP32[tmPtr>>2]=date.getSeconds();HEAP32[tmPtr+4>>2]=date.getMinutes();HEAP32[tmPtr+8>>2]=date.getHours();HEAP32[tmPtr+12>>2]=date.getDate();HEAP32[tmPtr+16>>2]=date.getMonth();HEAP32[tmPtr+20>>2]=date.getFullYear()-1900;HEAP32[tmPtr+24>>2]=date.getDay();var yday=__yday_from_date(date)|0;HEAP32[tmPtr+28>>2]=yday;HEAP32[tmPtr+36>>2]=-(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]=dst}function __mktime_js(tmPtr){var date=new Date(HEAP32[tmPtr+20>>2]+1900,HEAP32[tmPtr+16>>2],HEAP32[tmPtr+12>>2],HEAP32[tmPtr+8>>2],HEAP32[tmPtr+4>>2],HEAP32[tmPtr>>2],0);var dst=HEAP32[tmPtr+32>>2];var guessedOffset=date.getTimezoneOffset();var start=new Date(date.getFullYear(),0,1);var summerOffset=new Date(date.getFullYear(),6,1).getTimezoneOffset();var winterOffset=start.getTimezoneOffset();var dstOffset=Math.min(winterOffset,summerOffset);if(dst<0){HEAP32[tmPtr+32>>2]=Number(summerOffset!=winterOffset&&dstOffset==guessedOffset)}else if(dst>0!=(dstOffset==guessedOffset)){var nonDstOffset=Math.max(winterOffset,summerOffset);var trueOffset=dst>0?dstOffset:nonDstOffset;date.setTime(date.getTime()+(trueOffset-guessedOffset)*6e4)}HEAP32[tmPtr+24>>2]=date.getDay();var yday=__yday_from_date(date)|0;HEAP32[tmPtr+28>>2]=yday;HEAP32[tmPtr>>2]=date.getSeconds();HEAP32[tmPtr+4>>2]=date.getMinutes();HEAP32[tmPtr+8>>2]=date.getHours();HEAP32[tmPtr+12>>2]=date.getDate();HEAP32[tmPtr+16>>2]=date.getMonth();HEAP32[tmPtr+20>>2]=date.getYear();return date.getTime()/1e3|0}function allocateUTF8(str){var size=lengthBytesUTF8(str)+1;var ret=_malloc(size);if(ret)stringToUTF8Array(str,HEAP8,ret,size);return ret}function __tzset_js(timezone,daylight,tzname){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]=stdTimezoneOffset*60;HEAP32[daylight>>2]=Number(winterOffset!=summerOffset);function extractZone(date){var match=date.toTimeString().match(/\(([A-Za-z ]+)\)$/);return match?match[1]:"GMT"}var winterName=extractZone(winter);var summerName=extractZone(summer);var winterNamePtr=allocateUTF8(winterName);var summerNamePtr=allocateUTF8(summerName);if(summerOffset>2]=winterNamePtr;HEAPU32[tzname+4>>2]=summerNamePtr}else{HEAPU32[tzname>>2]=summerNamePtr;HEAPU32[tzname+4>>2]=winterNamePtr}}function _abort(){abort("")}function _emscripten_date_now(){return Date.now()}function getHeapMax(){return 2147483648}var _emscripten_get_now;if(ENVIRONMENT_IS_NODE){_emscripten_get_now=()=>{var t=process["hrtime"]();return t[0]*1e3+t[1]/1e6}}else _emscripten_get_now=()=>performance.now();function emscripten_realloc_buffer(size){var b=wasmMemory.buffer;try{wasmMemory.grow(size-b.byteLength+65535>>>16);updateMemoryViews();return 1}catch(e){}}function _emscripten_resize_heap(requestedSize){var oldSize=HEAPU8.length;requestedSize=requestedSize>>>0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}let alignUp=(x,multiple)=>x+(multiple-x%multiple)%multiple;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,alignUp(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=emscripten_realloc_buffer(newSize);if(replacement){return true}}return false}var ENV={};function getExecutableName(){return thisProgram||"./this.program"}function getEnvStrings(){if(!getEnvStrings.strings){var lang=(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"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 writeAsciiToMemory(str,buffer,dontAddNull){for(var i=0;i>0]=str.charCodeAt(i)}if(!dontAddNull)HEAP8[buffer>>0]=0}function _environ_get(__environ,environ_buf){var bufSize=0;getEnvStrings().forEach(function(string,i){var ptr=environ_buf+bufSize;HEAPU32[__environ+i*4>>2]=ptr;writeAsciiToMemory(string,ptr);bufSize+=string.length+1});return 0}function _environ_sizes_get(penviron_count,penviron_buf_size){var strings=getEnvStrings();HEAPU32[penviron_count>>2]=strings.length;var bufSize=0;strings.forEach(function(string){bufSize+=string.length+1});HEAPU32[penviron_buf_size>>2]=bufSize;return 0}function _fd_close(fd){try{var stream=SYSCALLS.getStreamFromFD(fd);FS.close(stream);return 0}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return e.errno}}function doReadv(stream,iov,iovcnt,offset){var ret=0;for(var i=0;i>2];var len=HEAPU32[iov+4>>2];iov+=8;var curr=FS.read(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr;if(curr>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return e.errno}}function _fd_seek(fd,offset_low,offset_high,whence,newOffset){try{var offset=convertI32PairToI53Checked(offset_low,offset_high);if(isNaN(offset))return 61;var stream=SYSCALLS.getStreamFromFD(fd);FS.llseek(stream,offset,whence);tempI64=[stream.position>>>0,(tempDouble=stream.position,+Math.abs(tempDouble)>=1?tempDouble>0?(Math.min(+Math.floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[newOffset>>2]=tempI64[0],HEAP32[newOffset+4>>2]=tempI64[1];if(stream.getdents&&offset===0&&whence===0)stream.getdents=null;return 0}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return e.errno}}function doWritev(stream,iov,iovcnt,offset){var ret=0;for(var i=0;i>2];var len=HEAPU32[iov+4>>2];iov+=8;var curr=FS.write(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr;if(typeof offset!=="undefined"){offset+=curr}}return ret}function _fd_write(fd,iov,iovcnt,pnum){try{var stream=SYSCALLS.getStreamFromFD(fd);var num=doWritev(stream,iov,iovcnt);HEAPU32[pnum>>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return e.errno}}var FSNode=function(parent,name,mode,rdev){if(!parent){parent=this}this.parent=parent;this.mount=parent.mount;this.mounted=null;this.id=FS.nextInode++;this.name=name;this.mode=mode;this.node_ops={};this.stream_ops={};this.rdev=rdev};var readMode=292|73;var writeMode=146;Object.defineProperties(FSNode.prototype,{read:{get:function(){return(this.mode&readMode)===readMode},set:function(val){val?this.mode|=readMode:this.mode&=~readMode}},write:{get:function(){return(this.mode&writeMode)===writeMode},set:function(val){val?this.mode|=writeMode:this.mode&=~writeMode}},isFolder:{get:function(){return FS.isDir(this.mode)}},isDevice:{get:function(){return FS.isChrdev(this.mode)}}});FS.FSNode=FSNode;FS.staticInit();InternalError=Module["InternalError"]=extendError(Error,"InternalError");embind_init_charCodes();BindingError=Module["BindingError"]=extendError(Error,"BindingError");init_ClassHandle();init_embind();init_RegisteredPointer();UnboundTypeError=Module["UnboundTypeError"]=extendError(Error,"UnboundTypeError");init_emval();var asmLibraryArg={"v":___cxa_throw,"U":___syscall_connect,"ea":___syscall_faccessat,"o":___syscall_fcntl64,"Z":___syscall_fstat64,"S":___syscall_ftruncate64,"K":___syscall_ioctl,"W":___syscall_lstat64,"X":___syscall_newfstatat,"G":___syscall_openat,"F":___syscall_socket,"Y":___syscall_stat64,"r":__embind_finalize_value_array,"ka":__embind_finalize_value_object,"T":__embind_register_bigint,"ga":__embind_register_bool,"e":__embind_register_class,"f":__embind_register_class_class_function,"g":__embind_register_class_constructor,"b":__embind_register_class_function,"a":__embind_register_class_property,"fa":__embind_register_emval,"i":__embind_register_enum,"d":__embind_register_enum_value,"M":__embind_register_float,"p":__embind_register_integer,"l":__embind_register_memory_view,"L":__embind_register_std_string,"B":__embind_register_std_wstring,"q":__embind_register_value_array,"ia":__embind_register_value_array_element,"ja":__embind_register_value_object,"N":__embind_register_value_object_field,"ha":__embind_register_void,"t":__emval_as,"la":__emval_call_method,"P":__emval_call_void_method,"c":__emval_decref,"Q":__emval_equals,"y":__emval_get_global,"C":__emval_get_method_caller,"E":__emval_get_module_property,"w":__emval_get_property,"m":__emval_incref,"D":__emval_instanceof,"na":__emval_is_number,"ma":__emval_is_string,"O":__emval_new,"n":__emval_new_array,"u":__emval_new_cstring,"k":__emval_new_object,"s":__emval_run_destructors,"j":__emval_set_property,"h":__emval_take_value,"aa":__gmtime_js,"ba":__localtime_js,"ca":__mktime_js,"da":__tzset_js,"z":_abort,"I":_emscripten_date_now,"H":_emscripten_get_now,"V":_emscripten_resize_heap,"_":_environ_get,"$":_environ_sizes_get,"x":_fd_close,"J":_fd_read,"R":_fd_seek,"A":_fd_write};var asm=createWasm();var ___wasm_call_ctors=Module["___wasm_call_ctors"]=function(){return(___wasm_call_ctors=Module["___wasm_call_ctors"]=Module["asm"]["pa"]).apply(null,arguments)};var _malloc=Module["_malloc"]=function(){return(_malloc=Module["_malloc"]=Module["asm"]["ra"]).apply(null,arguments)};var _free=Module["_free"]=function(){return(_free=Module["_free"]=Module["asm"]["sa"]).apply(null,arguments)};var ___errno_location=Module["___errno_location"]=function(){return(___errno_location=Module["___errno_location"]=Module["asm"]["ta"]).apply(null,arguments)};var ___getTypeName=Module["___getTypeName"]=function(){return(___getTypeName=Module["___getTypeName"]=Module["asm"]["ua"]).apply(null,arguments)};var __embind_initialize_bindings=Module["__embind_initialize_bindings"]=function(){return(__embind_initialize_bindings=Module["__embind_initialize_bindings"]=Module["asm"]["va"]).apply(null,arguments)};var _htons=Module["_htons"]=function(){return(_htons=Module["_htons"]=Module["asm"]["wa"]).apply(null,arguments)};var _ntohs=Module["_ntohs"]=function(){return(_ntohs=Module["_ntohs"]=Module["asm"]["xa"]).apply(null,arguments)};var ___cxa_is_pointer_type=Module["___cxa_is_pointer_type"]=function(){return(___cxa_is_pointer_type=Module["___cxa_is_pointer_type"]=Module["asm"]["ya"]).apply(null,arguments)};var dynCall_ji=Module["dynCall_ji"]=function(){return(dynCall_ji=Module["dynCall_ji"]=Module["asm"]["za"]).apply(null,arguments)};var dynCall_vij=Module["dynCall_vij"]=function(){return(dynCall_vij=Module["dynCall_vij"]=Module["asm"]["Aa"]).apply(null,arguments)};var dynCall_jiji=Module["dynCall_jiji"]=function(){return(dynCall_jiji=Module["dynCall_jiji"]=Module["asm"]["Ba"]).apply(null,arguments)};var calledRun;dependenciesFulfilled=function runCaller(){if(!calledRun)run();if(!calledRun)dependenciesFulfilled=runCaller};function run(args){args=args||arguments_;if(runDependencies>0){return}preRun();if(runDependencies>0){return}function doRun(){if(calledRun)return;calledRun=true;Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve(Module);if(Module["onRuntimeInitialized"])Module["onRuntimeInitialized"]();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(function(){setTimeout(function(){Module["setStatus"]("")},1);doRun()},1)}else{doRun()}}if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].pop()()}}run(); - - - return rhino3dm.ready -} -); -})(); -if (typeof exports === 'object' && typeof module === 'object') - module.exports = rhino3dm; -else if (typeof define === 'function' && define['amd']) - define([], function() { return rhino3dm; }); -else if (typeof exports === 'object') - exports["rhino3dm"] = rhino3dm; diff --git a/public/assets/lib/vendor/three/rhino3dm/rhino3dm.min.js b/public/assets/lib/vendor/three/rhino3dm/rhino3dm.min.js deleted file mode 100644 index b4fa67e1..00000000 --- a/public/assets/lib/vendor/three/rhino3dm/rhino3dm.min.js +++ /dev/null @@ -1 +0,0 @@ -var rhino3dm=(()=>{var e="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0;return"undefined"!=typeof __filename&&(e=e||__filename),function(r){var t,n,o=r||{},a=void 0!==o?o:{};a.ready=new Promise(function(e,r){t=e,n=r});var i,s,u,c=Object.assign({},a),l=[],f="./this.program",d="object"==typeof window,p="function"==typeof importScripts,h="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,m="";if(h){var v=require("fs"),w=require("path");m=p?w.dirname(m)+"/":__dirname+"/",i=((e,r)=>(e=ne(e)?new URL(e):w.normalize(e),v.readFileSync(e,r?void 0:"utf8"))),u=(e=>{var r=i(e,!0);return r.buffer||(r=new Uint8Array(r)),r}),s=((e,r,t)=>{e=ne(e)?new URL(e):w.normalize(e),v.readFile(e,function(e,n){e?t(e):r(n.buffer)})}),process.argv.length>1&&(f=process.argv[1].replace(/\\/g,"/")),l=process.argv.slice(2),process.on("uncaughtException",function(e){if(!(e instanceof ae))throw e}),process.on("unhandledRejection",function(e){throw e}),(e,r)=>{if(k)throw process.exitCode=e,r;!function(e){if(e instanceof ae)return;g("exiting due to exception: "+e)}(r),process.exit(e)},a.inspect=function(){return"[Emscripten Module object]"}}else(d||p)&&(p?m=self.location.href:"undefined"!=typeof document&&document.currentScript&&(m=document.currentScript.src),e&&(m=e),m=0!==m.indexOf("blob:")?m.substr(0,m.replace(/[?#].*/,"").lastIndexOf("/")+1):"",i=(e=>{var r=new XMLHttpRequest;return r.open("GET",e,!1),r.send(null),r.responseText}),p&&(u=(e=>{var r=new XMLHttpRequest;return r.open("GET",e,!1),r.responseType="arraybuffer",r.send(null),new Uint8Array(r.response)})),s=((e,r,t)=>{var n=new XMLHttpRequest;n.open("GET",e,!0),n.responseType="arraybuffer",n.onload=(()=>{200==n.status||0==n.status&&n.response?r(n.response):t()}),n.onerror=t,n.send(null)}),e=>document.title=e);var y=a.print||console.log.bind(console),g=a.printErr||console.warn.bind(console);Object.assign(a,c),c=null,a.arguments&&(l=a.arguments),a.thisProgram&&(f=a.thisProgram),a.quit&&a.quit;var E,b=4;a.wasmBinary&&(E=a.wasmBinary);var _,k=a.noExitRuntime||!0;"object"!=typeof WebAssembly&&K("no native wasm support detected");var T=!1;function P(e,r){e||K(r)}var C,S,D,A,F,$,M,O,j="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function x(e,r,t){for(var n=r+t,o=r;e[o]&&!(o>=n);)++o;if(o-r>16&&e.buffer&&j)return j.decode(e.subarray(r,o));for(var a="";r>10,56320|1023&c)}}else a+=String.fromCharCode((31&i)<<6|s)}else a+=String.fromCharCode(i)}return a}function N(e,r){return e?x(S,e,r):""}function R(e,r,t,n){if(!(n>0))return 0;for(var o=t,a=t+n-1,i=0;i=55296&&s<=57343)s=65536+((1023&s)<<10)|1023&e.charCodeAt(++i);if(s<=127){if(t>=a)break;r[t++]=s}else if(s<=2047){if(t+1>=a)break;r[t++]=192|s>>6,r[t++]=128|63&s}else if(s<=65535){if(t+2>=a)break;r[t++]=224|s>>12,r[t++]=128|s>>6&63,r[t++]=128|63&s}else{if(t+3>=a)break;r[t++]=240|s>>18,r[t++]=128|s>>12&63,r[t++]=128|s>>6&63,r[t++]=128|63&s}}return r[t]=0,t-o}function z(e){for(var r=0,t=0;t=55296&&n<=57343?(r+=4,++t):r+=3}return r}function W(){var e=_.buffer;a.HEAP8=C=new Int8Array(e),a.HEAP16=D=new Int16Array(e),a.HEAP32=F=new Int32Array(e),a.HEAPU8=S=new Uint8Array(e),a.HEAPU16=A=new Uint16Array(e),a.HEAPU32=$=new Uint32Array(e),a.HEAPF32=M=new Float32Array(e),a.HEAPF64=O=new Float64Array(e)}a.INITIAL_MEMORY;var B,U=[],L=[],I=[];var H=0,V=null,q=null;function G(e){return e}function X(e){H++,a.monitorRunDependencies&&a.monitorRunDependencies(H)}function Y(e){if(H--,a.monitorRunDependencies&&a.monitorRunDependencies(H),0==H&&(null!==V&&(clearInterval(V),V=null),q)){var r=q;q=null,r()}}function K(e){a.onAbort&&a.onAbort(e),g(e="Aborted("+e+")"),T=!0,1,e+=". Build with -sASSERTIONS for more info.";var r=new WebAssembly.RuntimeError(e);throw n(r),r}var Z,J,Q,ee,re="data:application/octet-stream;base64,";function te(e){return e.startsWith(re)}function ne(e){return e.startsWith("file://")}function oe(e){try{if(e==Z&&E)return new Uint8Array(E);if(u)return u(e);throw"both async and sync fetching of the wasm failed"}catch(e){K(e)}}function ae(e){this.name="ExitStatus",this.message="Program terminated with exit("+e+")",this.status=e}function ie(e){for(;e.length>0;)e.shift()(a)}te(Z="rhino3dm.wasm")||(J=Z,Z=a.locateFile?a.locateFile(J,m):m+J);var se={isAbs:e=>"/"===e.charAt(0),splitPath:e=>{return/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(e).slice(1)},normalizeArray:(e,r)=>{for(var t=0,n=e.length-1;n>=0;n--){var o=e[n];"."===o?e.splice(n,1):".."===o?(e.splice(n,1),t++):t&&(e.splice(n,1),t--)}if(r)for(;t;t--)e.unshift("..");return e},normalize:e=>{var r=se.isAbs(e),t="/"===e.substr(-1);return(e=se.normalizeArray(e.split("/").filter(e=>!!e),!r).join("/"))||r||(e="."),e&&t&&(e+="/"),(r?"/":"")+e},dirname:e=>{var r=se.splitPath(e),t=r[0],n=r[1];return t||n?(n&&(n=n.substr(0,n.length-1)),t+n):"."},basename:e=>{if("/"===e)return"/";var r=(e=(e=se.normalize(e)).replace(/\/$/,"")).lastIndexOf("/");return-1===r?e:e.substr(r+1)},join:function(){var e=Array.prototype.slice.call(arguments);return se.normalize(e.join("/"))},join2:(e,r)=>se.normalize(e+"/"+r)},ue={resolve:function(){for(var e="",r=!1,t=arguments.length-1;t>=-1&&!r;t--){var n=t>=0?arguments[t]:pe.cwd();if("string"!=typeof n)throw new TypeError("Arguments to path.resolve must be strings");if(!n)return"";e=n+"/"+e,r=se.isAbs(n)}return(r?"/":"")+(e=se.normalizeArray(e.split("/").filter(e=>!!e),!r).join("/"))||"."},relative:(e,r)=>{function t(e){for(var r=0;r=0&&""===e[t];t--);return r>t?[]:e.slice(r,t-r+1)}e=ue.resolve(e).substr(1),r=ue.resolve(r).substr(1);for(var n=t(e.split("/")),o=t(r.split("/")),a=Math.min(n.length,o.length),i=a,s=0;s0?t:z(e)+1,o=new Array(n),a=R(e,o,0,o.length);return r&&(o.length=a),o}var le={ttys:[],init:function(){},shutdown:function(){},register:function(e,r){le.ttys[e]={input:[],output:[],ops:r},pe.registerDevice(e,le.stream_ops)},stream_ops:{open:function(e){var r=le.ttys[e.node.rdev];if(!r)throw new pe.ErrnoError(43);e.tty=r,e.seekable=!1},close:function(e){e.tty.ops.fsync(e.tty)},fsync:function(e){e.tty.ops.fsync(e.tty)},read:function(e,r,t,n,o){if(!e.tty||!e.tty.ops.get_char)throw new pe.ErrnoError(60);for(var a=0,i=0;i0?t.slice(0,n).toString("utf-8"):null}else"undefined"!=typeof window&&"function"==typeof window.prompt?null!==(r=window.prompt("Input: "))&&(r+="\n"):"function"==typeof readline&&null!==(r=readline())&&(r+="\n");if(!r)return null;e.input=ce(r,!0)}return e.input.shift()},put_char:function(e,r){null===r||10===r?(y(x(e.output,0)),e.output=[]):0!=r&&e.output.push(r)},fsync:function(e){e.output&&e.output.length>0&&(y(x(e.output,0)),e.output=[])}},default_tty1_ops:{put_char:function(e,r){null===r||10===r?(g(x(e.output,0)),e.output=[]):0!=r&&e.output.push(r)},fsync:function(e){e.output&&e.output.length>0&&(g(x(e.output,0)),e.output=[])}}};function fe(e){K()}var de={ops_table:null,mount:function(e){return de.createNode(null,"/",16895,0)},createNode:function(e,r,t,n){if(pe.isBlkdev(t)||pe.isFIFO(t))throw new pe.ErrnoError(63);de.ops_table||(de.ops_table={dir:{node:{getattr:de.node_ops.getattr,setattr:de.node_ops.setattr,lookup:de.node_ops.lookup,mknod:de.node_ops.mknod,rename:de.node_ops.rename,unlink:de.node_ops.unlink,rmdir:de.node_ops.rmdir,readdir:de.node_ops.readdir,symlink:de.node_ops.symlink},stream:{llseek:de.stream_ops.llseek}},file:{node:{getattr:de.node_ops.getattr,setattr:de.node_ops.setattr},stream:{llseek:de.stream_ops.llseek,read:de.stream_ops.read,write:de.stream_ops.write,allocate:de.stream_ops.allocate,mmap:de.stream_ops.mmap,msync:de.stream_ops.msync}},link:{node:{getattr:de.node_ops.getattr,setattr:de.node_ops.setattr,readlink:de.node_ops.readlink},stream:{}},chrdev:{node:{getattr:de.node_ops.getattr,setattr:de.node_ops.setattr},stream:pe.chrdev_stream_ops}});var o=pe.createNode(e,r,t,n);return pe.isDir(o.mode)?(o.node_ops=de.ops_table.dir.node,o.stream_ops=de.ops_table.dir.stream,o.contents={}):pe.isFile(o.mode)?(o.node_ops=de.ops_table.file.node,o.stream_ops=de.ops_table.file.stream,o.usedBytes=0,o.contents=null):pe.isLink(o.mode)?(o.node_ops=de.ops_table.link.node,o.stream_ops=de.ops_table.link.stream):pe.isChrdev(o.mode)&&(o.node_ops=de.ops_table.chrdev.node,o.stream_ops=de.ops_table.chrdev.stream),o.timestamp=Date.now(),e&&(e.contents[r]=o,e.timestamp=o.timestamp),o},getFileDataAsTypedArray:function(e){return e.contents?e.contents.subarray?e.contents.subarray(0,e.usedBytes):new Uint8Array(e.contents):new Uint8Array(0)},expandFileStorage:function(e,r){var t=e.contents?e.contents.length:0;if(!(t>=r)){r=Math.max(r,t*(t<1048576?2:1.125)>>>0),0!=t&&(r=Math.max(r,256));var n=e.contents;e.contents=new Uint8Array(r),e.usedBytes>0&&e.contents.set(n.subarray(0,e.usedBytes),0)}},resizeFileStorage:function(e,r){if(e.usedBytes!=r)if(0==r)e.contents=null,e.usedBytes=0;else{var t=e.contents;e.contents=new Uint8Array(r),t&&e.contents.set(t.subarray(0,Math.min(r,e.usedBytes))),e.usedBytes=r}},node_ops:{getattr:function(e){var r={};return r.dev=pe.isChrdev(e.mode)?e.id:1,r.ino=e.id,r.mode=e.mode,r.nlink=1,r.uid=0,r.gid=0,r.rdev=e.rdev,pe.isDir(e.mode)?r.size=4096:pe.isFile(e.mode)?r.size=e.usedBytes:pe.isLink(e.mode)?r.size=e.link.length:r.size=0,r.atime=new Date(e.timestamp),r.mtime=new Date(e.timestamp),r.ctime=new Date(e.timestamp),r.blksize=4096,r.blocks=Math.ceil(r.size/r.blksize),r},setattr:function(e,r){void 0!==r.mode&&(e.mode=r.mode),void 0!==r.timestamp&&(e.timestamp=r.timestamp),void 0!==r.size&&de.resizeFileStorage(e,r.size)},lookup:function(e,r){throw pe.genericErrors[44]},mknod:function(e,r,t,n){return de.createNode(e,r,t,n)},rename:function(e,r,t){if(pe.isDir(e.mode)){var n;try{n=pe.lookupNode(r,t)}catch(e){}if(n)for(var o in n.contents)throw new pe.ErrnoError(55)}delete e.parent.contents[e.name],e.parent.timestamp=Date.now(),e.name=t,r.contents[t]=e,r.timestamp=e.parent.timestamp,e.parent=r},unlink:function(e,r){delete e.contents[r],e.timestamp=Date.now()},rmdir:function(e,r){var t=pe.lookupNode(e,r);for(var n in t.contents)throw new pe.ErrnoError(55);delete e.contents[r],e.timestamp=Date.now()},readdir:function(e){var r=[".",".."];for(var t in e.contents)e.contents.hasOwnProperty(t)&&r.push(t);return r},symlink:function(e,r,t){var n=de.createNode(e,r,41471,0);return n.link=t,n},readlink:function(e){if(!pe.isLink(e.mode))throw new pe.ErrnoError(28);return e.link}},stream_ops:{read:function(e,r,t,n,o){var a=e.node.contents;if(o>=e.node.usedBytes)return 0;var i=Math.min(e.node.usedBytes-o,n);if(i>8&&a.subarray)r.set(a.subarray(o,o+i),t);else for(var s=0;s0||t+r{if(!(e=ue.resolve(e)))return{path:"",node:null};if((r=Object.assign({follow_mount:!0,recurse_count:0},r)).recurse_count>8)throw new pe.ErrnoError(32);for(var t=e.split("/").filter(e=>!!e),n=pe.root,o="/",a=0;a40)throw new pe.ErrnoError(32)}}return{path:o,node:n}},getPath:e=>{for(var r;;){if(pe.isRoot(e)){var t=e.mount.mountpoint;return r?"/"!==t[t.length-1]?t+"/"+r:t+r:t}r=r?e.name+"/"+r:e.name,e=e.parent}},hashName:(e,r)=>{for(var t=0,n=0;n>>0)%pe.nameTable.length},hashAddNode:e=>{var r=pe.hashName(e.parent.id,e.name);e.name_next=pe.nameTable[r],pe.nameTable[r]=e},hashRemoveNode:e=>{var r=pe.hashName(e.parent.id,e.name);if(pe.nameTable[r]===e)pe.nameTable[r]=e.name_next;else for(var t=pe.nameTable[r];t;){if(t.name_next===e){t.name_next=e.name_next;break}t=t.name_next}},lookupNode:(e,r)=>{var t=pe.mayLookup(e);if(t)throw new pe.ErrnoError(t,e);for(var n=pe.hashName(e.id,r),o=pe.nameTable[n];o;o=o.name_next){var a=o.name;if(o.parent.id===e.id&&a===r)return o}return pe.lookup(e,r)},createNode:(e,r,t,n)=>{var o=new pe.FSNode(e,r,t,n);return pe.hashAddNode(o),o},destroyNode:e=>{pe.hashRemoveNode(e)},isRoot:e=>e===e.parent,isMountpoint:e=>!!e.mounted,isFile:e=>32768==(61440&e),isDir:e=>16384==(61440&e),isLink:e=>40960==(61440&e),isChrdev:e=>8192==(61440&e),isBlkdev:e=>24576==(61440&e),isFIFO:e=>4096==(61440&e),isSocket:e=>49152==(49152&e),flagModes:{r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090},modeStringToFlags:e=>{var r=pe.flagModes[e];if(void 0===r)throw new Error("Unknown file open mode: "+e);return r},flagsToPermissionString:e=>{var r=["r","w","rw"][3&e];return 512&e&&(r+="w"),r},nodePermissions:(e,r)=>pe.ignorePermissions?0:(!r.includes("r")||292&e.mode)&&(!r.includes("w")||146&e.mode)&&(!r.includes("x")||73&e.mode)?0:2,mayLookup:e=>{var r=pe.nodePermissions(e,"x");return r||(e.node_ops.lookup?0:2)},mayCreate:(e,r)=>{try{pe.lookupNode(e,r);return 20}catch(e){}return pe.nodePermissions(e,"wx")},mayDelete:(e,r,t)=>{var n;try{n=pe.lookupNode(e,r)}catch(e){return e.errno}var o=pe.nodePermissions(e,"wx");if(o)return o;if(t){if(!pe.isDir(n.mode))return 54;if(pe.isRoot(n)||pe.getPath(n)===pe.cwd())return 10}else if(pe.isDir(n.mode))return 31;return 0},mayOpen:(e,r)=>e?pe.isLink(e.mode)?32:pe.isDir(e.mode)&&("r"!==pe.flagsToPermissionString(r)||512&r)?31:pe.nodePermissions(e,pe.flagsToPermissionString(r)):44,MAX_OPEN_FDS:4096,nextfd:(e=0,r=pe.MAX_OPEN_FDS)=>{for(var t=e;t<=r;t++)if(!pe.streams[t])return t;throw new pe.ErrnoError(33)},getStream:e=>pe.streams[e],createStream:(e,r,t)=>{pe.FSStream||(pe.FSStream=function(){this.shared={}},pe.FSStream.prototype={},Object.defineProperties(pe.FSStream.prototype,{object:{get:function(){return this.node},set:function(e){this.node=e}},isRead:{get:function(){return 1!=(2097155&this.flags)}},isWrite:{get:function(){return 0!=(2097155&this.flags)}},isAppend:{get:function(){return 1024&this.flags}},flags:{get:function(){return this.shared.flags},set:function(e){this.shared.flags=e}},position:{get:function(){return this.shared.position},set:function(e){this.shared.position=e}}})),e=Object.assign(new pe.FSStream,e);var n=pe.nextfd(r,t);return e.fd=n,pe.streams[n]=e,e},closeStream:e=>{pe.streams[e]=null},chrdev_stream_ops:{open:e=>{var r=pe.getDevice(e.node.rdev);e.stream_ops=r.stream_ops,e.stream_ops.open&&e.stream_ops.open(e)},llseek:()=>{throw new pe.ErrnoError(70)}},major:e=>e>>8,minor:e=>255&e,makedev:(e,r)=>e<<8|r,registerDevice:(e,r)=>{pe.devices[e]={stream_ops:r}},getDevice:e=>pe.devices[e],getMounts:e=>{for(var r=[],t=[e];t.length;){var n=t.pop();r.push(n),t.push.apply(t,n.mounts)}return r},syncfs:(e,r)=>{"function"==typeof e&&(r=e,e=!1),pe.syncFSRequests++,pe.syncFSRequests>1&&g("warning: "+pe.syncFSRequests+" FS.syncfs operations in flight at once, probably just doing extra work");var t=pe.getMounts(pe.root.mount),n=0;function o(e){return pe.syncFSRequests--,r(e)}function a(e){if(e)return a.errored?void 0:(a.errored=!0,o(e));++n>=t.length&&o(null)}t.forEach(r=>{if(!r.type.syncfs)return a(null);r.type.syncfs(r,e,a)})},mount:(e,r,t)=>{var n,o="/"===t,a=!t;if(o&&pe.root)throw new pe.ErrnoError(10);if(!o&&!a){var i=pe.lookupPath(t,{follow_mount:!1});if(t=i.path,n=i.node,pe.isMountpoint(n))throw new pe.ErrnoError(10);if(!pe.isDir(n.mode))throw new pe.ErrnoError(54)}var s={type:e,opts:r,mountpoint:t,mounts:[]},u=e.mount(s);return u.mount=s,s.root=u,o?pe.root=u:n&&(n.mounted=s,n.mount&&n.mount.mounts.push(s)),u},unmount:e=>{var r=pe.lookupPath(e,{follow_mount:!1});if(!pe.isMountpoint(r.node))throw new pe.ErrnoError(28);var t=r.node,n=t.mounted,o=pe.getMounts(n);Object.keys(pe.nameTable).forEach(e=>{for(var r=pe.nameTable[e];r;){var t=r.name_next;o.includes(r.mount)&&pe.destroyNode(r),r=t}}),t.mounted=null;var a=t.mount.mounts.indexOf(n);t.mount.mounts.splice(a,1)},lookup:(e,r)=>e.node_ops.lookup(e,r),mknod:(e,r,t)=>{var n=pe.lookupPath(e,{parent:!0}).node,o=se.basename(e);if(!o||"."===o||".."===o)throw new pe.ErrnoError(28);var a=pe.mayCreate(n,o);if(a)throw new pe.ErrnoError(a);if(!n.node_ops.mknod)throw new pe.ErrnoError(63);return n.node_ops.mknod(n,o,r,t)},create:(e,r)=>(r=void 0!==r?r:438,r&=4095,r|=32768,pe.mknod(e,r,0)),mkdir:(e,r)=>(r=void 0!==r?r:511,r&=1023,r|=16384,pe.mknod(e,r,0)),mkdirTree:(e,r)=>{for(var t=e.split("/"),n="",o=0;o(void 0===t&&(t=r,r=438),r|=8192,pe.mknod(e,r,t)),symlink:(e,r)=>{if(!ue.resolve(e))throw new pe.ErrnoError(44);var t=pe.lookupPath(r,{parent:!0}).node;if(!t)throw new pe.ErrnoError(44);var n=se.basename(r),o=pe.mayCreate(t,n);if(o)throw new pe.ErrnoError(o);if(!t.node_ops.symlink)throw new pe.ErrnoError(63);return t.node_ops.symlink(t,n,e)},rename:(e,r)=>{var t,n,o=se.dirname(e),a=se.dirname(r),i=se.basename(e),s=se.basename(r);if(t=pe.lookupPath(e,{parent:!0}).node,n=pe.lookupPath(r,{parent:!0}).node,!t||!n)throw new pe.ErrnoError(44);if(t.mount!==n.mount)throw new pe.ErrnoError(75);var u,c=pe.lookupNode(t,i),l=ue.relative(e,a);if("."!==l.charAt(0))throw new pe.ErrnoError(28);if("."!==(l=ue.relative(r,o)).charAt(0))throw new pe.ErrnoError(55);try{u=pe.lookupNode(n,s)}catch(e){}if(c!==u){var f=pe.isDir(c.mode),d=pe.mayDelete(t,i,f);if(d)throw new pe.ErrnoError(d);if(d=u?pe.mayDelete(n,s,f):pe.mayCreate(n,s))throw new pe.ErrnoError(d);if(!t.node_ops.rename)throw new pe.ErrnoError(63);if(pe.isMountpoint(c)||u&&pe.isMountpoint(u))throw new pe.ErrnoError(10);if(n!==t&&(d=pe.nodePermissions(t,"w")))throw new pe.ErrnoError(d);pe.hashRemoveNode(c);try{t.node_ops.rename(c,n,s)}catch(e){throw e}finally{pe.hashAddNode(c)}}},rmdir:e=>{var r=pe.lookupPath(e,{parent:!0}).node,t=se.basename(e),n=pe.lookupNode(r,t),o=pe.mayDelete(r,t,!0);if(o)throw new pe.ErrnoError(o);if(!r.node_ops.rmdir)throw new pe.ErrnoError(63);if(pe.isMountpoint(n))throw new pe.ErrnoError(10);r.node_ops.rmdir(r,t),pe.destroyNode(n)},readdir:e=>{var r=pe.lookupPath(e,{follow:!0}).node;if(!r.node_ops.readdir)throw new pe.ErrnoError(54);return r.node_ops.readdir(r)},unlink:e=>{var r=pe.lookupPath(e,{parent:!0}).node;if(!r)throw new pe.ErrnoError(44);var t=se.basename(e),n=pe.lookupNode(r,t),o=pe.mayDelete(r,t,!1);if(o)throw new pe.ErrnoError(o);if(!r.node_ops.unlink)throw new pe.ErrnoError(63);if(pe.isMountpoint(n))throw new pe.ErrnoError(10);r.node_ops.unlink(r,t),pe.destroyNode(n)},readlink:e=>{var r=pe.lookupPath(e).node;if(!r)throw new pe.ErrnoError(44);if(!r.node_ops.readlink)throw new pe.ErrnoError(28);return ue.resolve(pe.getPath(r.parent),r.node_ops.readlink(r))},stat:(e,r)=>{var t=pe.lookupPath(e,{follow:!r}).node;if(!t)throw new pe.ErrnoError(44);if(!t.node_ops.getattr)throw new pe.ErrnoError(63);return t.node_ops.getattr(t)},lstat:e=>pe.stat(e,!0),chmod:(e,r,t)=>{var n;"string"==typeof e?n=pe.lookupPath(e,{follow:!t}).node:n=e;if(!n.node_ops.setattr)throw new pe.ErrnoError(63);n.node_ops.setattr(n,{mode:4095&r|-4096&n.mode,timestamp:Date.now()})},lchmod:(e,r)=>{pe.chmod(e,r,!0)},fchmod:(e,r)=>{var t=pe.getStream(e);if(!t)throw new pe.ErrnoError(8);pe.chmod(t.node,r)},chown:(e,r,t,n)=>{var o;"string"==typeof e?o=pe.lookupPath(e,{follow:!n}).node:o=e;if(!o.node_ops.setattr)throw new pe.ErrnoError(63);o.node_ops.setattr(o,{timestamp:Date.now()})},lchown:(e,r,t)=>{pe.chown(e,r,t,!0)},fchown:(e,r,t)=>{var n=pe.getStream(e);if(!n)throw new pe.ErrnoError(8);pe.chown(n.node,r,t)},truncate:(e,r)=>{if(r<0)throw new pe.ErrnoError(28);var t;"string"==typeof e?t=pe.lookupPath(e,{follow:!0}).node:t=e;if(!t.node_ops.setattr)throw new pe.ErrnoError(63);if(pe.isDir(t.mode))throw new pe.ErrnoError(31);if(!pe.isFile(t.mode))throw new pe.ErrnoError(28);var n=pe.nodePermissions(t,"w");if(n)throw new pe.ErrnoError(n);t.node_ops.setattr(t,{size:r,timestamp:Date.now()})},ftruncate:(e,r)=>{var t=pe.getStream(e);if(!t)throw new pe.ErrnoError(8);if(0==(2097155&t.flags))throw new pe.ErrnoError(28);pe.truncate(t.node,r)},utime:(e,r,t)=>{var n=pe.lookupPath(e,{follow:!0}).node;n.node_ops.setattr(n,{timestamp:Math.max(r,t)})},open:(e,r,t)=>{if(""===e)throw new pe.ErrnoError(44);var n;if(t=void 0===t?438:t,t=64&(r="string"==typeof r?pe.modeStringToFlags(r):r)?4095&t|32768:0,"object"==typeof e)n=e;else{e=se.normalize(e);try{n=pe.lookupPath(e,{follow:!(131072&r)}).node}catch(e){}}var o=!1;if(64&r)if(n){if(128&r)throw new pe.ErrnoError(20)}else n=pe.mknod(e,t,0),o=!0;if(!n)throw new pe.ErrnoError(44);if(pe.isChrdev(n.mode)&&(r&=-513),65536&r&&!pe.isDir(n.mode))throw new pe.ErrnoError(54);if(!o){var i=pe.mayOpen(n,r);if(i)throw new pe.ErrnoError(i)}512&r&&!o&&pe.truncate(n,0),r&=-131713;var s=pe.createStream({node:n,path:pe.getPath(n),flags:r,seekable:!0,position:0,stream_ops:n.stream_ops,ungotten:[],error:!1});return s.stream_ops.open&&s.stream_ops.open(s),!a.logReadFiles||1&r||(pe.readFiles||(pe.readFiles={}),e in pe.readFiles||(pe.readFiles[e]=1)),s},close:e=>{if(pe.isClosed(e))throw new pe.ErrnoError(8);e.getdents&&(e.getdents=null);try{e.stream_ops.close&&e.stream_ops.close(e)}catch(e){throw e}finally{pe.closeStream(e.fd)}e.fd=null},isClosed:e=>null===e.fd,llseek:(e,r,t)=>{if(pe.isClosed(e))throw new pe.ErrnoError(8);if(!e.seekable||!e.stream_ops.llseek)throw new pe.ErrnoError(70);if(0!=t&&1!=t&&2!=t)throw new pe.ErrnoError(28);return e.position=e.stream_ops.llseek(e,r,t),e.ungotten=[],e.position},read:(e,r,t,n,o)=>{if(n<0||o<0)throw new pe.ErrnoError(28);if(pe.isClosed(e))throw new pe.ErrnoError(8);if(1==(2097155&e.flags))throw new pe.ErrnoError(8);if(pe.isDir(e.node.mode))throw new pe.ErrnoError(31);if(!e.stream_ops.read)throw new pe.ErrnoError(28);var a=void 0!==o;if(a){if(!e.seekable)throw new pe.ErrnoError(70)}else o=e.position;var i=e.stream_ops.read(e,r,t,n,o);return a||(e.position+=i),i},write:(e,r,t,n,o,a)=>{if(n<0||o<0)throw new pe.ErrnoError(28);if(pe.isClosed(e))throw new pe.ErrnoError(8);if(0==(2097155&e.flags))throw new pe.ErrnoError(8);if(pe.isDir(e.node.mode))throw new pe.ErrnoError(31);if(!e.stream_ops.write)throw new pe.ErrnoError(28);e.seekable&&1024&e.flags&&pe.llseek(e,0,2);var i=void 0!==o;if(i){if(!e.seekable)throw new pe.ErrnoError(70)}else o=e.position;var s=e.stream_ops.write(e,r,t,n,o,a);return i||(e.position+=s),s},allocate:(e,r,t)=>{if(pe.isClosed(e))throw new pe.ErrnoError(8);if(r<0||t<=0)throw new pe.ErrnoError(28);if(0==(2097155&e.flags))throw new pe.ErrnoError(8);if(!pe.isFile(e.node.mode)&&!pe.isDir(e.node.mode))throw new pe.ErrnoError(43);if(!e.stream_ops.allocate)throw new pe.ErrnoError(138);e.stream_ops.allocate(e,r,t)},mmap:(e,r,t,n,o)=>{if(0!=(2&n)&&0==(2&o)&&2!=(2097155&e.flags))throw new pe.ErrnoError(2);if(1==(2097155&e.flags))throw new pe.ErrnoError(2);if(!e.stream_ops.mmap)throw new pe.ErrnoError(43);return e.stream_ops.mmap(e,r,t,n,o)},msync:(e,r,t,n,o)=>e.stream_ops.msync?e.stream_ops.msync(e,r,t,n,o):0,munmap:e=>0,ioctl:(e,r,t)=>{if(!e.stream_ops.ioctl)throw new pe.ErrnoError(59);return e.stream_ops.ioctl(e,r,t)},readFile:(e,r={})=>{if(r.flags=r.flags||0,r.encoding=r.encoding||"binary","utf8"!==r.encoding&&"binary"!==r.encoding)throw new Error('Invalid encoding type "'+r.encoding+'"');var t,n=pe.open(e,r.flags),o=pe.stat(e).size,a=new Uint8Array(o);return pe.read(n,a,0,o,0),"utf8"===r.encoding?t=x(a,0):"binary"===r.encoding&&(t=a),pe.close(n),t},writeFile:(e,r,t={})=>{t.flags=t.flags||577;var n=pe.open(e,t.flags,t.mode);if("string"==typeof r){var o=new Uint8Array(z(r)+1),a=R(r,o,0,o.length);pe.write(n,o,0,a,void 0,t.canOwn)}else{if(!ArrayBuffer.isView(r))throw new Error("Unsupported data type");pe.write(n,r,0,r.byteLength,void 0,t.canOwn)}pe.close(n)},cwd:()=>pe.currentPath,chdir:e=>{var r=pe.lookupPath(e,{follow:!0});if(null===r.node)throw new pe.ErrnoError(44);if(!pe.isDir(r.node.mode))throw new pe.ErrnoError(54);var t=pe.nodePermissions(r.node,"x");if(t)throw new pe.ErrnoError(t);pe.currentPath=r.path},createDefaultDirectories:()=>{pe.mkdir("/tmp"),pe.mkdir("/home"),pe.mkdir("/home/web_user")},createDefaultDevices:()=>{pe.mkdir("/dev"),pe.registerDevice(pe.makedev(1,3),{read:()=>0,write:(e,r,t,n,o)=>n}),pe.mkdev("/dev/null",pe.makedev(1,3)),le.register(pe.makedev(5,0),le.default_tty_ops),le.register(pe.makedev(6,0),le.default_tty1_ops),pe.mkdev("/dev/tty",pe.makedev(5,0)),pe.mkdev("/dev/tty1",pe.makedev(6,0));var e=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var e=new Uint8Array(1);return()=>(crypto.getRandomValues(e),e[0])}if(h)try{var r=require("crypto");return()=>r.randomBytes(1)[0]}catch(e){}return()=>K("randomDevice")}();pe.createDevice("/dev","random",e),pe.createDevice("/dev","urandom",e),pe.mkdir("/dev/shm"),pe.mkdir("/dev/shm/tmp")},createSpecialDirectories:()=>{pe.mkdir("/proc");var e=pe.mkdir("/proc/self");pe.mkdir("/proc/self/fd"),pe.mount({mount:()=>{var r=pe.createNode(e,"fd",16895,73);return r.node_ops={lookup:(e,r)=>{var t=+r,n=pe.getStream(t);if(!n)throw new pe.ErrnoError(8);var o={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>n.path}};return o.parent=o,o}},r}},{},"/proc/self/fd")},createStandardStreams:()=>{a.stdin?pe.createDevice("/dev","stdin",a.stdin):pe.symlink("/dev/tty","/dev/stdin"),a.stdout?pe.createDevice("/dev","stdout",null,a.stdout):pe.symlink("/dev/tty","/dev/stdout"),a.stderr?pe.createDevice("/dev","stderr",null,a.stderr):pe.symlink("/dev/tty1","/dev/stderr");pe.open("/dev/stdin",0),pe.open("/dev/stdout",1),pe.open("/dev/stderr",1)},ensureErrnoError:()=>{pe.ErrnoError||(pe.ErrnoError=function(e,r){this.node=r,this.setErrno=function(e){this.errno=e},this.setErrno(e),this.message="FS error"},pe.ErrnoError.prototype=new Error,pe.ErrnoError.prototype.constructor=pe.ErrnoError,[44].forEach(e=>{pe.genericErrors[e]=new pe.ErrnoError(e),pe.genericErrors[e].stack=""}))},staticInit:()=>{pe.ensureErrnoError(),pe.nameTable=new Array(4096),pe.mount(de,{},"/"),pe.createDefaultDirectories(),pe.createDefaultDevices(),pe.createSpecialDirectories(),pe.filesystems={MEMFS:de}},init:(e,r,t)=>{pe.init.initialized=!0,pe.ensureErrnoError(),a.stdin=e||a.stdin,a.stdout=r||a.stdout,a.stderr=t||a.stderr,pe.createStandardStreams()},quit:()=>{pe.init.initialized=!1;for(var e=0;e{var t=0;return e&&(t|=365),r&&(t|=146),t},findObject:(e,r)=>{var t=pe.analyzePath(e,r);return t.exists?t.object:null},analyzePath:(e,r)=>{try{e=(n=pe.lookupPath(e,{follow:!r})).path}catch(e){}var t={isRoot:!1,exists:!1,error:0,name:null,path:null,object:null,parentExists:!1,parentPath:null,parentObject:null};try{var n=pe.lookupPath(e,{parent:!0});t.parentExists=!0,t.parentPath=n.path,t.parentObject=n.node,t.name=se.basename(e),n=pe.lookupPath(e,{follow:!r}),t.exists=!0,t.path=n.path,t.object=n.node,t.name=n.node.name,t.isRoot="/"===n.path}catch(e){t.error=e.errno}return t},createPath:(e,r,t,n)=>{e="string"==typeof e?e:pe.getPath(e);for(var o=r.split("/").reverse();o.length;){var a=o.pop();if(a){var i=se.join2(e,a);try{pe.mkdir(i)}catch(e){}e=i}}return i},createFile:(e,r,t,n,o)=>{var a=se.join2("string"==typeof e?e:pe.getPath(e),r),i=pe.getMode(n,o);return pe.create(a,i)},createDataFile:(e,r,t,n,o,a)=>{var i=r;e&&(e="string"==typeof e?e:pe.getPath(e),i=r?se.join2(e,r):e);var s=pe.getMode(n,o),u=pe.create(i,s);if(t){if("string"==typeof t){for(var c=new Array(t.length),l=0,f=t.length;l{var o=se.join2("string"==typeof e?e:pe.getPath(e),r),a=pe.getMode(!!t,!!n);pe.createDevice.major||(pe.createDevice.major=64);var i=pe.makedev(pe.createDevice.major++,0);return pe.registerDevice(i,{open:e=>{e.seekable=!1},close:e=>{n&&n.buffer&&n.buffer.length&&n(10)},read:(e,r,n,o,a)=>{for(var i=0,s=0;s{for(var i=0;i{if(e.isDevice||e.isFolder||e.link||e.contents)return!0;if("undefined"!=typeof XMLHttpRequest)throw new Error("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.");if(!i)throw new Error("Cannot load without read() or XMLHttpRequest.");try{e.contents=ce(i(e.url),!0),e.usedBytes=e.contents.length}catch(e){throw new pe.ErrnoError(29)}},createLazyFile:(e,r,t,n,o)=>{function a(){this.lengthKnown=!1,this.chunks=[]}if(a.prototype.get=function(e){if(!(e>this.length-1||e<0)){var r=e%this.chunkSize,t=e/this.chunkSize|0;return this.getter(t)[r]}},a.prototype.setDataGetter=function(e){this.getter=e},a.prototype.cacheLength=function(){var e=new XMLHttpRequest;if(e.open("HEAD",t,!1),e.send(null),!(e.status>=200&&e.status<300||304===e.status))throw new Error("Couldn't load "+t+". Status: "+e.status);var r,n=Number(e.getResponseHeader("Content-length")),o=(r=e.getResponseHeader("Accept-Ranges"))&&"bytes"===r,a=(r=e.getResponseHeader("Content-Encoding"))&&"gzip"===r,i=1048576;o||(i=n);var s=this;s.setDataGetter(e=>{var r=e*i,o=(e+1)*i-1;if(o=Math.min(o,n-1),void 0===s.chunks[e]&&(s.chunks[e]=((e,r)=>{if(e>r)throw new Error("invalid range ("+e+", "+r+") or no bytes requested!");if(r>n-1)throw new Error("only "+n+" bytes available! programmer error!");var o=new XMLHttpRequest;if(o.open("GET",t,!1),n!==i&&o.setRequestHeader("Range","bytes="+e+"-"+r),o.responseType="arraybuffer",o.overrideMimeType&&o.overrideMimeType("text/plain; charset=x-user-defined"),o.send(null),!(o.status>=200&&o.status<300||304===o.status))throw new Error("Couldn't load "+t+". Status: "+o.status);return void 0!==o.response?new Uint8Array(o.response||[]):ce(o.responseText||"",!0)})(r,o)),void 0===s.chunks[e])throw new Error("doXHR failed!");return s.chunks[e]}),!a&&n||(i=n=1,n=this.getter(0).length,i=n,y("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=n,this._chunkSize=i,this.lengthKnown=!0},"undefined"!=typeof XMLHttpRequest){if(!p)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var i=new a;Object.defineProperties(i,{length:{get:function(){return this.lengthKnown||this.cacheLength(),this._length}},chunkSize:{get:function(){return this.lengthKnown||this.cacheLength(),this._chunkSize}}});var s={isDevice:!1,contents:i}}else s={isDevice:!1,url:t};var u=pe.createFile(e,r,s,n,o);s.contents?u.contents=s.contents:s.url&&(u.contents=null,u.url=s.url),Object.defineProperties(u,{usedBytes:{get:function(){return this.contents.length}}});var c={};function l(e,r,t,n,o){var a=e.node.contents;if(o>=a.length)return 0;var i=Math.min(a.length-o,n);if(a.slice)for(var s=0;s{var r=u.stream_ops[e];c[e]=function(){return pe.forceLoadFile(u),r.apply(null,arguments)}}),c.read=((e,r,t,n,o)=>(pe.forceLoadFile(u),l(e,r,t,n,o))),c.mmap=((e,r,t,n,o)=>{pe.forceLoadFile(u);var a=fe();if(!a)throw new pe.ErrnoError(48);return l(e,C,a,r,t),{ptr:a,allocated:!0}}),u.stream_ops=c,u},createPreloadedFile:(e,r,t,n,o,a,i,u,c,l)=>{var f=r?ue.resolve(se.join2(e,r)):e;G("cp "+f);function d(t){function s(t){l&&l(),u||pe.createDataFile(e,r,t,n,o,c),a&&a(),Y()}Browser.handledByPreloadPlugin(t,f,s,()=>{i&&i(),Y()})||s(t)}X(),"string"==typeof t?function(e,r,t,n){var o=n?"":G("al "+e);s(e,t=>{P(t,'Loading data file "'+e+'" failed (no arrayBuffer).'),r(new Uint8Array(t)),o&&Y()},r=>{if(!t)throw'Loading data file "'+e+'" failed.';t()}),o&&X()}(t,e=>d(e),i):d(t)},indexedDB:()=>window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB,DB_NAME:()=>"EM_FS_"+window.location.pathname,DB_VERSION:20,DB_STORE_NAME:"FILE_DATA",saveFilesToDB:(e,r,t)=>{r=r||(()=>{}),t=t||(()=>{});var n=pe.indexedDB();try{var o=n.open(pe.DB_NAME(),pe.DB_VERSION)}catch(e){return t(e)}o.onupgradeneeded=(()=>{y("creating db"),o.result.createObjectStore(pe.DB_STORE_NAME)}),o.onsuccess=(()=>{var n=o.result.transaction([pe.DB_STORE_NAME],"readwrite"),a=n.objectStore(pe.DB_STORE_NAME),i=0,s=0,u=e.length;function c(){0==s?r():t()}e.forEach(e=>{var r=a.put(pe.analyzePath(e).object.contents,e);r.onsuccess=(()=>{++i+s==u&&c()}),r.onerror=(()=>{i+ ++s==u&&c()})}),n.onerror=t}),o.onerror=t},loadFilesFromDB:(e,r,t)=>{r=r||(()=>{}),t=t||(()=>{});var n=pe.indexedDB();try{var o=n.open(pe.DB_NAME(),pe.DB_VERSION)}catch(e){return t(e)}o.onupgradeneeded=t,o.onsuccess=(()=>{var n=o.result;try{var a=n.transaction([pe.DB_STORE_NAME],"readonly")}catch(e){return void t(e)}var i=a.objectStore(pe.DB_STORE_NAME),s=0,u=0,c=e.length;function l(){0==u?r():t()}e.forEach(e=>{var r=i.get(e);r.onsuccess=(()=>{pe.analyzePath(e).exists&&pe.unlink(e),pe.createDataFile(se.dirname(e),se.basename(e),r.result,!0,!0,!0),++s+u==c&&l()}),r.onerror=(()=>{s+ ++u==c&&l()})}),a.onerror=t}),o.onerror=t}},he={mount:function(e){return a.websocket=a.websocket&&"object"==typeof a.websocket?a.websocket:{},a.websocket._callbacks={},a.websocket.on=function(e,r){return"function"==typeof r&&(this._callbacks[e]=r),this},a.websocket.emit=function(e,r){"function"==typeof this._callbacks[e]&&this._callbacks[e].call(this,r)},pe.createNode(null,"/",16895,0)},createSocket:function(e,r,t){if(1==(r&=-526337)&&t&&6!=t)throw new pe.ErrnoError(66);var n={family:e,type:r,protocol:t,server:null,error:null,peers:{},pending:[],recv_queue:[],sock_ops:he.websocket_sock_ops},o=he.nextname(),a=pe.createNode(he.root,o,49152,0);a.sock=n;var i=pe.createStream({path:o,node:a,flags:2,seekable:!1,stream_ops:he.stream_ops});return n.stream=i,n},getSocket:function(e){var r=pe.getStream(e);return r&&pe.isSocket(r.node.mode)?r.node.sock:null},stream_ops:{poll:function(e){var r=e.node.sock;return r.sock_ops.poll(r)},ioctl:function(e,r,t){var n=e.node.sock;return n.sock_ops.ioctl(n,r,t)},read:function(e,r,t,n,o){var a=e.node.sock,i=a.sock_ops.recvmsg(a,n);return i?(r.set(i.buffer,t),i.buffer.length):0},write:function(e,r,t,n,o){var a=e.node.sock;return a.sock_ops.sendmsg(a,r,t,n)},close:function(e){var r=e.node.sock;r.sock_ops.close(r)}},nextname:function(){return he.nextname.current||(he.nextname.current=0),"socket["+he.nextname.current+++"]"},websocket_sock_ops:{createPeer:function(e,r,t){var n;if("object"==typeof r&&(n=r,r=null,t=null),n)if(n._socket)r=n._socket.remoteAddress,t=n._socket.remotePort;else{var o=/ws[s]?:\/\/([^:]+):(\d+)/.exec(n.url);if(!o)throw new Error("WebSocket URL must be in the format ws(s)://address:port");r=o[1],t=parseInt(o[2],10)}else try{var i=a.websocket&&"object"==typeof a.websocket,s="ws:#".replace("#","//");if(i&&"string"==typeof a.websocket.url&&(s=a.websocket.url),"ws://"===s||"wss://"===s){var u=r.split("/");s=s+u[0]+":"+t+"/"+u.slice(1).join("/")}var c="binary";i&&"string"==typeof a.websocket.subprotocol&&(c=a.websocket.subprotocol);var l=void 0;"null"!==c&&(l=c=c.replace(/^ +| +$/g,"").split(/ *, */)),i&&null===a.websocket.subprotocol&&(c="null",l=void 0),(n=new(h?require("ws"):WebSocket)(s,l)).binaryType="arraybuffer"}catch(e){throw new pe.ErrnoError(23)}var f={addr:r,port:t,socket:n,dgram_send_queue:[]};return he.websocket_sock_ops.addPeer(e,f),he.websocket_sock_ops.handlePeerEvents(e,f),2===e.type&&void 0!==e.sport&&f.dgram_send_queue.push(new Uint8Array([255,255,255,255,"p".charCodeAt(0),"o".charCodeAt(0),"r".charCodeAt(0),"t".charCodeAt(0),(65280&e.sport)>>8,255&e.sport])),f},getPeer:function(e,r,t){return e.peers[r+":"+t]},addPeer:function(e,r){e.peers[r.addr+":"+r.port]=r},removePeer:function(e,r){delete e.peers[r.addr+":"+r.port]},handlePeerEvents:function(e,r){var t=!0,n=function(){a.websocket.emit("open",e.stream.fd);try{for(var t=r.dgram_send_queue.shift();t;)r.socket.send(t),t=r.dgram_send_queue.shift()}catch(e){r.socket.close()}};function o(n){if("string"==typeof n){n=(new TextEncoder).encode(n)}else{if(P(void 0!==n.byteLength),0==n.byteLength)return;n=new Uint8Array(n)}var o=t;if(t=!1,o&&10===n.length&&255===n[0]&&255===n[1]&&255===n[2]&&255===n[3]&&n[4]==="p".charCodeAt(0)&&n[5]==="o".charCodeAt(0)&&n[6]==="r".charCodeAt(0)&&n[7]==="t".charCodeAt(0)){var i=n[8]<<8|n[9];return he.websocket_sock_ops.removePeer(e,r),r.port=i,void he.websocket_sock_ops.addPeer(e,r)}e.recv_queue.push({addr:r.addr,port:r.port,data:n}),a.websocket.emit("message",e.stream.fd)}h?(r.socket.on("open",n),r.socket.on("message",function(e,r){r&&o(new Uint8Array(e).buffer)}),r.socket.on("close",function(){a.websocket.emit("close",e.stream.fd)}),r.socket.on("error",function(r){e.error=14,a.websocket.emit("error",[e.stream.fd,e.error,"ECONNREFUSED: Connection refused"])})):(r.socket.onopen=n,r.socket.onclose=function(){a.websocket.emit("close",e.stream.fd)},r.socket.onmessage=function(e){o(e.data)},r.socket.onerror=function(r){e.error=14,a.websocket.emit("error",[e.stream.fd,e.error,"ECONNREFUSED: Connection refused"])})},poll:function(e){if(1===e.type&&e.server)return e.pending.length?65:0;var r=0,t=1===e.type?he.websocket_sock_ops.getPeer(e,e.daddr,e.dport):null;return(e.recv_queue.length||!t||t&&t.socket.readyState===t.socket.CLOSING||t&&t.socket.readyState===t.socket.CLOSED)&&(r|=65),(!t||t&&t.socket.readyState===t.socket.OPEN)&&(r|=4),(t&&t.socket.readyState===t.socket.CLOSING||t&&t.socket.readyState===t.socket.CLOSED)&&(r|=16),r},ioctl:function(e,r,t){switch(r){case 21531:var n=0;return e.recv_queue.length&&(n=e.recv_queue[0].data.length),F[t>>2]=n,0;default:return 28}},close:function(e){if(e.server){try{e.server.close()}catch(e){}e.server=null}for(var r=Object.keys(e.peers),t=0;t>8&255)+"."+(e>>16&255)+"."+(e>>24&255)}function ve(e,r){var t,n=D[e>>1],o=ht(A[e+2>>1]);switch(n){case 2:if(16!==r)return{errno:28};t=me(t=F[e+4>>2]);break;case 10:if(28!==r)return{errno:28};t=function(e){var r="",t=0,n=0,o=0,a=0,i=0,s=0,u=[65535&e[0],e[0]>>16,65535&e[1],e[1]>>16,65535&e[2],e[2]>>16,65535&e[3],e[3]>>16],c=!0,l="";for(s=0;s<5;s++)if(0!==u[s]){c=!1;break}if(c){if(l=me(u[6]|u[7]<<16),-1===u[5])return r="::ffff:",r+=l;if(0===u[5])return r="::","0.0.0.0"===l&&(l=""),"0.0.0.1"===l&&(l="1"),r+=l}for(t=0;t<8;t++)0===u[t]&&(t-o>1&&(i=0),o=t,i++),i>n&&(a=t-(n=i)+1);for(t=0;t<8;t++)n>1&&0===u[t]&&t>=a&&t>2],F[e+12>>2],F[e+16>>2],F[e+20>>2]]);break;default:return{errno:5}}return{family:n,addr:t,port:o}}function we(e){return parseInt(e)}var ye={address_map:{id:1,addrs:{},names:{}},lookup_name:function(e){var r,t=function(e){for(var r=e.split("."),t=0;t<4;t++){var n=Number(r[t]);if(isNaN(n))return null;r[t]=n}return(r[0]|r[1]<<8|r[2]<<16|r[3]<<24)>>>0}(e);if(null!==t)return e;if(null!==(t=function(e){var r,t,n,o,a=[];if(!/^((?=.*::)(?!.*::.+::)(::)?([\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.test(e))return null;if("::"===e)return[0,0,0,0,0,0,0,0];for((e=e.startsWith("::")?e.replace("::","Z:"):e.replace("::",":Z:")).indexOf(".")>0?((r=(e=e.replace(new RegExp("[.]","g"),":")).split(":"))[r.length-4]=we(r[r.length-4])+256*we(r[r.length-3]),r[r.length-3]=we(r[r.length-2])+256*we(r[r.length-1]),r=r.slice(0,r.length-2)):r=e.split(":"),n=0,o=0,t=0;t>2]=n.dev,F[t+8>>2]=n.ino,F[t+12>>2]=n.mode,$[t+16>>2]=n.nlink,F[t+20>>2]=n.uid,F[t+24>>2]=n.gid,F[t+28>>2]=n.rdev,ee=[n.size>>>0,(Q=n.size,+Math.abs(Q)>=1?Q>0?(0|Math.min(+Math.floor(Q/4294967296),4294967295))>>>0:~~+Math.ceil((Q-+(~~Q>>>0))/4294967296)>>>0:0)],F[t+40>>2]=ee[0],F[t+44>>2]=ee[1],F[t+48>>2]=4096,F[t+52>>2]=n.blocks;var o=n.atime.getTime(),a=n.mtime.getTime(),i=n.ctime.getTime();return ee=[Math.floor(o/1e3)>>>0,(Q=Math.floor(o/1e3),+Math.abs(Q)>=1?Q>0?(0|Math.min(+Math.floor(Q/4294967296),4294967295))>>>0:~~+Math.ceil((Q-+(~~Q>>>0))/4294967296)>>>0:0)],F[t+56>>2]=ee[0],F[t+60>>2]=ee[1],$[t+64>>2]=o%1e3*1e3,ee=[Math.floor(a/1e3)>>>0,(Q=Math.floor(a/1e3),+Math.abs(Q)>=1?Q>0?(0|Math.min(+Math.floor(Q/4294967296),4294967295))>>>0:~~+Math.ceil((Q-+(~~Q>>>0))/4294967296)>>>0:0)],F[t+72>>2]=ee[0],F[t+76>>2]=ee[1],$[t+80>>2]=a%1e3*1e3,ee=[Math.floor(i/1e3)>>>0,(Q=Math.floor(i/1e3),+Math.abs(Q)>=1?Q>0?(0|Math.min(+Math.floor(Q/4294967296),4294967295))>>>0:~~+Math.ceil((Q-+(~~Q>>>0))/4294967296)>>>0:0)],F[t+88>>2]=ee[0],F[t+92>>2]=ee[1],$[t+96>>2]=i%1e3*1e3,ee=[n.ino>>>0,(Q=n.ino,+Math.abs(Q)>=1?Q>0?(0|Math.min(+Math.floor(Q/4294967296),4294967295))>>>0:~~+Math.ceil((Q-+(~~Q>>>0))/4294967296)>>>0:0)],F[t+104>>2]=ee[0],F[t+108>>2]=ee[1],0},doMsync:function(e,r,t,n,o){if(!pe.isFile(r.node.mode))throw new pe.ErrnoError(43);if(2&n)return 0;var a=S.slice(e,e+t);pe.msync(r,a,o,t,n)},varargs:void 0,get:function(){return ge.varargs+=4,F[ge.varargs-4>>2]},getStr:function(e){return N(e)},getStreamFromFD:function(e){var r=pe.getStream(e);if(!r)throw new pe.ErrnoError(8);return r}};function Ee(e,r){return r+2097152>>>0<4194305-!!e?(e>>>0)+4294967296*r:NaN}var be={};function _e(e){for(;e.length;){var r=e.pop();e.pop()(r)}}function ke(e){return this.fromWireType(F[e>>2])}var Te={},Pe={},Ce={},Se=48,De=57;function Ae(e){if(void 0===e)return"_unknown";var r=(e=e.replace(/[^a-zA-Z0-9_]/g,"$")).charCodeAt(0);return r>=Se&&r<=De?"_"+e:e}function Fe(e,r){return e=Ae(e),new Function("body","return function "+e+'() {\n "use strict"; return body.apply(this, arguments);\n};\n')(r)}function $e(e,r){var t=Fe(r,function(e){this.name=r,this.message=e;var t=new Error(e).stack;void 0!==t&&(this.stack=this.toString()+"\n"+t.replace(/^Error(:[^\n]*)?\n/,""))});return t.prototype=Object.create(e.prototype),t.prototype.constructor=t,t.prototype.toString=function(){return void 0===this.message?this.name:this.name+": "+this.message},t}var Me=void 0;function Oe(e){throw new Me(e)}function je(e,r,t){function n(r){var n=t(r);n.length!==e.length&&Oe("Mismatched type converter count");for(var o=0;o{Pe.hasOwnProperty(e)?o[r]=Pe[e]:(a.push(e),Te.hasOwnProperty(e)||(Te[e]=[]),Te[e].push(()=>{o[r]=Pe[e],++i===a.length&&n(o)}))}),0===a.length&&n(o)}var xe={};function Ne(e){switch(e){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError("Unknown type size: "+e)}}var Re=void 0;function ze(e){for(var r="",t=e;S[t];)r+=Re[S[t++]];return r}var We=void 0;function Be(e){throw new We(e)}function Ue(e,r,t={}){if(!("argPackAdvance"in r))throw new TypeError("registerType registeredInstance requires argPackAdvance");var n=r.name;if(e||Be('type "'+n+'" must have a positive integer typeid pointer'),Pe.hasOwnProperty(e)){if(t.ignoreDuplicateRegistrations)return;Be("Cannot register type '"+n+"' twice")}if(Pe[e]=r,delete Ce[e],Te.hasOwnProperty(e)){var o=Te[e];delete Te[e],o.forEach(e=>e())}}function Le(e){if(!(this instanceof cr))return!1;if(!(e instanceof cr))return!1;for(var r=this.$$.ptrType.registeredClass,t=this.$$.ptr,n=e.$$.ptrType.registeredClass,o=e.$$.ptr;r.baseClass;)t=r.upcast(t),r=r.baseClass;for(;n.baseClass;)o=n.upcast(o),n=n.baseClass;return r===n&&t===o}function Ie(e){Be(e.$$.ptrType.registeredClass.name+" instance already deleted")}var He=!1;function Ve(e){}function qe(e){e.count.value-=1,0===e.count.value&&function(e){e.smartPtr?e.smartPtrType.rawDestructor(e.smartPtr):e.ptrType.registeredClass.rawDestructor(e.ptr)}(e)}var Ge={};function Xe(){return Object.keys(er).length}function Ye(){var e=[];for(var r in er)er.hasOwnProperty(r)&&e.push(er[r]);return e}var Ke=[];function Ze(){for(;Ke.length;){var e=Ke.pop();e.$$.deleteScheduled=!1,e.delete()}}var Je=void 0;function Qe(e){Je=e,Ke.length&&Je&&Je(Ze)}var er={};function rr(e,r){return r=function(e,r){for(void 0===r&&Be("ptr should not be undefined");e.baseClass;)r=e.upcast(r),e=e.baseClass;return r}(e,r),er[r]}function tr(e,r){return r.ptrType&&r.ptr||Oe("makeClassHandle requires ptr and ptrType"),!!r.smartPtrType!==!!r.smartPtr&&Oe("Both smartPtrType and smartPtr must be specified"),r.count={value:1},or(Object.create(e,{$$:{value:r}}))}function nr(e){var r=this.getPointee(e);if(!r)return this.destructor(e),null;var t=rr(this.registeredClass,r);if(void 0!==t){if(0===t.$$.count.value)return t.$$.ptr=r,t.$$.smartPtr=e,t.clone();var n=t.clone();return this.destructor(e),n}function o(){return this.isSmartPointer?tr(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:r,smartPtrType:this,smartPtr:e}):tr(this.registeredClass.instancePrototype,{ptrType:this,ptr:e})}var a,i=this.registeredClass.getActualType(r),s=Ge[i];if(!s)return o.call(this);a=this.isConst?s.constPointerType:s.pointerType;var u=function e(r,t,n){if(t===n)return r;if(void 0===n.baseClass)return null;var o=e(r,t,n.baseClass);return null===o?null:n.downcast(o)}(r,this.registeredClass,a.registeredClass);return null===u?o.call(this):this.isSmartPointer?tr(a.registeredClass.instancePrototype,{ptrType:a,ptr:u,smartPtrType:this,smartPtr:e}):tr(a.registeredClass.instancePrototype,{ptrType:a,ptr:u})}function or(e){return"undefined"==typeof FinalizationRegistry?(or=(e=>e),e):(He=new FinalizationRegistry(e=>{qe(e.$$)}),Ve=(e=>He.unregister(e)),(or=(e=>{var r=e.$$;if(!!r.smartPtr){var t={$$:r};He.register(e,t,e)}return e}))(e))}function ar(){if(this.$$.ptr||Ie(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var e,r=or(Object.create(Object.getPrototypeOf(this),{$$:{value:(e=this.$$,{count:e.count,deleteScheduled:e.deleteScheduled,preservePointerOnDelete:e.preservePointerOnDelete,ptr:e.ptr,ptrType:e.ptrType,smartPtr:e.smartPtr,smartPtrType:e.smartPtrType})}}));return r.$$.count.value+=1,r.$$.deleteScheduled=!1,r}function ir(){this.$$.ptr||Ie(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&Be("Object already scheduled for deletion"),Ve(this),qe(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)}function sr(){return!this.$$.ptr}function ur(){return this.$$.ptr||Ie(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&Be("Object already scheduled for deletion"),Ke.push(this),1===Ke.length&&Je&&Je(Ze),this.$$.deleteScheduled=!0,this}function cr(){}function lr(e,r,t){if(void 0===e[r].overloadTable){var n=e[r];e[r]=function(){return e[r].overloadTable.hasOwnProperty(arguments.length)||Be("Function '"+t+"' called with an invalid number of arguments ("+arguments.length+") - expects one of ("+e[r].overloadTable+")!"),e[r].overloadTable[arguments.length].apply(this,arguments)},e[r].overloadTable=[],e[r].overloadTable[n.argCount]=n}}function fr(e,r,t){a.hasOwnProperty(e)?((void 0===t||void 0!==a[e].overloadTable&&void 0!==a[e].overloadTable[t])&&Be("Cannot register public name '"+e+"' twice"),lr(a,e,e),a.hasOwnProperty(t)&&Be("Cannot register multiple overloads of a function with the same number of arguments ("+t+")!"),a[e].overloadTable[t]=r):(a[e]=r,void 0!==t&&(a[e].numArguments=t))}function dr(e,r,t){for(;r!==t;)r.upcast||Be("Expected null or instance of "+t.name+", got an instance of "+r.name),e=r.upcast(e),r=r.baseClass;return e}function pr(e,r){if(null===r)return this.isReference&&Be("null is not a valid "+this.name),0;r.$$||Be('Cannot pass "'+Rr(r)+'" as a '+this.name),r.$$.ptr||Be("Cannot pass deleted object as a pointer of type "+this.name);var t=r.$$.ptrType.registeredClass;return dr(r.$$.ptr,t,this.registeredClass)}function hr(e,r){var t;if(null===r)return this.isReference&&Be("null is not a valid "+this.name),this.isSmartPointer?(t=this.rawConstructor(),null!==e&&e.push(this.rawDestructor,t),t):0;r.$$||Be('Cannot pass "'+Rr(r)+'" as a '+this.name),r.$$.ptr||Be("Cannot pass deleted object as a pointer of type "+this.name),!this.isConst&&r.$$.ptrType.isConst&&Be("Cannot convert argument of type "+(r.$$.smartPtrType?r.$$.smartPtrType.name:r.$$.ptrType.name)+" to parameter type "+this.name);var n=r.$$.ptrType.registeredClass;if(t=dr(r.$$.ptr,n,this.registeredClass),this.isSmartPointer)switch(void 0===r.$$.smartPtr&&Be("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:r.$$.smartPtrType===this?t=r.$$.smartPtr:Be("Cannot convert argument of type "+(r.$$.smartPtrType?r.$$.smartPtrType.name:r.$$.ptrType.name)+" to parameter type "+this.name);break;case 1:t=r.$$.smartPtr;break;case 2:if(r.$$.smartPtrType===this)t=r.$$.smartPtr;else{var o=r.clone();t=this.rawShare(t,xr.toHandle(function(){o.delete()})),null!==e&&e.push(this.rawDestructor,t)}break;default:Be("Unsupporting sharing policy")}return t}function mr(e,r){if(null===r)return this.isReference&&Be("null is not a valid "+this.name),0;r.$$||Be('Cannot pass "'+Rr(r)+'" as a '+this.name),r.$$.ptr||Be("Cannot pass deleted object as a pointer of type "+this.name),r.$$.ptrType.isConst&&Be("Cannot convert argument of type "+r.$$.ptrType.name+" to parameter type "+this.name);var t=r.$$.ptrType.registeredClass;return dr(r.$$.ptr,t,this.registeredClass)}function vr(e){return this.rawGetPointee&&(e=this.rawGetPointee(e)),e}function wr(e){this.rawDestructor&&this.rawDestructor(e)}function yr(e){null!==e&&e.delete()}function gr(e,r,t,n,o,a,i,s,u,c,l){this.name=e,this.registeredClass=r,this.isReference=t,this.isConst=n,this.isSmartPointer=o,this.pointeeType=a,this.sharingPolicy=i,this.rawGetPointee=s,this.rawConstructor=u,this.rawShare=c,this.rawDestructor=l,o||void 0!==r.baseClass?this.toWireType=hr:n?(this.toWireType=pr,this.destructorFunction=null):(this.toWireType=mr,this.destructorFunction=null)}function Er(e){return B.get(e)}function br(e,r,t){return e.includes("j")?function(e,r,t){var n=a["dynCall_"+e];return t&&t.length?n.apply(null,[r].concat(t)):n.call(null,r)}(e,r,t):Er(r).apply(null,t)}function _r(e,r){var t,n,o,a=(e=ze(e)).includes("j")?(t=e,n=r,o=[],function(){return o.length=0,Object.assign(o,arguments),br(t,n,o)}):Er(r);return"function"!=typeof a&&Be("unknown function pointer with signature "+e+": "+r),a}var kr=void 0;function Tr(e){var r=dt(e),t=ze(r);return lt(r),t}function Pr(e,r){var t=[],n={};throw r.forEach(function e(r){n[r]||Pe[r]||(Ce[r]?Ce[r].forEach(e):(t.push(r),n[r]=!0))}),new kr(e+": "+t.map(Tr).join([", "]))}function Cr(e,r){if(!(e instanceof Function))throw new TypeError("new_ called with constructor type "+typeof e+" which is not a function");var t=Fe(e.name||"unknownFunctionName",function(){});t.prototype=e.prototype;var n=new t,o=e.apply(n,r);return o instanceof Object?o:n}function Sr(e,r,t,n,o){var a=r.length;a<2&&Be("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var i=null!==r[1]&&null!==t,s=!1,u=1;u0?", ":"")+f),d+=(c?"var rv = ":"")+"invoker(fn"+(f.length>0?", ":"")+f+");\n",s)d+="runDestructors(destructors);\n";else for(u=i?1:2;u>2]);return t}function Ar(e,r,t){return e instanceof Object||Be(t+' with invalid "this": '+e),e instanceof r.registeredClass.constructor||Be(t+' incompatible with "this" of type '+e.constructor.name),e.$$.ptr||Be("cannot call emscripten binding method "+t+" on deleted object"),dr(e.$$.ptr,e.$$.ptrType.registeredClass,r.registeredClass)}var Fr=[],$r=[{},{value:void 0},{value:null},{value:!0},{value:!1}];function Mr(e){e>4&&0==--$r[e].refcount&&($r[e]=void 0,Fr.push(e))}function Or(){for(var e=0,r=5;r<$r.length;++r)void 0!==$r[r]&&++e;return e}function jr(){for(var e=5;e<$r.length;++e)if(void 0!==$r[e])return $r[e];return null}var xr={toValue:e=>(e||Be("Cannot use deleted val. handle = "+e),$r[e].value),toHandle:e=>{switch(e){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:var r=Fr.length?Fr.pop():$r.length;return $r[r]={refcount:1,value:e},r}}};function Nr(e,r){var t=Pe[e];return void 0===t&&Be(r+" has unknown type "+Tr(e)),t}function Rr(e){if(null===e)return"null";var r=typeof e;return"object"===r||"array"===r||"function"===r?e.toString():""+e}var zr="undefined"!=typeof TextDecoder?new TextDecoder("utf-16le"):void 0;function Wr(e,r){for(var t=e,n=t>>1,o=n+r/2;!(n>=o)&&A[n];)++n;if((t=n<<1)-e>32&&zr)return zr.decode(S.subarray(e,t));for(var a="",i=0;!(i>=r/2);++i){var s=D[e+2*i>>1];if(0==s)break;a+=String.fromCharCode(s)}return a}function Br(e,r,t){if(void 0===t&&(t=2147483647),t<2)return 0;for(var n=r,o=(t-=2)<2*e.length?t/2:e.length,a=0;a>1]=i,r+=2}return D[r>>1]=0,r-n}function Ur(e){return 2*e.length}function Lr(e,r){for(var t=0,n="";!(t>=r/4);){var o=F[e+4*t>>2];if(0==o)break;if(++t,o>=65536){var a=o-65536;n+=String.fromCharCode(55296|a>>10,56320|1023&a)}else n+=String.fromCharCode(o)}return n}function Ir(e,r,t){if(void 0===t&&(t=2147483647),t<4)return 0;for(var n=r,o=n+t-4,a=0;a=55296&&i<=57343)i=65536+((1023&i)<<10)|1023&e.charCodeAt(++a);if(F[r>>2]=i,(r+=4)+4>o)break}return F[r>>2]=0,r-n}function Hr(e){for(var r=0,t=0;t=55296&&n<=57343&&++t,r+=4}return r}var Vr={};function qr(e){var r=Vr[e];return void 0===r?ze(e):r}var Gr=[];function Xr(){return"object"==typeof globalThis?globalThis:Function("return this")()}var Yr=[];var Kr={};function Zr(e){return $[e>>2]+4294967296*F[e+4>>2]}var Jr,Qr=[0,31,60,91,121,152,182,213,244,274,305,335],et=[0,31,59,90,120,151,181,212,243,273,304,334];function rt(e){var r;return((r=e.getFullYear())%4==0&&(r%100!=0||r%400==0)?Qr:et)[e.getMonth()]+e.getDate()-1}function tt(e){var r=z(e)+1,t=ct(r);return t&&R(e,C,t,r),t}function nt(e){var r=_.buffer;try{return _.grow(e-r.byteLength+65535>>>16),W(),1}catch(e){}}Jr=h?()=>{var e=process.hrtime();return 1e3*e[0]+e[1]/1e6}:()=>performance.now();var ot={};function at(){if(!at.strings){var e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:f||"./this.program"};for(var r in ot)void 0===ot[r]?delete e[r]:e[r]=ot[r];var t=[];for(var r in e)t.push(r+"="+e[r]);at.strings=t}return at.strings}var it=function(e,r,t,n){e||(e=this),this.parent=e,this.mount=e.mount,this.mounted=null,this.id=pe.nextInode++,this.name=r,this.mode=t,this.node_ops={},this.stream_ops={},this.rdev=n};Object.defineProperties(it.prototype,{read:{get:function(){return 365==(365&this.mode)},set:function(e){e?this.mode|=365:this.mode&=-366}},write:{get:function(){return 146==(146&this.mode)},set:function(e){e?this.mode|=146:this.mode&=-147}},isFolder:{get:function(){return pe.isDir(this.mode)}},isDevice:{get:function(){return pe.isChrdev(this.mode)}}}),pe.FSNode=it,pe.staticInit(),Me=a.InternalError=$e(Error,"InternalError"),function(){for(var e=new Array(256),r=0;r<256;++r)e[r]=String.fromCharCode(r);Re=e}(),We=a.BindingError=$e(Error,"BindingError"),cr.prototype.isAliasOf=Le,cr.prototype.clone=ar,cr.prototype.delete=ir,cr.prototype.isDeleted=sr,cr.prototype.deleteLater=ur,a.getInheritedInstanceCount=Xe,a.getLiveInheritedInstances=Ye,a.flushPendingDeletes=Ze,a.setDelayFunction=Qe,gr.prototype.getPointee=vr,gr.prototype.destructor=wr,gr.prototype.argPackAdvance=8,gr.prototype.readValueFromPointer=ke,gr.prototype.deleteObject=yr,gr.prototype.fromWireType=nr,kr=a.UnboundTypeError=$e(Error,"UnboundTypeError"),a.count_emval_handles=Or,a.get_first_emval=jr;var st,ut={v:function(e,r,t){throw new function(e){this.excPtr=e,this.ptr=e-24,this.set_type=function(e){$[this.ptr+4>>2]=e},this.get_type=function(){return $[this.ptr+4>>2]},this.set_destructor=function(e){$[this.ptr+8>>2]=e},this.get_destructor=function(){return $[this.ptr+8>>2]},this.set_refcount=function(e){F[this.ptr>>2]=e},this.set_caught=function(e){e=e?1:0,C[this.ptr+12>>0]=e},this.get_caught=function(){return 0!=C[this.ptr+12>>0]},this.set_rethrown=function(e){e=e?1:0,C[this.ptr+13>>0]=e},this.get_rethrown=function(){return 0!=C[this.ptr+13>>0]},this.init=function(e,r){this.set_adjusted_ptr(0),this.set_type(e),this.set_destructor(r),this.set_refcount(0),this.set_caught(!1),this.set_rethrown(!1)},this.add_ref=function(){var e=F[this.ptr>>2];F[this.ptr>>2]=e+1},this.release_ref=function(){var e=F[this.ptr>>2];return F[this.ptr>>2]=e-1,1===e},this.set_adjusted_ptr=function(e){$[this.ptr+16>>2]=e},this.get_adjusted_ptr=function(){return $[this.ptr+16>>2]},this.get_exception_ptr=function(){if(mt(this.get_type()))return $[this.excPtr>>2];var e=this.get_adjusted_ptr();return 0!==e?e:this.excPtr}}(e).init(r,t),e,0,e},U:function(e,r,t){try{var n=function(e){var r=he.getSocket(e);if(!r)throw new pe.ErrnoError(8);return r}(e),o=function(e,r,t){if(t&&0===e)return null;var n=ve(e,r);if(n.errno)throw new pe.ErrnoError(n.errno);return n.addr=ye.lookup_addr(n.addr)||n.addr,n}(r,t);return n.sock_ops.connect(n,o.addr,o.port),0}catch(e){if(void 0===pe||!(e instanceof pe.ErrnoError))throw e;return-e.errno}},ea:function(e,r,t,n){try{if(r=ge.getStr(r),r=ge.calculateAt(e,r),-8&t)return-28;var o=pe.lookupPath(r,{follow:!0}).node;if(!o)return-44;var a="";return 4&t&&(a+="r"),2&t&&(a+="w"),1&t&&(a+="x"),a&&pe.nodePermissions(o,a)?-2:0}catch(e){if(void 0===pe||!(e instanceof pe.ErrnoError))throw e;return-e.errno}},o:function(e,r,t){ge.varargs=t;try{var n=ge.getStreamFromFD(e);switch(r){case 0:return(o=ge.get())<0?-28:pe.createStream(n,o).fd;case 1:case 2:return 0;case 3:return n.flags;case 4:var o=ge.get();return n.flags|=o,0;case 5:return o=ge.get(),D[o+0>>1]=2,0;case 6:case 7:return 0;case 16:case 8:return-28;case 9:return a=28,F[ft()>>2]=a,-1;default:return-28}}catch(e){if(void 0===pe||!(e instanceof pe.ErrnoError))throw e;return-e.errno}var a},Z:function(e,r){try{var t=ge.getStreamFromFD(e);return ge.doStat(pe.stat,t.path,r)}catch(e){if(void 0===pe||!(e instanceof pe.ErrnoError))throw e;return-e.errno}},S:function(e,r,t){try{var n=Ee(r,t);return isNaN(n)?-61:(pe.ftruncate(e,n),0)}catch(e){if(void 0===pe||!(e instanceof pe.ErrnoError))throw e;return-e.errno}},K:function(e,r,t){ge.varargs=t;try{var n=ge.getStreamFromFD(e);switch(r){case 21509:case 21505:return n.tty?0:-59;case 21510:case 21511:case 21512:case 21506:case 21507:case 21508:return n.tty?0:-59;case 21519:if(!n.tty)return-59;var o=ge.get();return F[o>>2]=0,0;case 21520:return n.tty?-28:-59;case 21531:return o=ge.get(),pe.ioctl(n,r,o);case 21523:case 21524:return n.tty?0:-59;default:return-28}}catch(e){if(void 0===pe||!(e instanceof pe.ErrnoError))throw e;return-e.errno}},W:function(e,r){try{return e=ge.getStr(e),ge.doStat(pe.lstat,e,r)}catch(e){if(void 0===pe||!(e instanceof pe.ErrnoError))throw e;return-e.errno}},X:function(e,r,t,n){try{r=ge.getStr(r);var o=256&n,a=4096&n;return n&=-6401,r=ge.calculateAt(e,r,a),ge.doStat(o?pe.lstat:pe.stat,r,t)}catch(e){if(void 0===pe||!(e instanceof pe.ErrnoError))throw e;return-e.errno}},G:function(e,r,t,n){ge.varargs=n;try{r=ge.getStr(r),r=ge.calculateAt(e,r);var o=n?ge.get():0;return pe.open(r,t,o).fd}catch(e){if(void 0===pe||!(e instanceof pe.ErrnoError))throw e;return-e.errno}},F:function(e,r,t){try{return he.createSocket(e,r,t).stream.fd}catch(e){if(void 0===pe||!(e instanceof pe.ErrnoError))throw e;return-e.errno}},Y:function(e,r){try{return e=ge.getStr(e),ge.doStat(pe.stat,e,r)}catch(e){if(void 0===pe||!(e instanceof pe.ErrnoError))throw e;return-e.errno}},r:function(e){var r=be[e];delete be[e];var t=r.elements,n=t.length,o=t.map(function(e){return e.getterReturnType}).concat(t.map(function(e){return e.setterArgumentType})),a=r.rawConstructor,i=r.rawDestructor;je([e],o,function(e){return t.forEach((r,t)=>{var o=e[t],a=r.getter,i=r.getterContext,s=e[t+n],u=r.setter,c=r.setterContext;r.read=(e=>o.fromWireType(a(i,e))),r.write=((e,r)=>{var t=[];u(c,e,s.toWireType(t,r)),_e(t)})}),[{name:r.name,fromWireType:function(e){for(var r=new Array(n),o=0;o>a])},destructorFunction:null})},e:function(e,r,t,n,o,i,s,u,c,l,f,d,p){f=ze(f),i=_r(o,i),u&&(u=_r(s,u)),l&&(l=_r(c,l)),p=_r(d,p);var h=Ae(f);fr(h,function(){Pr("Cannot construct "+f+" due to unbound types",[n])}),je([e,r,t],n?[n]:[],function(r){var t,o;r=r[0],o=n?(t=r.registeredClass).instancePrototype:cr.prototype;var s=Fe(h,function(){if(Object.getPrototypeOf(this)!==c)throw new We("Use 'new' to construct "+f);if(void 0===d.constructor_body)throw new We(f+" has no accessible constructor");var e=d.constructor_body[arguments.length];if(void 0===e)throw new We("Tried to invoke ctor of "+f+" with invalid number of parameters ("+arguments.length+") - expected ("+Object.keys(d.constructor_body).toString()+") parameters instead!");return e.apply(this,arguments)}),c=Object.create(o,{constructor:{value:s}});s.prototype=c;var d=new function(e,r,t,n,o,a,i,s){this.name=e,this.constructor=r,this.instancePrototype=t,this.rawDestructor=n,this.baseClass=o,this.getActualType=a,this.upcast=i,this.downcast=s,this.pureVirtualFunctions=[]}(f,s,c,p,t,i,u,l),m=new gr(f,d,!0,!1,!1),v=new gr(f+"*",d,!1,!1,!1),w=new gr(f+" const*",d,!1,!0,!1);return Ge[e]={pointerType:v,constPointerType:w},function(e,r,t){a.hasOwnProperty(e)||Oe("Replacing nonexistant public symbol"),void 0!==a[e].overloadTable&&void 0!==t?a[e].overloadTable[t]=r:(a[e]=r,a[e].argCount=t)}(h,s),[m,v,w]})},f:function(e,r,t,n,o,a,i){var s=Dr(t,n);r=ze(r),a=_r(o,a),je([],[e],function(e){var n=(e=e[0]).name+"."+r;function o(){Pr("Cannot call "+n+" due to unbound types",s)}r.startsWith("@@")&&(r=Symbol[r.substring(2)]);var u=e.registeredClass.constructor;return void 0===u[r]?(o.argCount=t-1,u[r]=o):(lr(u,r,n),u[r].overloadTable[t-1]=o),je([],s,function(e){var o=[e[0],null].concat(e.slice(1)),s=Sr(n,o,null,a,i);return void 0===u[r].overloadTable?(s.argCount=t-1,u[r]=s):u[r].overloadTable[t-1]=s,[]}),[]})},g:function(e,r,t,n,o,a){P(r>0);var i=Dr(r,t);o=_r(n,o),je([],[e],function(e){var t="constructor "+(e=e[0]).name;if(void 0===e.registeredClass.constructor_body&&(e.registeredClass.constructor_body=[]),void 0!==e.registeredClass.constructor_body[r-1])throw new We("Cannot register multiple constructors with identical number of parameters ("+(r-1)+") for class '"+e.name+"'! Overload resolution is currently only performed using the parameter count, not actual type info!");return e.registeredClass.constructor_body[r-1]=(()=>{Pr("Cannot construct "+e.name+" due to unbound types",i)}),je([],i,function(n){return n.splice(1,0,null),e.registeredClass.constructor_body[r-1]=Sr(t,n,null,o,a),[]}),[]})},b:function(e,r,t,n,o,a,i,s){var u=Dr(t,n);r=ze(r),a=_r(o,a),je([],[e],function(e){var n=(e=e[0]).name+"."+r;function o(){Pr("Cannot call "+n+" due to unbound types",u)}r.startsWith("@@")&&(r=Symbol[r.substring(2)]),s&&e.registeredClass.pureVirtualFunctions.push(r);var c=e.registeredClass.instancePrototype,l=c[r];return void 0===l||void 0===l.overloadTable&&l.className!==e.name&&l.argCount===t-2?(o.argCount=t-2,o.className=e.name,c[r]=o):(lr(c,r,n),c[r].overloadTable[t-2]=o),je([],u,function(o){var s=Sr(n,o,e,a,i);return void 0===c[r].overloadTable?(s.argCount=t-2,c[r]=s):c[r].overloadTable[t-2]=s,[]}),[]})},a:function(e,r,t,n,o,a,i,s,u,c){r=ze(r),o=_r(n,o),je([],[e],function(e){var n=(e=e[0]).name+"."+r,l={get:function(){Pr("Cannot access "+n+" due to unbound types",[t,i])},enumerable:!0,configurable:!0};return l.set=u?()=>{Pr("Cannot access "+n+" due to unbound types",[t,i])}:e=>{Be(n+" is a read-only property")},Object.defineProperty(e.registeredClass.instancePrototype,r,l),je([],u?[t,i]:[t],function(t){var i=t[0],l={get:function(){var r=Ar(this,e,n+" getter");return i.fromWireType(o(a,r))},enumerable:!0};if(u){u=_r(s,u);var f=t[1];l.set=function(r){var t=Ar(this,e,n+" setter"),o=[];u(c,t,f.toWireType(o,r)),_e(o)}}return Object.defineProperty(e.registeredClass.instancePrototype,r,l),[]}),[]})},fa:function(e,r){Ue(e,{name:r=ze(r),fromWireType:function(e){var r=xr.toValue(e);return Mr(e),r},toWireType:function(e,r){return xr.toHandle(r)},argPackAdvance:8,readValueFromPointer:ke,destructorFunction:null})},i:function(e,r,t,n){var o=Ne(t);function a(){}r=ze(r),a.values={},Ue(e,{name:r,constructor:a,fromWireType:function(e){return this.constructor.values[e]},toWireType:function(e,r){return r.value},argPackAdvance:8,readValueFromPointer:function(e,r,t){switch(r){case 0:return function(e){var r=t?C:S;return this.fromWireType(r[e])};case 1:return function(e){var r=t?D:A;return this.fromWireType(r[e>>1])};case 2:return function(e){var r=t?F:$;return this.fromWireType(r[e>>2])};default:throw new TypeError("Unknown integer type: "+e)}}(r,o,n),destructorFunction:null}),fr(r,a)},d:function(e,r,t){var n=Nr(e,"enum");r=ze(r);var o=n.constructor,a=Object.create(n.constructor.prototype,{value:{value:t},constructor:{value:Fe(n.name+"_"+r,function(){})}});o.values[t]=a,o[r]=a},M:function(e,r,t){var n=Ne(t);Ue(e,{name:r=ze(r),fromWireType:function(e){return e},toWireType:function(e,r){return r},argPackAdvance:8,readValueFromPointer:function(e,r){switch(r){case 2:return function(e){return this.fromWireType(M[e>>2])};case 3:return function(e){return this.fromWireType(O[e>>3])};default:throw new TypeError("Unknown float type: "+e)}}(r,n),destructorFunction:null})},p:function(e,r,t,n,o){r=ze(r),-1===o&&(o=4294967295);var a=Ne(t),i=e=>e;if(0===n){var s=32-8*t;i=(e=>e<>>s)}var u=r.includes("unsigned");Ue(e,{name:r,fromWireType:i,toWireType:u?function(e,r){return this.name,r>>>0}:function(e,r){return this.name,r},argPackAdvance:8,readValueFromPointer:function(e,r,t){switch(r){case 0:return t?function(e){return C[e]}:function(e){return S[e]};case 1:return t?function(e){return D[e>>1]}:function(e){return A[e>>1]};case 2:return t?function(e){return F[e>>2]}:function(e){return $[e>>2]};default:throw new TypeError("Unknown integer type: "+e)}}(r,a,0!==n),destructorFunction:null})},l:function(e,r,t){var n=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][r];function o(e){var r=$,t=r[e>>=2],o=r[e+1];return new n(r.buffer,o,t)}Ue(e,{name:t=ze(t),fromWireType:o,argPackAdvance:8,readValueFromPointer:o},{ignoreDuplicateRegistrations:!0})},L:function(e,r){var t="std::string"===(r=ze(r));Ue(e,{name:r,fromWireType:function(e){var r,n=$[e>>2],o=e+4;if(t)for(var a=o,i=0;i<=n;++i){var s=o+i;if(i==n||0==S[s]){var u=N(a,s-a);void 0===r?r=u:(r+=String.fromCharCode(0),r+=u),a=s+1}}else{var c=new Array(n);for(i=0;i>2]=n,t&&o)R(r,S,i,n+1);else if(o)for(var s=0;s255&&(lt(i),Be("String has UTF-16 code units that do not fit in 8 bits")),S[i+s]=u}else for(s=0;sA),s=1):4===r&&(n=Lr,o=Ir,i=Hr,a=(()=>$),s=2),Ue(e,{name:t,fromWireType:function(e){for(var t,o=$[e>>2],i=a(),u=e+4,c=0;c<=o;++c){var l=e+4+c*r;if(c==o||0==i[l>>s]){var f=n(u,l-u);void 0===t?t=f:(t+=String.fromCharCode(0),t+=f),u=l+r}}return lt(e),t},toWireType:function(e,n){"string"!=typeof n&&Be("Cannot pass non-string to C++ string type "+t);var a=i(n),u=ct(4+a+r);return $[u>>2]=a>>s,o(n,u+4,a+r),null!==e&&e.push(lt,u),u},argPackAdvance:8,readValueFromPointer:ke,destructorFunction:function(e){lt(e)}})},q:function(e,r,t,n,o,a){be[e]={name:ze(r),rawConstructor:_r(t,n),rawDestructor:_r(o,a),elements:[]}},ia:function(e,r,t,n,o,a,i,s,u){be[e].elements.push({getterReturnType:r,getter:_r(t,n),getterContext:o,setterArgumentType:a,setter:_r(i,s),setterContext:u})},ja:function(e,r,t,n,o,a){xe[e]={name:ze(r),rawConstructor:_r(t,n),rawDestructor:_r(o,a),fields:[]}},N:function(e,r,t,n,o,a,i,s,u,c){xe[e].fields.push({fieldName:ze(r),getterReturnType:t,getter:_r(n,o),getterContext:a,setterArgumentType:i,setter:_r(s,u),setterContext:c})},ha:function(e,r){Ue(e,{isVoid:!0,name:r=ze(r),argPackAdvance:0,fromWireType:function(){},toWireType:function(e,r){}})},t:function(e,r,t){e=xr.toValue(e),r=Nr(r,"emval::as");var n=[],o=xr.toHandle(n);return $[t>>2]=o,r.toWireType(n,e)},la:function(e,r,t,n,o){return(e=Gr[e])(r=xr.toValue(r),t=qr(t),function(e){var r=[];return $[e>>2]=xr.toHandle(r),r}(n),o)},P:function(e,r,t,n){(e=Gr[e])(r=xr.toValue(r),t=qr(t),null,n)},c:Mr,Q:function(e,r){return(e=xr.toValue(e))==(r=xr.toValue(r))},y:function(e){return 0===e?xr.toHandle(Xr()):(e=qr(e),xr.toHandle(Xr()[e]))},C:function(e,r){var t=function(e,r){for(var t=new Array(e),n=0;n>2],"parameter "+n);return t}(e,r),n=t[0],o=n.name+"_$"+t.slice(1).map(function(e){return e.name}).join("_")+"$",a=Yr[o];if(void 0!==a)return a;for(var i=["retType"],s=[n],u="",c=0;c4&&($r[e].refcount+=1)},D:function(e,r){return(e=xr.toValue(e))instanceof(r=xr.toValue(r))},na:function(e){return"number"==typeof(e=xr.toValue(e))},ma:function(e){return"string"==typeof(e=xr.toValue(e))},O:function(e,r,t,n){e=xr.toValue(e);var o=Kr[r];return o||(o=function(e){for(var r="",t=0;t>2)], 'parameter "+t+"');\nvar arg"+t+" = argType"+t+".readValueFromPointer(args);\nargs += argType"+t+"['argPackAdvance'];\nargTypes += 4;\n";return n+="var obj = new constructor("+r+");\nreturn valueToHandle(obj);\n}\n",new Function("requireRegisteredType","Module","valueToHandle","getMemory",n)(Nr,a,xr.toHandle,()=>$)}(r),Kr[r]=o),o(e,t,n)},n:function(){return xr.toHandle([])},u:function(e){return xr.toHandle(qr(e))},k:function(){return xr.toHandle({})},s:function(e){_e(xr.toValue(e)),Mr(e)},j:function(e,r,t){e=xr.toValue(e),r=xr.toValue(r),t=xr.toValue(t),e[r]=t},h:function(e,r){var t=(e=Nr(e,"_emval_take_value")).readValueFromPointer(r);return xr.toHandle(t)},aa:function(e,r){var t=new Date(1e3*Zr(e));F[r>>2]=t.getUTCSeconds(),F[r+4>>2]=t.getUTCMinutes(),F[r+8>>2]=t.getUTCHours(),F[r+12>>2]=t.getUTCDate(),F[r+16>>2]=t.getUTCMonth(),F[r+20>>2]=t.getUTCFullYear()-1900,F[r+24>>2]=t.getUTCDay();var n=Date.UTC(t.getUTCFullYear(),0,1,0,0,0,0),o=(t.getTime()-n)/864e5|0;F[r+28>>2]=o},ba:function(e,r){var t=new Date(1e3*Zr(e));F[r>>2]=t.getSeconds(),F[r+4>>2]=t.getMinutes(),F[r+8>>2]=t.getHours(),F[r+12>>2]=t.getDate(),F[r+16>>2]=t.getMonth(),F[r+20>>2]=t.getFullYear()-1900,F[r+24>>2]=t.getDay();var n=0|rt(t);F[r+28>>2]=n,F[r+36>>2]=-60*t.getTimezoneOffset();var o=new Date(t.getFullYear(),0,1),a=new Date(t.getFullYear(),6,1).getTimezoneOffset(),i=o.getTimezoneOffset(),s=0|(a!=i&&t.getTimezoneOffset()==Math.min(i,a));F[r+32>>2]=s},ca:function(e){var r=new Date(F[e+20>>2]+1900,F[e+16>>2],F[e+12>>2],F[e+8>>2],F[e+4>>2],F[e>>2],0),t=F[e+32>>2],n=r.getTimezoneOffset(),o=new Date(r.getFullYear(),0,1),a=new Date(r.getFullYear(),6,1).getTimezoneOffset(),i=o.getTimezoneOffset(),s=Math.min(i,a);if(t<0)F[e+32>>2]=Number(a!=i&&s==n);else if(t>0!=(s==n)){var u=Math.max(i,a),c=t>0?s:u;r.setTime(r.getTime()+6e4*(c-n))}F[e+24>>2]=r.getDay();var l=0|rt(r);return F[e+28>>2]=l,F[e>>2]=r.getSeconds(),F[e+4>>2]=r.getMinutes(),F[e+8>>2]=r.getHours(),F[e+12>>2]=r.getDate(),F[e+16>>2]=r.getMonth(),F[e+20>>2]=r.getYear(),r.getTime()/1e3|0},da:function(e,r,t){var n=(new Date).getFullYear(),o=new Date(n,0,1),a=new Date(n,6,1),i=o.getTimezoneOffset(),s=a.getTimezoneOffset(),u=Math.max(i,s);function c(e){var r=e.toTimeString().match(/\(([A-Za-z ]+)\)$/);return r?r[1]:"GMT"}$[e>>2]=60*u,F[r>>2]=Number(i!=s);var l=c(o),f=c(a),d=tt(l),p=tt(f);s>2]=d,$[t+4>>2]=p):($[t>>2]=p,$[t+4>>2]=d)},z:function(){K("")},I:function(){return Date.now()},H:Jr,V:function(e){var r=S.length;if((e>>>=0)>2147483648)return!1;let t=(e,r)=>e+(r-e%r)%r;for(var n=1;n<=4;n*=2){var o=r*(1+.2/n);if(o=Math.min(o,e+100663296),nt(Math.min(2147483648,t(Math.max(e,o),65536))))return!0}return!1},_:function(e,r){var t=0;return at().forEach(function(n,o){var a=r+t;$[e+4*o>>2]=a,function(e,r,t){for(var n=0;n>0]=e.charCodeAt(n);t||(C[r>>0]=0)}(n,a),t+=n.length+1}),0},$:function(e,r){var t=at();$[e>>2]=t.length;var n=0;return t.forEach(function(e){n+=e.length+1}),$[r>>2]=n,0},x:function(e){try{var r=ge.getStreamFromFD(e);return pe.close(r),0}catch(e){if(void 0===pe||!(e instanceof pe.ErrnoError))throw e;return e.errno}},J:function(e,r,t,n){try{var o=function(e,r,t,n){for(var o=0,a=0;a>2],s=$[r+4>>2];r+=8;var u=pe.read(e,C,i,s,n);if(u<0)return-1;if(o+=u,u>2]=o,0}catch(e){if(void 0===pe||!(e instanceof pe.ErrnoError))throw e;return e.errno}},R:function(e,r,t,n,o){try{var a=Ee(r,t);if(isNaN(a))return 61;var i=ge.getStreamFromFD(e);return pe.llseek(i,a,n),ee=[i.position>>>0,(Q=i.position,+Math.abs(Q)>=1?Q>0?(0|Math.min(+Math.floor(Q/4294967296),4294967295))>>>0:~~+Math.ceil((Q-+(~~Q>>>0))/4294967296)>>>0:0)],F[o>>2]=ee[0],F[o+4>>2]=ee[1],i.getdents&&0===a&&0===n&&(i.getdents=null),0}catch(e){if(void 0===pe||!(e instanceof pe.ErrnoError))throw e;return e.errno}},A:function(e,r,t,n){try{var o=function(e,r,t,n){for(var o=0,a=0;a>2],s=$[r+4>>2];r+=8;var u=pe.write(e,C,i,s,n);if(u<0)return-1;o+=u,void 0!==n&&(n+=u)}return o}(ge.getStreamFromFD(e),r,t);return $[n>>2]=o,0}catch(e){if(void 0===pe||!(e instanceof pe.ErrnoError))throw e;return e.errno}}},ct=(function(){var e={a:ut};function r(e,r){var t,n=e.exports;a.asm=n,_=a.asm.oa,W(),B=a.asm.qa,t=a.asm.pa,L.unshift(t),Y()}function t(e){r(e.instance)}function o(r){return function(){if(!E&&(d||p)){if("function"==typeof fetch&&!ne(Z))return fetch(Z,{credentials:"same-origin"}).then(function(e){if(!e.ok)throw"failed to load wasm binary file at '"+Z+"'";return e.arrayBuffer()}).catch(function(){return oe(Z)});if(s)return new Promise(function(e,r){s(Z,function(r){e(new Uint8Array(r))},r)})}return Promise.resolve().then(function(){return oe(Z)})}().then(function(r){return WebAssembly.instantiate(r,e)}).then(function(e){return e}).then(r,function(e){g("failed to asynchronously prepare wasm: "+e),K(e)})}if(X(),a.instantiateWasm)try{return a.instantiateWasm(e,r)}catch(e){g("Module.instantiateWasm callback failed with error: "+e),n(e)}(E||"function"!=typeof WebAssembly.instantiateStreaming||te(Z)||ne(Z)||h||"function"!=typeof fetch?o(t):fetch(Z,{credentials:"same-origin"}).then(function(r){return WebAssembly.instantiateStreaming(r,e).then(t,function(e){return g("wasm streaming compile failed: "+e),g("falling back to ArrayBuffer instantiation"),o(t)})})).catch(n)}(),a.___wasm_call_ctors=function(){return(a.___wasm_call_ctors=a.asm.pa).apply(null,arguments)},a._malloc=function(){return(ct=a._malloc=a.asm.ra).apply(null,arguments)}),lt=a._free=function(){return(lt=a._free=a.asm.sa).apply(null,arguments)},ft=a.___errno_location=function(){return(ft=a.___errno_location=a.asm.ta).apply(null,arguments)},dt=a.___getTypeName=function(){return(dt=a.___getTypeName=a.asm.ua).apply(null,arguments)},pt=(a.__embind_initialize_bindings=function(){return(a.__embind_initialize_bindings=a.asm.va).apply(null,arguments)},a._htons=function(){return(pt=a._htons=a.asm.wa).apply(null,arguments)}),ht=a._ntohs=function(){return(ht=a._ntohs=a.asm.xa).apply(null,arguments)},mt=a.___cxa_is_pointer_type=function(){return(mt=a.___cxa_is_pointer_type=a.asm.ya).apply(null,arguments)};a.dynCall_ji=function(){return(a.dynCall_ji=a.asm.za).apply(null,arguments)},a.dynCall_vij=function(){return(a.dynCall_vij=a.asm.Aa).apply(null,arguments)},a.dynCall_jiji=function(){return(a.dynCall_jiji=a.asm.Ba).apply(null,arguments)};function vt(e){function r(){st||(st=!0,a.calledRun=!0,T||(!0,he.root=pe.mount(he,{},null),a.noFSInit||pe.init.initialized||pe.init(),pe.ignorePermissions=!1,le.init(),ie(L),t(a),a.onRuntimeInitialized&&a.onRuntimeInitialized(),function(){if(a.postRun)for("function"==typeof a.postRun&&(a.postRun=[a.postRun]);a.postRun.length;)e=a.postRun.shift(),I.unshift(e);var e;ie(I)}()))}e=e||l,H>0||(!function(){if(a.preRun)for("function"==typeof a.preRun&&(a.preRun=[a.preRun]);a.preRun.length;)e=a.preRun.shift(),U.unshift(e);var e;ie(U)}(),H>0||(a.setStatus?(a.setStatus("Running..."),setTimeout(function(){setTimeout(function(){a.setStatus("")},1),r()},1)):r()))}if(q=function e(){st||vt(),st||(q=e)},a.preInit)for("function"==typeof a.preInit&&(a.preInit=[a.preInit]);a.preInit.length>0;)a.preInit.pop()();return vt(),o.ready}})();"object"==typeof exports&&"object"==typeof module?module.exports=rhino3dm:"function"==typeof define&&define.amd?define([],function(){return rhino3dm}):"object"==typeof exports&&(exports.rhino3dm=rhino3dm); \ No newline at end of file diff --git a/public/assets/lib/vendor/three/rhino3dm/rhino3dm.module.js b/public/assets/lib/vendor/three/rhino3dm/rhino3dm.module.js deleted file mode 100644 index 14ec1330..00000000 --- a/public/assets/lib/vendor/three/rhino3dm/rhino3dm.module.js +++ /dev/null @@ -1,16 +0,0 @@ - -var rhino3dm = (() => { - var _scriptDir = import.meta.url; - - return ( -async function(config) { - var rhino3dm = config || {}; - -var Module=typeof rhino3dm!="undefined"?rhino3dm:{};var readyPromiseResolve,readyPromiseReject;Module["ready"]=new Promise(function(resolve,reject){readyPromiseResolve=resolve;readyPromiseReject=reject});var moduleOverrides=Object.assign({},Module);var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var ENVIRONMENT_IS_WEB=typeof window=="object";var ENVIRONMENT_IS_WORKER=typeof importScripts=="function";var ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string";var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var read_,readAsync,readBinary,setWindowTitle;function logExceptionOnExit(e){if(e instanceof ExitStatus)return;let toLog=e;err("exiting due to exception: "+toLog)}if(ENVIRONMENT_IS_NODE){const{createRequire:createRequire}=await import("module");var require=createRequire(import.meta.url);var fs=require("fs");var nodePath=require("path");if(ENVIRONMENT_IS_WORKER){scriptDirectory=nodePath.dirname(scriptDirectory)+"/"}else{scriptDirectory=require("url").fileURLToPath(new URL("./",import.meta.url))}read_=(filename,binary)=>{filename=isFileURI(filename)?new URL(filename):nodePath.normalize(filename);return fs.readFileSync(filename,binary?undefined:"utf8")};readBinary=filename=>{var ret=read_(filename,true);if(!ret.buffer){ret=new Uint8Array(ret)}return ret};readAsync=(filename,onload,onerror)=>{filename=isFileURI(filename)?new URL(filename):nodePath.normalize(filename);fs.readFile(filename,function(err,data){if(err)onerror(err);else onload(data.buffer)})};if(process["argv"].length>1){thisProgram=process["argv"][1].replace(/\\/g,"/")}arguments_=process["argv"].slice(2);process["on"]("uncaughtException",function(ex){if(!(ex instanceof ExitStatus)){throw ex}});process["on"]("unhandledRejection",function(reason){throw reason});quit_=(status,toThrow)=>{if(keepRuntimeAlive()){process["exitCode"]=status;throw toThrow}logExceptionOnExit(toThrow);process["exit"](status)};Module["inspect"]=function(){return"[Emscripten Module object]"}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER){scriptDirectory=self.location.href}else if(typeof document!="undefined"&&document.currentScript){scriptDirectory=document.currentScript.src}if(_scriptDir){scriptDirectory=_scriptDir}if(scriptDirectory.indexOf("blob:")!==0){scriptDirectory=scriptDirectory.substr(0,scriptDirectory.replace(/[?#].*/,"").lastIndexOf("/")+1)}else{scriptDirectory=""}{read_=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.send(null);return xhr.responseText};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=(url,onload,onerror)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){onload(xhr.response);return}onerror()};xhr.onerror=onerror;xhr.send(null)}}setWindowTitle=title=>document.title=title}else{}var out=Module["print"]||console.log.bind(console);var err=Module["printErr"]||console.warn.bind(console);Object.assign(Module,moduleOverrides);moduleOverrides=null;if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["quit"])quit_=Module["quit"];var POINTER_SIZE=4;var wasmBinary;if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];var noExitRuntime=Module["noExitRuntime"]||true;if(typeof WebAssembly!="object"){abort("no native wasm support detected")}var wasmMemory;var ABORT=false;var EXITSTATUS;function assert(condition,text){if(!condition){abort(text)}}var UTF8Decoder=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):undefined;function UTF8ArrayToString(heapOrArray,idx,maxBytesToRead){var endIdx=idx+maxBytesToRead;var endPtr=idx;while(heapOrArray[endPtr]&&!(endPtr>=endIdx))++endPtr;if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx>10,56320|ch&1023)}}return str}function UTF8ToString(ptr,maxBytesToRead){return ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead):""}function stringToUTF8Array(str,heap,outIdx,maxBytesToWrite){if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i=55296&&u<=57343){var u1=str.charCodeAt(++i);u=65536+((u&1023)<<10)|u1&1023}if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}}heap[outIdx]=0;return outIdx-startIdx}function stringToUTF8(str,outPtr,maxBytesToWrite){return stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite)}function lengthBytesUTF8(str){var len=0;for(var i=0;i=55296&&c<=57343){len+=4;++i}else{len+=3}}return len}var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;function updateMemoryViews(){var b=wasmMemory.buffer;Module["HEAP8"]=HEAP8=new Int8Array(b);Module["HEAP16"]=HEAP16=new Int16Array(b);Module["HEAP32"]=HEAP32=new Int32Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);Module["HEAPU16"]=HEAPU16=new Uint16Array(b);Module["HEAPU32"]=HEAPU32=new Uint32Array(b);Module["HEAPF32"]=HEAPF32=new Float32Array(b);Module["HEAPF64"]=HEAPF64=new Float64Array(b)}var INITIAL_MEMORY=Module["INITIAL_MEMORY"]||16777216;var wasmTable;var __ATPRERUN__=[];var __ATINIT__=[];var __ATPOSTRUN__=[];var runtimeInitialized=false;function keepRuntimeAlive(){return noExitRuntime}function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=true;SOCKFS.root=FS.mount(SOCKFS,{},null);if(!Module["noFSInit"]&&!FS.init.initialized)FS.init();FS.ignorePermissions=false;TTY.init();callRuntimeCallbacks(__ATINIT__)}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(cb){__ATPRERUN__.unshift(cb)}function addOnInit(cb){__ATINIT__.unshift(cb)}function addOnPostRun(cb){__ATPOSTRUN__.unshift(cb)}var runDependencies=0;var runDependencyWatcher=null;var dependenciesFulfilled=null;function getUniqueRunDependency(id){return id}function addRunDependency(id){runDependencies++;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}}function removeRunDependency(id){runDependencies--;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}if(runDependencies==0){if(runDependencyWatcher!==null){clearInterval(runDependencyWatcher);runDependencyWatcher=null}if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}function abort(what){if(Module["onAbort"]){Module["onAbort"](what)}what="Aborted("+what+")";err(what);ABORT=true;EXITSTATUS=1;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject(e);throw e}var dataURIPrefix="data:application/octet-stream;base64,";function isDataURI(filename){return filename.startsWith(dataURIPrefix)}function isFileURI(filename){return filename.startsWith("file://")}var wasmBinaryFile;if(Module["locateFile"]){wasmBinaryFile="rhino3dm.wasm";if(!isDataURI(wasmBinaryFile)){wasmBinaryFile=locateFile(wasmBinaryFile)}}else{wasmBinaryFile=new URL("rhino3dm.wasm",import.meta.url).href}function getBinary(file){try{if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}catch(err){abort(err)}}function getBinaryPromise(){if(!wasmBinary&&(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)){if(typeof fetch=="function"&&!isFileURI(wasmBinaryFile)){return fetch(wasmBinaryFile,{credentials:"same-origin"}).then(function(response){if(!response["ok"]){throw"failed to load wasm binary file at '"+wasmBinaryFile+"'"}return response["arrayBuffer"]()}).catch(function(){return getBinary(wasmBinaryFile)})}else{if(readAsync){return new Promise(function(resolve,reject){readAsync(wasmBinaryFile,function(response){resolve(new Uint8Array(response))},reject)})}}}return Promise.resolve().then(function(){return getBinary(wasmBinaryFile)})}function createWasm(){var info={"a":asmLibraryArg};function receiveInstance(instance,module){var exports=instance.exports;Module["asm"]=exports;wasmMemory=Module["asm"]["oa"];updateMemoryViews();wasmTable=Module["asm"]["qa"];addOnInit(Module["asm"]["pa"]);removeRunDependency("wasm-instantiate")}addRunDependency("wasm-instantiate");function receiveInstantiationResult(result){receiveInstance(result["instance"])}function instantiateArrayBuffer(receiver){return getBinaryPromise().then(function(binary){return WebAssembly.instantiate(binary,info)}).then(function(instance){return instance}).then(receiver,function(reason){err("failed to asynchronously prepare wasm: "+reason);abort(reason)})}function instantiateAsync(){if(!wasmBinary&&typeof WebAssembly.instantiateStreaming=="function"&&!isDataURI(wasmBinaryFile)&&!isFileURI(wasmBinaryFile)&&!ENVIRONMENT_IS_NODE&&typeof fetch=="function"){return fetch(wasmBinaryFile,{credentials:"same-origin"}).then(function(response){var result=WebAssembly.instantiateStreaming(response,info);return result.then(receiveInstantiationResult,function(reason){err("wasm streaming compile failed: "+reason);err("falling back to ArrayBuffer instantiation");return instantiateArrayBuffer(receiveInstantiationResult)})})}else{return instantiateArrayBuffer(receiveInstantiationResult)}}if(Module["instantiateWasm"]){try{var exports=Module["instantiateWasm"](info,receiveInstance);return exports}catch(e){err("Module.instantiateWasm callback failed with error: "+e);readyPromiseReject(e)}}instantiateAsync().catch(readyPromiseReject);return{}}var tempDouble;var tempI64;function ExitStatus(status){this.name="ExitStatus";this.message="Program terminated with exit("+status+")";this.status=status}function callRuntimeCallbacks(callbacks){while(callbacks.length>0){callbacks.shift()(Module)}}function ExceptionInfo(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24;this.set_type=function(type){HEAPU32[this.ptr+4>>2]=type};this.get_type=function(){return HEAPU32[this.ptr+4>>2]};this.set_destructor=function(destructor){HEAPU32[this.ptr+8>>2]=destructor};this.get_destructor=function(){return HEAPU32[this.ptr+8>>2]};this.set_refcount=function(refcount){HEAP32[this.ptr>>2]=refcount};this.set_caught=function(caught){caught=caught?1:0;HEAP8[this.ptr+12>>0]=caught};this.get_caught=function(){return HEAP8[this.ptr+12>>0]!=0};this.set_rethrown=function(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13>>0]=rethrown};this.get_rethrown=function(){return HEAP8[this.ptr+13>>0]!=0};this.init=function(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor);this.set_refcount(0);this.set_caught(false);this.set_rethrown(false)};this.add_ref=function(){var value=HEAP32[this.ptr>>2];HEAP32[this.ptr>>2]=value+1};this.release_ref=function(){var prev=HEAP32[this.ptr>>2];HEAP32[this.ptr>>2]=prev-1;return prev===1};this.set_adjusted_ptr=function(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr};this.get_adjusted_ptr=function(){return HEAPU32[this.ptr+16>>2]};this.get_exception_ptr=function(){var isPointer=___cxa_is_pointer_type(this.get_type());if(isPointer){return HEAPU32[this.excPtr>>2]}var adjusted=this.get_adjusted_ptr();if(adjusted!==0)return adjusted;return this.excPtr}}var exceptionLast=0;var uncaughtExceptionCount=0;function ___cxa_throw(ptr,type,destructor){var info=new ExceptionInfo(ptr);info.init(type,destructor);exceptionLast=ptr;uncaughtExceptionCount++;throw ptr}function getRandomDevice(){if(typeof crypto=="object"&&typeof crypto["getRandomValues"]=="function"){var randomBuffer=new Uint8Array(1);return()=>{crypto.getRandomValues(randomBuffer);return randomBuffer[0]}}else if(ENVIRONMENT_IS_NODE){try{var crypto_module=require("crypto");return()=>crypto_module["randomBytes"](1)[0]}catch(e){}}return()=>abort("randomDevice")}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.substr(-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.substr(0,dir.length-1)}return root+dir},basename:path=>{if(path==="/")return"/";path=PATH.normalize(path);path=path.replace(/\/$/,"");var lastSlash=path.lastIndexOf("/");if(lastSlash===-1)return path;return path.substr(lastSlash+1)},join:function(){var paths=Array.prototype.slice.call(arguments);return PATH.normalize(paths.join("/"))},join2:(l,r)=>{return PATH.normalize(l+"/"+r)}};var PATH_FS={resolve:function(){var resolvedPath="",resolvedAbsolute=false;for(var i=arguments.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?arguments[i]:FS.cwd();if(typeof path!="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!path){return""}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=PATH.isAbs(path)}resolvedPath=PATH.normalizeArray(resolvedPath.split("/").filter(p=>!!p),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."},relative:(from,to)=>{from=PATH_FS.resolve(from).substr(1);to=PATH_FS.resolve(to).substr(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;i0?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 TTY={ttys:[],init:function(){},shutdown:function(){},register:function(dev,ops){TTY.ttys[dev]={input:[],output:[],ops:ops};FS.registerDevice(dev,TTY.stream_ops)},stream_ops:{open:function(stream){var tty=TTY.ttys[stream.node.rdev];if(!tty){throw new FS.ErrnoError(43)}stream.tty=tty;stream.seekable=false},close:function(stream){stream.tty.ops.fsync(stream.tty)},fsync:function(stream){stream.tty.ops.fsync(stream.tty)},read:function(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.get_char){throw new FS.ErrnoError(60)}var bytesRead=0;for(var i=0;i0){result=buf.slice(0,bytesRead).toString("utf-8")}else{result=null}}else if(typeof window!="undefined"&&typeof window.prompt=="function"){result=window.prompt("Input: ");if(result!==null){result+="\n"}}else if(typeof readline=="function"){result=readline();if(result!==null){result+="\n"}}if(!result){return null}tty.input=intArrayFromString(result,true)}return tty.input.shift()},put_char:function(tty,val){if(val===null||val===10){out(UTF8ArrayToString(tty.output,0));tty.output=[]}else{if(val!=0)tty.output.push(val)}},fsync:function(tty){if(tty.output&&tty.output.length>0){out(UTF8ArrayToString(tty.output,0));tty.output=[]}}},default_tty1_ops:{put_char:function(tty,val){if(val===null||val===10){err(UTF8ArrayToString(tty.output,0));tty.output=[]}else{if(val!=0)tty.output.push(val)}},fsync:function(tty){if(tty.output&&tty.output.length>0){err(UTF8ArrayToString(tty.output,0));tty.output=[]}}}};function mmapAlloc(size){abort()}var MEMFS={ops_table:null,mount:function(mount){return MEMFS.createNode(null,"/",16384|511,0)},createNode:function(parent,name,mode,dev){if(FS.isBlkdev(mode)||FS.isFIFO(mode)){throw new FS.ErrnoError(63)}if(!MEMFS.ops_table){MEMFS.ops_table={dir:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,lookup:MEMFS.node_ops.lookup,mknod:MEMFS.node_ops.mknod,rename:MEMFS.node_ops.rename,unlink:MEMFS.node_ops.unlink,rmdir:MEMFS.node_ops.rmdir,readdir:MEMFS.node_ops.readdir,symlink:MEMFS.node_ops.symlink},stream:{llseek:MEMFS.stream_ops.llseek}},file:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:{llseek:MEMFS.stream_ops.llseek,read:MEMFS.stream_ops.read,write:MEMFS.stream_ops.write,allocate:MEMFS.stream_ops.allocate,mmap:MEMFS.stream_ops.mmap,msync:MEMFS.stream_ops.msync}},link:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,readlink:MEMFS.node_ops.readlink},stream:{}},chrdev:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:FS.chrdev_stream_ops}}}var node=FS.createNode(parent,name,mode,dev);if(FS.isDir(node.mode)){node.node_ops=MEMFS.ops_table.dir.node;node.stream_ops=MEMFS.ops_table.dir.stream;node.contents={}}else if(FS.isFile(node.mode)){node.node_ops=MEMFS.ops_table.file.node;node.stream_ops=MEMFS.ops_table.file.stream;node.usedBytes=0;node.contents=null}else if(FS.isLink(node.mode)){node.node_ops=MEMFS.ops_table.link.node;node.stream_ops=MEMFS.ops_table.link.stream}else if(FS.isChrdev(node.mode)){node.node_ops=MEMFS.ops_table.chrdev.node;node.stream_ops=MEMFS.ops_table.chrdev.stream}node.timestamp=Date.now();if(parent){parent.contents[name]=node;parent.timestamp=node.timestamp}return node},getFileDataAsTypedArray:function(node){if(!node.contents)return new Uint8Array(0);if(node.contents.subarray)return node.contents.subarray(0,node.usedBytes);return new Uint8Array(node.contents)},expandFileStorage:function(node,newCapacity){var prevCapacity=node.contents?node.contents.length:0;if(prevCapacity>=newCapacity)return;var CAPACITY_DOUBLING_MAX=1024*1024;newCapacity=Math.max(newCapacity,prevCapacity*(prevCapacity>>0);if(prevCapacity!=0)newCapacity=Math.max(newCapacity,256);var oldContents=node.contents;node.contents=new Uint8Array(newCapacity);if(node.usedBytes>0)node.contents.set(oldContents.subarray(0,node.usedBytes),0)},resizeFileStorage:function(node,newSize){if(node.usedBytes==newSize)return;if(newSize==0){node.contents=null;node.usedBytes=0}else{var oldContents=node.contents;node.contents=new Uint8Array(newSize);if(oldContents){node.contents.set(oldContents.subarray(0,Math.min(newSize,node.usedBytes)))}node.usedBytes=newSize}},node_ops:{getattr:function(node){var attr={};attr.dev=FS.isChrdev(node.mode)?node.id:1;attr.ino=node.id;attr.mode=node.mode;attr.nlink=1;attr.uid=0;attr.gid=0;attr.rdev=node.rdev;if(FS.isDir(node.mode)){attr.size=4096}else if(FS.isFile(node.mode)){attr.size=node.usedBytes}else if(FS.isLink(node.mode)){attr.size=node.link.length}else{attr.size=0}attr.atime=new Date(node.timestamp);attr.mtime=new Date(node.timestamp);attr.ctime=new Date(node.timestamp);attr.blksize=4096;attr.blocks=Math.ceil(attr.size/attr.blksize);return attr},setattr:function(node,attr){if(attr.mode!==undefined){node.mode=attr.mode}if(attr.timestamp!==undefined){node.timestamp=attr.timestamp}if(attr.size!==undefined){MEMFS.resizeFileStorage(node,attr.size)}},lookup:function(parent,name){throw FS.genericErrors[44]},mknod:function(parent,name,mode,dev){return MEMFS.createNode(parent,name,mode,dev)},rename:function(old_node,new_dir,new_name){if(FS.isDir(old_node.mode)){var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(new_node){for(var i in new_node.contents){throw new FS.ErrnoError(55)}}}delete old_node.parent.contents[old_node.name];old_node.parent.timestamp=Date.now();old_node.name=new_name;new_dir.contents[new_name]=old_node;new_dir.timestamp=old_node.parent.timestamp;old_node.parent=new_dir},unlink:function(parent,name){delete parent.contents[name];parent.timestamp=Date.now()},rmdir:function(parent,name){var node=FS.lookupNode(parent,name);for(var i in node.contents){throw new FS.ErrnoError(55)}delete parent.contents[name];parent.timestamp=Date.now()},readdir:function(node){var entries=[".",".."];for(var key in node.contents){if(!node.contents.hasOwnProperty(key)){continue}entries.push(key)}return entries},symlink:function(parent,newname,oldpath){var node=MEMFS.createNode(parent,newname,511|40960,0);node.link=oldpath;return node},readlink:function(node){if(!FS.isLink(node.mode)){throw new FS.ErrnoError(28)}return node.link}},stream_ops:{read:function(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=stream.node.usedBytes)return 0;var size=Math.min(stream.node.usedBytes-position,length);if(size>8&&contents.subarray){buffer.set(contents.subarray(position,position+size),offset)}else{for(var i=0;i0||position+length{assert(arrayBuffer,'Loading data file "'+url+'" failed (no arrayBuffer).');onload(new Uint8Array(arrayBuffer));if(dep)removeRunDependency(dep)},event=>{if(onerror){onerror()}else{throw'Loading data file "'+url+'" failed.'}});if(dep)addRunDependency(dep)}var FS={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:false,ignorePermissions:true,ErrnoError:null,genericErrors:{},filesystems:null,syncFSRequests:0,lookupPath:(path,opts={})=>{path=PATH_FS.resolve(path);if(!path)return{path:"",node:null};var defaults={follow_mount:true,recurse_count:0};opts=Object.assign(defaults,opts);if(opts.recurse_count>8){throw new FS.ErrnoError(32)}var parts=path.split("/").filter(p=>!!p);var current=FS.root;var current_path="/";for(var i=0;i40){throw new FS.ErrnoError(32)}}}}return{path:current_path,node:current}},getPath:node=>{var path;while(true){if(FS.isRoot(node)){var mount=node.mount.mountpoint;if(!path)return mount;return mount[mount.length-1]!=="/"?mount+"/"+path:mount+path}path=path?node.name+"/"+path:node.name;node=node.parent}},hashName:(parentid,name)=>{var hash=0;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,parent)}var hash=FS.hashName(parent.id,name);for(var node=FS.nameTable[hash];node;node=node.name_next){var nodeName=node.name;if(node.parent.id===parent.id&&nodeName===name){return node}}return FS.lookup(parent,name)},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},flagModes:{"r":0,"r+":2,"w":577,"w+":578,"a":1089,"a+":1090},modeStringToFlags:str=>{var flags=FS.flagModes[str];if(typeof flags=="undefined"){throw new Error("Unknown file open mode: "+str)}return flags},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}else if(perms.includes("w")&&!(node.mode&146)){return 2}else if(perms.includes("x")&&!(node.mode&73)){return 2}return 0},mayLookup:dir=>{var errCode=FS.nodePermissions(dir,"x");if(errCode)return errCode;if(!dir.node_ops.lookup)return 2;return 0},mayCreate:(dir,name)=>{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}else if(FS.isDir(node.mode)){if(FS.flagsToPermissionString(flags)!=="r"||flags&512){return 31}}return FS.nodePermissions(node,FS.flagsToPermissionString(flags))},MAX_OPEN_FDS:4096,nextfd:(fd_start=0,fd_end=FS.MAX_OPEN_FDS)=>{for(var fd=fd_start;fd<=fd_end;fd++){if(!FS.streams[fd]){return fd}}throw new FS.ErrnoError(33)},getStream:fd=>FS.streams[fd],createStream:(stream,fd_start,fd_end)=>{if(!FS.FSStream){FS.FSStream=function(){this.shared={}};FS.FSStream.prototype={};Object.defineProperties(FS.FSStream.prototype,{object:{get:function(){return this.node},set:function(val){this.node=val}},isRead:{get:function(){return(this.flags&2097155)!==1}},isWrite:{get:function(){return(this.flags&2097155)!==0}},isAppend:{get:function(){return this.flags&1024}},flags:{get:function(){return this.shared.flags},set:function(val){this.shared.flags=val}},position:{get:function(){return this.shared.position},set:function(val){this.shared.position=val}}})}stream=Object.assign(new FS.FSStream,stream);var fd=FS.nextfd(fd_start,fd_end);stream.fd=fd;FS.streams[fd]=stream;return stream},closeStream:fd=>{FS.streams[fd]=null},chrdev_stream_ops:{open:stream=>{var device=FS.getDevice(stream.node.rdev);stream.stream_ops=device.stream_ops;if(stream.stream_ops.open){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.apply(check,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)}}mounts.forEach(mount=>{if(!mount.type.syncfs){return done(null)}mount.type.syncfs(mount,populate,done)})},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:type,opts:opts,mountpoint: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);Object.keys(FS.nameTable).forEach(hash=>{var current=FS.nameTable[hash];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||name==="."||name===".."){throw new FS.ErrnoError(28)}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)},create:(path,mode)=>{mode=mode!==undefined?mode:438;mode&=4095;mode|=32768;return FS.mknod(path,mode,0)},mkdir:(path,mode)=>{mode=mode!==undefined?mode:511;mode&=511|512;mode|=16384;return FS.mknod(path,mode,0)},mkdirTree:(path,mode)=>{var dirs=path.split("/");var d="";for(var i=0;i{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)}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;if(!node.node_ops.readdir){throw new FS.ErrnoError(54)}return node.node_ops.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 PATH_FS.resolve(FS.getPath(link.parent),link.node_ops.readlink(link))},stat:(path,dontFollow)=>{var lookup=FS.lookupPath(path,{follow:!dontFollow});var node=lookup.node;if(!node){throw new FS.ErrnoError(44)}if(!node.node_ops.getattr){throw new FS.ErrnoError(63)}return node.node_ops.getattr(node)},lstat:path=>{return FS.stat(path,true)},chmod:(path,mode,dontFollow)=>{var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}if(!node.node_ops.setattr){throw new FS.ErrnoError(63)}node.node_ops.setattr(node,{mode:mode&4095|node.mode&~4095,timestamp:Date.now()})},lchmod:(path,mode)=>{FS.chmod(path,mode,true)},fchmod:(fd,mode)=>{var stream=FS.getStream(fd);if(!stream){throw new FS.ErrnoError(8)}FS.chmod(stream.node,mode)},chown:(path,uid,gid,dontFollow)=>{var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}if(!node.node_ops.setattr){throw new FS.ErrnoError(63)}node.node_ops.setattr(node,{timestamp:Date.now()})},lchown:(path,uid,gid)=>{FS.chown(path,uid,gid,true)},fchown:(fd,uid,gid)=>{var stream=FS.getStream(fd);if(!stream){throw new FS.ErrnoError(8)}FS.chown(stream.node,uid,gid)},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}if(!node.node_ops.setattr){throw new FS.ErrnoError(63)}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)}node.node_ops.setattr(node,{size:len,timestamp:Date.now()})},ftruncate:(fd,len)=>{var stream=FS.getStream(fd);if(!stream){throw new FS.ErrnoError(8)}if((stream.flags&2097155)===0){throw new FS.ErrnoError(28)}FS.truncate(stream.node,len)},utime:(path,atime,mtime)=>{var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;node.node_ops.setattr(node,{timestamp:Math.max(atime,mtime)})},open:(path,flags,mode)=>{if(path===""){throw new FS.ErrnoError(44)}flags=typeof flags=="string"?FS.modeStringToFlags(flags):flags;mode=typeof mode=="undefined"?438:mode;if(flags&64){mode=mode&4095|32768}else{mode=0}var node;if(typeof path=="object"){node=path}else{path=PATH.normalize(path);try{var lookup=FS.lookupPath(path,{follow:!(flags&131072)});node=lookup.node}catch(e){}}var created=false;if(flags&64){if(node){if(flags&128){throw new FS.ErrnoError(20)}}else{node=FS.mknod(path,mode,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:node,path:FS.getPath(node),flags:flags,seekable:true,position:0,stream_ops:node.stream_ops,ungotten:[],error:false});if(stream.stream_ops.open){stream.stream_ops.open(stream)}if(Module["logReadFiles"]&&!(flags&1)){if(!FS.readFiles)FS.readFiles={};if(!(path in FS.readFiles)){FS.readFiles[path]=1}}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},allocate:(stream,offset,length)=>{if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(offset<0||length<=0){throw new FS.ErrnoError(28)}if((stream.flags&2097155)===0){throw new FS.ErrnoError(8)}if(!FS.isFile(stream.node.mode)&&!FS.isDir(stream.node.mode)){throw new FS.ErrnoError(43)}if(!stream.stream_ops.allocate){throw new FS.ErrnoError(138)}stream.stream_ops.allocate(stream,offset,length)},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)}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)},munmap:stream=>0,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"){throw new Error('Invalid encoding type "'+opts.encoding+'"')}var ret;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"){ret=UTF8ArrayToString(buf,0)}else if(opts.encoding==="binary"){ret=buf}FS.close(stream);return ret},writeFile:(path,data,opts={})=>{opts.flags=opts.flags||577;var stream=FS.open(path,opts.flags,opts.mode);if(typeof data=="string"){var buf=new Uint8Array(lengthBytesUTF8(data)+1);var actualNumBytes=stringToUTF8Array(data,buf,0,buf.length);FS.write(stream,buf,0,actualNumBytes,undefined,opts.canOwn)}else if(ArrayBuffer.isView(data)){FS.write(stream,data,0,data.byteLength,undefined,opts.canOwn)}else{throw new Error("Unsupported data type")}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});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 random_device=getRandomDevice();FS.createDevice("/dev","random",random_device);FS.createDevice("/dev","urandom",random_device);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",16384|511,73);node.node_ops={lookup:(parent,name)=>{var fd=+name;var stream=FS.getStream(fd);if(!stream)throw new FS.ErrnoError(8);var ret={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>stream.path}};ret.parent=ret;return ret}};return node}},{},"/proc/self/fd")},createStandardStreams:()=>{if(Module["stdin"]){FS.createDevice("/dev","stdin",Module["stdin"])}else{FS.symlink("/dev/tty","/dev/stdin")}if(Module["stdout"]){FS.createDevice("/dev","stdout",null,Module["stdout"])}else{FS.symlink("/dev/tty","/dev/stdout")}if(Module["stderr"]){FS.createDevice("/dev","stderr",null,Module["stderr"])}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)},ensureErrnoError:()=>{if(FS.ErrnoError)return;FS.ErrnoError=function ErrnoError(errno,node){this.node=node;this.setErrno=function(errno){this.errno=errno};this.setErrno(errno);this.message="FS error"};FS.ErrnoError.prototype=new Error;FS.ErrnoError.prototype.constructor=FS.ErrnoError;[44].forEach(code=>{FS.genericErrors[code]=new FS.ErrnoError(code);FS.genericErrors[code].stack=""})},staticInit:()=>{FS.ensureErrnoError();FS.nameTable=new Array(4096);FS.mount(MEMFS,{},"/");FS.createDefaultDirectories();FS.createDefaultDevices();FS.createSpecialDirectories();FS.filesystems={"MEMFS":MEMFS}},init:(input,output,error)=>{FS.init.initialized=true;FS.ensureErrnoError();Module["stdin"]=input||Module["stdin"];Module["stdout"]=output||Module["stdout"];Module["stderr"]=error||Module["stderr"];FS.createStandardStreams()},quit:()=>{FS.init.initialized=false;for(var i=0;i{var mode=0;if(canRead)mode|=292|73;if(canWrite)mode|=146;return mode},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){}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){if(typeof data=="string"){var arr=new Array(data.length);for(var i=0,len=data.length;i{var path=PATH.join2(typeof parent=="string"?parent:FS.getPath(parent),name);var mode=FS.getMode(!!input,!!output);if(!FS.createDevice.major)FS.createDevice.major=64;var dev=FS.makedev(FS.createDevice.major++,0);FS.registerDevice(dev,{open:stream=>{stream.seekable=false},close:stream=>{if(output&&output.buffer&&output.buffer.length){output(10)}},read:(stream,buffer,offset,length,pos)=>{var bytesRead=0;for(var i=0;i{for(var i=0;i{if(obj.isDevice||obj.isFolder||obj.link||obj.contents)return true;if(typeof XMLHttpRequest!="undefined"){throw new Error("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.")}else if(read_){try{obj.contents=intArrayFromString(read_(obj.url),true);obj.usedBytes=obj.contents.length}catch(e){throw new FS.ErrnoError(29)}}else{throw new Error("Cannot load without read() or XMLHttpRequest.")}},createLazyFile:(parent,name,url,canRead,canWrite)=>{function LazyUint8Array(){this.lengthKnown=false;this.chunks=[]}LazyUint8Array.prototype.get=function LazyUint8Array_get(idx){if(idx>this.length-1||idx<0){return undefined}var chunkOffset=idx%this.chunkSize;var chunkNum=idx/this.chunkSize|0;return this.getter(chunkNum)[chunkOffset]};LazyUint8Array.prototype.setDataGetter=function LazyUint8Array_setDataGetter(getter){this.getter=getter};LazyUint8Array.prototype.cacheLength=function LazyUint8Array_cacheLength(){var xhr=new XMLHttpRequest;xhr.open("HEAD",url,false);xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))throw new Error("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)throw new Error("invalid range ("+from+", "+to+") or no bytes requested!");if(to>datalength-1)throw new Error("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))throw new Error("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")throw new Error("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};if(typeof XMLHttpRequest!="undefined"){if(!ENVIRONMENT_IS_WORKER)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var lazyArray=new LazyUint8Array;Object.defineProperties(lazyArray,{length:{get:function(){if(!this.lengthKnown){this.cacheLength()}return this._length}},chunkSize:{get:function(){if(!this.lengthKnown){this.cacheLength()}return this._chunkSize}}});var properties={isDevice:false,contents:lazyArray}}else{var properties={isDevice:false,url: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={};var keys=Object.keys(node.stream_ops);keys.forEach(key=>{var fn=node.stream_ops[key];stream_ops[key]=function forceLoadLazyFile(){FS.forceLoadFile(node);return fn.apply(null,arguments)}});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:ptr,allocated:true}};node.stream_ops=stream_ops;return node},createPreloadedFile:(parent,name,url,canRead,canWrite,onload,onerror,dontCreateFile,canOwn,preFinish)=>{var fullname=name?PATH_FS.resolve(PATH.join2(parent,name)):parent;var dep=getUniqueRunDependency("cp "+fullname);function processData(byteArray){function finish(byteArray){if(preFinish)preFinish();if(!dontCreateFile){FS.createDataFile(parent,name,byteArray,canRead,canWrite,canOwn)}if(onload)onload();removeRunDependency(dep)}if(Browser.handledByPreloadPlugin(byteArray,fullname,finish,()=>{if(onerror)onerror();removeRunDependency(dep)})){return}finish(byteArray)}addRunDependency(dep);if(typeof url=="string"){asyncLoad(url,byteArray=>processData(byteArray),onerror)}else{processData(url)}},indexedDB:()=>{return window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB},DB_NAME:()=>{return"EM_FS_"+window.location.pathname},DB_VERSION:20,DB_STORE_NAME:"FILE_DATA",saveFilesToDB:(paths,onload,onerror)=>{onload=onload||(()=>{});onerror=onerror||(()=>{});var indexedDB=FS.indexedDB();try{var openRequest=indexedDB.open(FS.DB_NAME(),FS.DB_VERSION)}catch(e){return onerror(e)}openRequest.onupgradeneeded=()=>{out("creating db");var db=openRequest.result;db.createObjectStore(FS.DB_STORE_NAME)};openRequest.onsuccess=()=>{var db=openRequest.result;var transaction=db.transaction([FS.DB_STORE_NAME],"readwrite");var files=transaction.objectStore(FS.DB_STORE_NAME);var ok=0,fail=0,total=paths.length;function finish(){if(fail==0)onload();else onerror()}paths.forEach(path=>{var putRequest=files.put(FS.analyzePath(path).object.contents,path);putRequest.onsuccess=()=>{ok++;if(ok+fail==total)finish()};putRequest.onerror=()=>{fail++;if(ok+fail==total)finish()}});transaction.onerror=onerror};openRequest.onerror=onerror},loadFilesFromDB:(paths,onload,onerror)=>{onload=onload||(()=>{});onerror=onerror||(()=>{});var indexedDB=FS.indexedDB();try{var openRequest=indexedDB.open(FS.DB_NAME(),FS.DB_VERSION)}catch(e){return onerror(e)}openRequest.onupgradeneeded=onerror;openRequest.onsuccess=()=>{var db=openRequest.result;try{var transaction=db.transaction([FS.DB_STORE_NAME],"readonly")}catch(e){onerror(e);return}var files=transaction.objectStore(FS.DB_STORE_NAME);var ok=0,fail=0,total=paths.length;function finish(){if(fail==0)onload();else onerror()}paths.forEach(path=>{var getRequest=files.get(path);getRequest.onsuccess=()=>{if(FS.analyzePath(path).exists){FS.unlink(path)}FS.createDataFile(PATH.dirname(path),PATH.basename(path),getRequest.result,true,true,true);ok++;if(ok+fail==total)finish()};getRequest.onerror=()=>{fail++;if(ok+fail==total)finish()}});transaction.onerror=onerror};openRequest.onerror=onerror}};var SOCKFS={mount:function(mount){Module["websocket"]=Module["websocket"]&&"object"===typeof Module["websocket"]?Module["websocket"]:{};Module["websocket"]._callbacks={};Module["websocket"]["on"]=function(event,callback){if("function"===typeof callback){this._callbacks[event]=callback}return this};Module["websocket"].emit=function(event,param){if("function"===typeof this._callbacks[event]){this._callbacks[event].call(this,param)}};return FS.createNode(null,"/",16384|511,0)},createSocket:function(family,type,protocol){type&=~526336;var streaming=type==1;if(streaming&&protocol&&protocol!=6){throw new FS.ErrnoError(66)}var sock={family:family,type:type,protocol:protocol,server:null,error:null,peers:{},pending:[],recv_queue:[],sock_ops:SOCKFS.websocket_sock_ops};var name=SOCKFS.nextname();var node=FS.createNode(SOCKFS.root,name,49152,0);node.sock=sock;var stream=FS.createStream({path:name,node:node,flags:2,seekable:false,stream_ops:SOCKFS.stream_ops});sock.stream=stream;return sock},getSocket:function(fd){var stream=FS.getStream(fd);if(!stream||!FS.isSocket(stream.node.mode)){return null}return stream.node.sock},stream_ops:{poll:function(stream){var sock=stream.node.sock;return sock.sock_ops.poll(sock)},ioctl:function(stream,request,varargs){var sock=stream.node.sock;return sock.sock_ops.ioctl(sock,request,varargs)},read:function(stream,buffer,offset,length,position){var sock=stream.node.sock;var msg=sock.sock_ops.recvmsg(sock,length);if(!msg){return 0}buffer.set(msg.buffer,offset);return msg.buffer.length},write:function(stream,buffer,offset,length,position){var sock=stream.node.sock;return sock.sock_ops.sendmsg(sock,buffer,offset,length)},close:function(stream){var sock=stream.node.sock;sock.sock_ops.close(sock)}},nextname:function(){if(!SOCKFS.nextname.current){SOCKFS.nextname.current=0}return"socket["+SOCKFS.nextname.current+++"]"},websocket_sock_ops:{createPeer:function(sock,addr,port){var ws;if(typeof addr=="object"){ws=addr;addr=null;port=null}if(ws){if(ws._socket){addr=ws._socket.remoteAddress;port=ws._socket.remotePort}else{var result=/ws[s]?:\/\/([^:]+):(\d+)/.exec(ws.url);if(!result){throw new Error("WebSocket URL must be in the format ws(s)://address:port")}addr=result[1];port=parseInt(result[2],10)}}else{try{var runtimeConfig=Module["websocket"]&&"object"===typeof Module["websocket"];var url="ws:#".replace("#","//");if(runtimeConfig){if("string"===typeof Module["websocket"]["url"]){url=Module["websocket"]["url"]}}if(url==="ws://"||url==="wss://"){var parts=addr.split("/");url=url+parts[0]+":"+port+"/"+parts.slice(1).join("/")}var subProtocols="binary";if(runtimeConfig){if("string"===typeof Module["websocket"]["subprotocol"]){subProtocols=Module["websocket"]["subprotocol"]}}var opts=undefined;if(subProtocols!=="null"){subProtocols=subProtocols.replace(/^ +| +$/g,"").split(/ *, */);opts=subProtocols}if(runtimeConfig&&null===Module["websocket"]["subprotocol"]){subProtocols="null";opts=undefined}var WebSocketConstructor;if(ENVIRONMENT_IS_NODE){WebSocketConstructor=require("ws")}else{WebSocketConstructor=WebSocket}ws=new WebSocketConstructor(url,opts);ws.binaryType="arraybuffer"}catch(e){throw new FS.ErrnoError(23)}}var peer={addr:addr,port:port,socket:ws,dgram_send_queue:[]};SOCKFS.websocket_sock_ops.addPeer(sock,peer);SOCKFS.websocket_sock_ops.handlePeerEvents(sock,peer);if(sock.type===2&&typeof sock.sport!="undefined"){peer.dgram_send_queue.push(new Uint8Array([255,255,255,255,"p".charCodeAt(0),"o".charCodeAt(0),"r".charCodeAt(0),"t".charCodeAt(0),(sock.sport&65280)>>8,sock.sport&255]))}return peer},getPeer:function(sock,addr,port){return sock.peers[addr+":"+port]},addPeer:function(sock,peer){sock.peers[peer.addr+":"+peer.port]=peer},removePeer:function(sock,peer){delete sock.peers[peer.addr+":"+peer.port]},handlePeerEvents:function(sock,peer){var first=true;var handleOpen=function(){Module["websocket"].emit("open",sock.stream.fd);try{var queued=peer.dgram_send_queue.shift();while(queued){peer.socket.send(queued);queued=peer.dgram_send_queue.shift()}}catch(e){peer.socket.close()}};function handleMessage(data){if(typeof data=="string"){var encoder=new TextEncoder;data=encoder.encode(data)}else{assert(data.byteLength!==undefined);if(data.byteLength==0){return}data=new Uint8Array(data)}var wasfirst=first;first=false;if(wasfirst&&data.length===10&&data[0]===255&&data[1]===255&&data[2]===255&&data[3]===255&&data[4]==="p".charCodeAt(0)&&data[5]==="o".charCodeAt(0)&&data[6]==="r".charCodeAt(0)&&data[7]==="t".charCodeAt(0)){var newport=data[8]<<8|data[9];SOCKFS.websocket_sock_ops.removePeer(sock,peer);peer.port=newport;SOCKFS.websocket_sock_ops.addPeer(sock,peer);return}sock.recv_queue.push({addr:peer.addr,port:peer.port,data:data});Module["websocket"].emit("message",sock.stream.fd)}if(ENVIRONMENT_IS_NODE){peer.socket.on("open",handleOpen);peer.socket.on("message",function(data,isBinary){if(!isBinary){return}handleMessage(new Uint8Array(data).buffer)});peer.socket.on("close",function(){Module["websocket"].emit("close",sock.stream.fd)});peer.socket.on("error",function(error){sock.error=14;Module["websocket"].emit("error",[sock.stream.fd,sock.error,"ECONNREFUSED: Connection refused"])})}else{peer.socket.onopen=handleOpen;peer.socket.onclose=function(){Module["websocket"].emit("close",sock.stream.fd)};peer.socket.onmessage=function peer_socket_onmessage(event){handleMessage(event.data)};peer.socket.onerror=function(error){sock.error=14;Module["websocket"].emit("error",[sock.stream.fd,sock.error,"ECONNREFUSED: Connection refused"])}}},poll:function(sock){if(sock.type===1&&sock.server){return sock.pending.length?64|1:0}var mask=0;var dest=sock.type===1?SOCKFS.websocket_sock_ops.getPeer(sock,sock.daddr,sock.dport):null;if(sock.recv_queue.length||!dest||dest&&dest.socket.readyState===dest.socket.CLOSING||dest&&dest.socket.readyState===dest.socket.CLOSED){mask|=64|1}if(!dest||dest&&dest.socket.readyState===dest.socket.OPEN){mask|=4}if(dest&&dest.socket.readyState===dest.socket.CLOSING||dest&&dest.socket.readyState===dest.socket.CLOSED){mask|=16}return mask},ioctl:function(sock,request,arg){switch(request){case 21531:var bytes=0;if(sock.recv_queue.length){bytes=sock.recv_queue[0].data.length}HEAP32[arg>>2]=bytes;return 0;default:return 28}},close:function(sock){if(sock.server){try{sock.server.close()}catch(e){}sock.server=null}var peers=Object.keys(sock.peers);for(var i=0;i>2]=value;return value}function inetNtop4(addr){return(addr&255)+"."+(addr>>8&255)+"."+(addr>>16&255)+"."+(addr>>24&255)}function inetNtop6(ints){var str="";var word=0;var longest=0;var lastzero=0;var zstart=0;var len=0;var i=0;var parts=[ints[0]&65535,ints[0]>>16,ints[1]&65535,ints[1]>>16,ints[2]&65535,ints[2]>>16,ints[3]&65535,ints[3]>>16];var hasipv4=true;var v4part="";for(i=0;i<5;i++){if(parts[i]!==0){hasipv4=false;break}}if(hasipv4){v4part=inetNtop4(parts[6]|parts[7]<<16);if(parts[5]===-1){str="::ffff:";str+=v4part;return str}if(parts[5]===0){str="::";if(v4part==="0.0.0.0")v4part="";if(v4part==="0.0.0.1")v4part="1";str+=v4part;return str}}for(word=0;word<8;word++){if(parts[word]===0){if(word-lastzero>1){len=0}lastzero=word;len++}if(len>longest){longest=len;zstart=word-longest+1}}for(word=0;word<8;word++){if(longest>1){if(parts[word]===0&&word>=zstart&&word>1];var port=_ntohs(HEAPU16[sa+2>>1]);var addr;switch(family){case 2:if(salen!==16){return{errno:28}}addr=HEAP32[sa+4>>2];addr=inetNtop4(addr);break;case 10:if(salen!==28){return{errno:28}}addr=[HEAP32[sa+8>>2],HEAP32[sa+12>>2],HEAP32[sa+16>>2],HEAP32[sa+20>>2]];addr=inetNtop6(addr);break;default:return{errno:5}}return{family:family,addr:addr,port:port}}function 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}function jstoi_q(str){return parseInt(str)}function 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]=jstoi_q(words[words.length-4])+jstoi_q(words[words.length-3])*256;words[words.length-3]=jstoi_q(words[words.length-2])+jstoi_q(words[words.length-1])*256;words=words.slice(0,words.length-2)}else{words=str.split(":")}offset=0;z=0;for(w=0;w>2]=stat.dev;HEAP32[buf+8>>2]=stat.ino;HEAP32[buf+12>>2]=stat.mode;HEAPU32[buf+16>>2]=stat.nlink;HEAP32[buf+20>>2]=stat.uid;HEAP32[buf+24>>2]=stat.gid;HEAP32[buf+28>>2]=stat.rdev;tempI64=[stat.size>>>0,(tempDouble=stat.size,+Math.abs(tempDouble)>=1?tempDouble>0?(Math.min(+Math.floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+40>>2]=tempI64[0],HEAP32[buf+44>>2]=tempI64[1];HEAP32[buf+48>>2]=4096;HEAP32[buf+52>>2]=stat.blocks;var atime=stat.atime.getTime();var mtime=stat.mtime.getTime();var ctime=stat.ctime.getTime();tempI64=[Math.floor(atime/1e3)>>>0,(tempDouble=Math.floor(atime/1e3),+Math.abs(tempDouble)>=1?tempDouble>0?(Math.min(+Math.floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+56>>2]=tempI64[0],HEAP32[buf+60>>2]=tempI64[1];HEAPU32[buf+64>>2]=atime%1e3*1e3;tempI64=[Math.floor(mtime/1e3)>>>0,(tempDouble=Math.floor(mtime/1e3),+Math.abs(tempDouble)>=1?tempDouble>0?(Math.min(+Math.floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+72>>2]=tempI64[0],HEAP32[buf+76>>2]=tempI64[1];HEAPU32[buf+80>>2]=mtime%1e3*1e3;tempI64=[Math.floor(ctime/1e3)>>>0,(tempDouble=Math.floor(ctime/1e3),+Math.abs(tempDouble)>=1?tempDouble>0?(Math.min(+Math.floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+88>>2]=tempI64[0],HEAP32[buf+92>>2]=tempI64[1];HEAPU32[buf+96>>2]=ctime%1e3*1e3;tempI64=[stat.ino>>>0,(tempDouble=stat.ino,+Math.abs(tempDouble)>=1?tempDouble>0?(Math.min(+Math.floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+104>>2]=tempI64[0],HEAP32[buf+108>>2]=tempI64[1];return 0},doMsync:function(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)},varargs:undefined,get:function(){SYSCALLS.varargs+=4;var ret=HEAP32[SYSCALLS.varargs-4>>2];return ret},getStr:function(ptr){var ret=UTF8ToString(ptr);return ret},getStreamFromFD:function(fd){var stream=FS.getStream(fd);if(!stream)throw new FS.ErrnoError(8);return stream}};function ___syscall_connect(fd,addr,addrlen){try{var sock=getSocketFromFD(fd);var info=getSocketAddress(addr,addrlen);sock.sock_ops.connect(sock,info.addr,info.port);return 0}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function ___syscall_faccessat(dirfd,path,amode,flags){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 instanceof FS.ErrnoError))throw e;return-e.errno}}function ___syscall_fcntl64(fd,cmd,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(cmd){case 0:{var arg=SYSCALLS.get();if(arg<0){return-28}var newStream;newStream=FS.createStream(stream,arg);return newStream.fd}case 1:case 2:return 0;case 3:return stream.flags;case 4:{var arg=SYSCALLS.get();stream.flags|=arg;return 0}case 5:{var arg=SYSCALLS.get();var offset=0;HEAP16[arg+offset>>1]=2;return 0}case 6:case 7:return 0;case 16:case 8:return-28;case 9:setErrNo(28);return-1;default:{return-28}}}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function ___syscall_fstat64(fd,buf){try{var stream=SYSCALLS.getStreamFromFD(fd);return SYSCALLS.doStat(FS.stat,stream.path,buf)}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function convertI32PairToI53Checked(lo,hi){return hi+2097152>>>0<4194305-!!lo?(lo>>>0)+hi*4294967296:NaN}function ___syscall_ftruncate64(fd,length_low,length_high){try{var length=convertI32PairToI53Checked(length_low,length_high);if(isNaN(length))return-61;FS.ftruncate(fd,length);return 0}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function ___syscall_ioctl(fd,op,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(op){case 21509:case 21505:{if(!stream.tty)return-59;return 0}case 21510:case 21511:case 21512:case 21506:case 21507:case 21508:{if(!stream.tty)return-59;return 0}case 21519:{if(!stream.tty)return-59;var argp=SYSCALLS.get();HEAP32[argp>>2]=0;return 0}case 21520:{if(!stream.tty)return-59;return-28}case 21531:{var argp=SYSCALLS.get();return FS.ioctl(stream,op,argp)}case 21523:{if(!stream.tty)return-59;return 0}case 21524:{if(!stream.tty)return-59;return 0}default:return-28}}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function ___syscall_lstat64(path,buf){try{path=SYSCALLS.getStr(path);return SYSCALLS.doStat(FS.lstat,path,buf)}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function ___syscall_newfstatat(dirfd,path,buf,flags){try{path=SYSCALLS.getStr(path);var nofollow=flags&256;var allowEmpty=flags&4096;flags=flags&~6400;path=SYSCALLS.calculateAt(dirfd,path,allowEmpty);return SYSCALLS.doStat(nofollow?FS.lstat:FS.stat,path,buf)}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function ___syscall_openat(dirfd,path,flags,varargs){SYSCALLS.varargs=varargs;try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);var mode=varargs?SYSCALLS.get():0;return FS.open(path,flags,mode).fd}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function ___syscall_socket(domain,type,protocol){try{var sock=SOCKFS.createSocket(domain,type,protocol);return sock.stream.fd}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function ___syscall_stat64(path,buf){try{path=SYSCALLS.getStr(path);return SYSCALLS.doStat(FS.stat,path,buf)}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}var tupleRegistrations={};function runDestructors(destructors){while(destructors.length){var ptr=destructors.pop();var del=destructors.pop();del(ptr)}}function simpleReadValueFromPointer(pointer){return this["fromWireType"](HEAP32[pointer>>2])}var awaitingDependencies={};var registeredTypes={};var typeDependencies={};var char_0=48;var char_9=57;function makeLegalFunctionName(name){if(undefined===name){return"_unknown"}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 createNamedFunction(name,body){name=makeLegalFunctionName(name);return new Function("body","return function "+name+"() {\n"+' "use strict";'+" return body.apply(this, arguments);\n"+"};\n")(body)}function extendError(baseErrorType,errorName){var errorClass=createNamedFunction(errorName,function(message){this.name=errorName;this.message=message;var stack=new Error(message).stack;if(stack!==undefined){this.stack=this.toString()+"\n"+stack.replace(/^Error(:[^\n]*)?\n/,"")}});errorClass.prototype=Object.create(baseErrorType.prototype);errorClass.prototype.constructor=errorClass;errorClass.prototype.toString=function(){if(this.message===undefined){return this.name}else{return this.name+": "+this.message}};return errorClass}var InternalError=undefined;function throwInternalError(message){throw new InternalError(message)}function whenDependentTypesAreResolved(myTypes,dependentTypes,getTypeConverters){myTypes.forEach(function(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{if(registeredTypes.hasOwnProperty(dt)){typeConverters[i]=registeredTypes[dt]}else{unregisteredTypes.push(dt);if(!awaitingDependencies.hasOwnProperty(dt)){awaitingDependencies[dt]=[]}awaitingDependencies[dt].push(()=>{typeConverters[i]=registeredTypes[dt];++registered;if(registered===unregisteredTypes.length){onComplete(typeConverters)}})}});if(0===unregisteredTypes.length){onComplete(typeConverters)}}function __embind_finalize_value_array(rawTupleType){var reg=tupleRegistrations[rawTupleType];delete tupleRegistrations[rawTupleType];var elements=reg.elements;var elementsLength=elements.length;var elementTypes=elements.map(function(elt){return elt.getterReturnType}).concat(elements.map(function(elt){return elt.setterArgumentType}));var rawConstructor=reg.rawConstructor;var rawDestructor=reg.rawDestructor;whenDependentTypesAreResolved([rawTupleType],elementTypes,function(elementTypes){elements.forEach((elt,i)=>{var getterReturnType=elementTypes[i];var getter=elt.getter;var getterContext=elt.getterContext;var setterArgumentType=elementTypes[i+elementsLength];var setter=elt.setter;var setterContext=elt.setterContext;elt.read=ptr=>{return getterReturnType["fromWireType"](getter(getterContext,ptr))};elt.write=(ptr,o)=>{var destructors=[];setter(setterContext,ptr,setterArgumentType["toWireType"](destructors,o));runDestructors(destructors)}});return[{name:reg.name,"fromWireType":function(ptr){var rv=new Array(elementsLength);for(var i=0;ifield.getterReturnType).concat(fieldRecords.map(field=>field.setterArgumentType));whenDependentTypesAreResolved([structType],fieldTypes,fieldTypes=>{var fields={};fieldRecords.forEach((field,i)=>{var fieldName=field.fieldName;var getterReturnType=fieldTypes[i];var getter=field.getter;var getterContext=field.getterContext;var setterArgumentType=fieldTypes[i+fieldRecords.length];var setter=field.setter;var setterContext=field.setterContext;fields[fieldName]={read:ptr=>{return getterReturnType["fromWireType"](getter(getterContext,ptr))},write:(ptr,o)=>{var destructors=[];setter(setterContext,ptr,setterArgumentType["toWireType"](destructors,o));runDestructors(destructors)}}});return[{name:reg.name,"fromWireType":function(ptr){var rv={};for(var i in fields){rv[i]=fields[i].read(ptr)}rawDestructor(ptr);return rv},"toWireType":function(destructors,o){for(var fieldName in fields){if(!(fieldName in o)){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},"argPackAdvance":8,"readValueFromPointer":simpleReadValueFromPointer,destructorFunction:rawDestructor}]})}function __embind_register_bigint(primitiveType,name,size,minRange,maxRange){}function getShiftFromSize(size){switch(size){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError("Unknown type size: "+size)}}function embind_init_charCodes(){var codes=new Array(256);for(var i=0;i<256;++i){codes[i]=String.fromCharCode(i)}embind_charCodes=codes}var embind_charCodes=undefined;function readLatin1String(ptr){var ret="";var c=ptr;while(HEAPU8[c]){ret+=embind_charCodes[HEAPU8[c++]]}return ret}var BindingError=undefined;function throwBindingError(message){throw new BindingError(message)}function registerType(rawType,registeredInstance,options={}){if(!("argPackAdvance"in registeredInstance)){throw new TypeError("registerType registeredInstance requires argPackAdvance")}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 __embind_register_bool(rawType,name,size,trueValue,falseValue){var shift=getShiftFromSize(size);name=readLatin1String(name);registerType(rawType,{name:name,"fromWireType":function(wt){return!!wt},"toWireType":function(destructors,o){return o?trueValue:falseValue},"argPackAdvance":8,"readValueFromPointer":function(pointer){var heap;if(size===1){heap=HEAP8}else if(size===2){heap=HEAP16}else if(size===4){heap=HEAP32}else{throw new TypeError("Unknown boolean type size: "+name)}return this["fromWireType"](heap[pointer>>shift])},destructorFunction:null})}function ClassHandle_isAliasOf(other){if(!(this instanceof ClassHandle)){return false}if(!(other instanceof ClassHandle)){return false}var leftClass=this.$$.ptrType.registeredClass;var left=this.$$.ptr;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}function shallowCopyInternalPointer(o){return{count:o.count,deleteScheduled:o.deleteScheduled,preservePointerOnDelete:o.preservePointerOnDelete,ptr:o.ptr,ptrType:o.ptrType,smartPtr:o.smartPtr,smartPtrType:o.smartPtrType}}function throwInstanceAlreadyDeleted(obj){function getInstanceTypeName(handle){return handle.$$.ptrType.registeredClass.name}throwBindingError(getInstanceTypeName(obj)+" instance already deleted")}var finalizationRegistry=false;function detachFinalizer(handle){}function runDestructor($$){if($$.smartPtr){$$.smartPtrType.rawDestructor($$.smartPtr)}else{$$.ptrType.registeredClass.rawDestructor($$.ptr)}}function releaseClassHandle($$){$$.count.value-=1;var toDelete=0===$$.count.value;if(toDelete){runDestructor($$)}}function 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 registeredPointers={};function getInheritedInstanceCount(){return Object.keys(registeredInstances).length}function getLiveInheritedInstances(){var rv=[];for(var k in registeredInstances){if(registeredInstances.hasOwnProperty(k)){rv.push(registeredInstances[k])}}return rv}var deletionQueue=[];function flushPendingDeletes(){while(deletionQueue.length){var obj=deletionQueue.pop();obj.$$.deleteScheduled=false;obj["delete"]()}}var delayFunction=undefined;function setDelayFunction(fn){delayFunction=fn;if(deletionQueue.length&&delayFunction){delayFunction(flushPendingDeletes)}}function init_embind(){Module["getInheritedInstanceCount"]=getInheritedInstanceCount;Module["getLiveInheritedInstances"]=getLiveInheritedInstances;Module["flushPendingDeletes"]=flushPendingDeletes;Module["setDelayFunction"]=setDelayFunction}var registeredInstances={};function getBasestPointer(class_,ptr){if(ptr===undefined){throwBindingError("ptr should not be undefined")}while(class_.baseClass){ptr=class_.upcast(ptr);class_=class_.baseClass}return ptr}function getInheritedInstance(class_,ptr){ptr=getBasestPointer(class_,ptr);return registeredInstances[ptr]}function 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}}))}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: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})}}function attachFinalizer(handle){if("undefined"===typeof 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)}function ClassHandle_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}}function ClassHandle_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}}function ClassHandle_isDeleted(){return!this.$$.ptr}function ClassHandle_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}function init_ClassHandle(){ClassHandle.prototype["isAliasOf"]=ClassHandle_isAliasOf;ClassHandle.prototype["clone"]=ClassHandle_clone;ClassHandle.prototype["delete"]=ClassHandle_delete;ClassHandle.prototype["isDeleted"]=ClassHandle_isDeleted;ClassHandle.prototype["deleteLater"]=ClassHandle_deleteLater}function ClassHandle(){}function ensureOverloadTable(proto,methodName,humanName){if(undefined===proto[methodName].overloadTable){var prevFunc=proto[methodName];proto[methodName]=function(){if(!proto[methodName].overloadTable.hasOwnProperty(arguments.length)){throwBindingError("Function '"+humanName+"' called with an invalid number of arguments ("+arguments.length+") - expects one of ("+proto[methodName].overloadTable+")!")}return proto[methodName].overloadTable[arguments.length].apply(this,arguments)};proto[methodName].overloadTable=[];proto[methodName].overloadTable[prevFunc.argCount]=prevFunc}}function 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.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;if(undefined!==numArguments){Module[name].numArguments=numArguments}}}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=[]}function 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}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.$$){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(function(){clonedHandle["delete"]()}));if(destructors!==null){destructors.push(this.rawDestructor,ptr)}}break;default:throwBindingError("Unsupporting 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}function RegisteredPointer_getPointee(ptr){if(this.rawGetPointee){ptr=this.rawGetPointee(ptr)}return ptr}function RegisteredPointer_destructor(ptr){if(this.rawDestructor){this.rawDestructor(ptr)}}function RegisteredPointer_deleteObject(handle){if(handle!==null){handle["delete"]()}}function init_RegisteredPointer(){RegisteredPointer.prototype.getPointee=RegisteredPointer_getPointee;RegisteredPointer.prototype.destructor=RegisteredPointer_destructor;RegisteredPointer.prototype["argPackAdvance"]=8;RegisteredPointer.prototype["readValueFromPointer"]=simpleReadValueFromPointer;RegisteredPointer.prototype["deleteObject"]=RegisteredPointer_deleteObject;RegisteredPointer.prototype["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}}function replacePublicSymbol(name,value,numArguments){if(!Module.hasOwnProperty(name)){throwInternalError("Replacing nonexistant public symbol")}if(undefined!==Module[name].overloadTable&&undefined!==numArguments){Module[name].overloadTable[numArguments]=value}else{Module[name]=value;Module[name].argCount=numArguments}}function dynCallLegacy(sig,ptr,args){var f=Module["dynCall_"+sig];return args&&args.length?f.apply(null,[ptr].concat(args)):f.call(null,ptr)}function getWasmTableEntry(funcPtr){return wasmTable.get(funcPtr)}function dynCall(sig,ptr,args){if(sig.includes("j")){return dynCallLegacy(sig,ptr,args)}var rtn=getWasmTableEntry(ptr).apply(null,args);return rtn}function getDynCaller(sig,ptr){var argCache=[];return function(){argCache.length=0;Object.assign(argCache,arguments);return dynCall(sig,ptr,argCache)}}function embind__requireFunction(signature,rawFunction){signature=readLatin1String(signature);function makeDynCaller(){if(signature.includes("j")){return getDynCaller(signature,rawFunction)}return getWasmTableEntry(rawFunction)}var fp=makeDynCaller();if(typeof fp!="function"){throwBindingError("unknown function pointer with signature "+signature+": "+rawFunction)}return fp}var UnboundTypeError=undefined;function getTypeName(type){var ptr=___getTypeName(type);var rv=readLatin1String(ptr);_free(ptr);return rv}function 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){name=readLatin1String(name);getActualType=embind__requireFunction(getActualTypeSignature,getActualType);if(upcast){upcast=embind__requireFunction(upcastSignature,upcast)}if(downcast){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]:[],function(base){base=base[0];var baseClass;var basePrototype;if(baseClassRawType){baseClass=base.registeredClass;basePrototype=baseClass.instancePrototype}else{basePrototype=ClassHandle.prototype}var constructor=createNamedFunction(legalFunctionName,function(){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[arguments.length];if(undefined===body){throw new BindingError("Tried to invoke ctor of "+name+" with invalid number of parameters ("+arguments.length+") - expected ("+Object.keys(registeredClass.constructor_body).toString()+") parameters instead!")}return body.apply(this,arguments)});var instancePrototype=Object.create(basePrototype,{constructor:{value:constructor}});constructor.prototype=instancePrototype;var registeredClass=new RegisteredClass(name,constructor,instancePrototype,rawDestructor,baseClass,getActualType,upcast,downcast);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]})}function new_(constructor,argumentList){if(!(constructor instanceof Function)){throw new TypeError("new_ called with constructor type "+typeof constructor+" which is not a function")}var dummy=createNamedFunction(constructor.name||"unknownFunctionName",function(){});dummy.prototype=constructor.prototype;var obj=new dummy;var r=constructor.apply(obj,argumentList);return r instanceof Object?r:obj}function craftInvokerFunction(humanName,argTypes,classType,cppInvokerFunc,cppTargetFunc){var argCount=argTypes.length;if(argCount<2){throwBindingError("argTypes array size mismatch! Must at least get return value and 'this' types!")}var isClassMethodFunc=argTypes[1]!==null&&classType!==null;var needsDestructorStack=false;for(var i=1;i0?", ":"")+argsListWired}invokerFnBody+=(returns?"var rv = ":"")+"invoker(fn"+(argsListWired.length>0?", ":"")+argsListWired+");\n";if(needsDestructorStack){invokerFnBody+="runDestructors(destructors);\n"}else{for(var i=isClassMethodFunc?1:2;i>2])}return array}function __embind_register_class_class_function(rawClassType,methodName,argCount,rawArgTypesAddr,invokerSignature,rawInvoker,fn){var rawArgTypes=heap32VectorToArray(argCount,rawArgTypesAddr);methodName=readLatin1String(methodName);rawInvoker=embind__requireFunction(invokerSignature,rawInvoker);whenDependentTypesAreResolved([],[rawClassType],function(classType){classType=classType[0];var humanName=classType.name+"."+methodName;function unboundTypesHandler(){throwUnboundTypeError("Cannot call "+humanName+" due to unbound types",rawArgTypes)}if(methodName.startsWith("@@")){methodName=Symbol[methodName.substring(2)]}var proto=classType.registeredClass.constructor;if(undefined===proto[methodName]){unboundTypesHandler.argCount=argCount-1;proto[methodName]=unboundTypesHandler}else{ensureOverloadTable(proto,methodName,humanName);proto[methodName].overloadTable[argCount-1]=unboundTypesHandler}whenDependentTypesAreResolved([],rawArgTypes,function(argTypes){var invokerArgsArray=[argTypes[0],null].concat(argTypes.slice(1));var func=craftInvokerFunction(humanName,invokerArgsArray,null,rawInvoker,fn);if(undefined===proto[methodName].overloadTable){func.argCount=argCount-1;proto[methodName]=func}else{proto[methodName].overloadTable[argCount-1]=func}return[]});return[]})}function __embind_register_class_constructor(rawClassType,argCount,rawArgTypesAddr,invokerSignature,invoker,rawConstructor){assert(argCount>0);var rawArgTypes=heap32VectorToArray(argCount,rawArgTypesAddr);invoker=embind__requireFunction(invokerSignature,invoker);whenDependentTypesAreResolved([],[rawClassType],function(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,function(argTypes){argTypes.splice(1,0,null);classType.registeredClass.constructor_body[argCount-1]=craftInvokerFunction(humanName,argTypes,null,invoker,rawConstructor);return[]});return[]})}function __embind_register_class_function(rawClassType,methodName,argCount,rawArgTypesAddr,invokerSignature,rawInvoker,context,isPureVirtual){var rawArgTypes=heap32VectorToArray(argCount,rawArgTypesAddr);methodName=readLatin1String(methodName);rawInvoker=embind__requireFunction(invokerSignature,rawInvoker);whenDependentTypesAreResolved([],[rawClassType],function(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,function(argTypes){var memberFunction=craftInvokerFunction(humanName,argTypes,classType,rawInvoker,context);if(undefined===proto[methodName].overloadTable){memberFunction.argCount=argCount-2;proto[methodName]=memberFunction}else{proto[methodName].overloadTable[argCount-2]=memberFunction}return[]});return[]})}function 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)}function __embind_register_class_property(classType,fieldName,getterReturnType,getterSignature,getter,getterContext,setterArgumentType,setterSignature,setter,setterContext){fieldName=readLatin1String(fieldName);getter=embind__requireFunction(getterSignature,getter);whenDependentTypesAreResolved([],[classType],function(classType){classType=classType[0];var humanName=classType.name+"."+fieldName;var desc={get:function(){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],function(types){var getterReturnType=types[0];var desc={get:function(){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_free_list=[];var emval_handle_array=[{},{value:undefined},{value:null},{value:true},{value:false}];function __emval_decref(handle){if(handle>4&&0===--emval_handle_array[handle].refcount){emval_handle_array[handle]=undefined;emval_free_list.push(handle)}}function count_emval_handles(){var count=0;for(var i=5;i{if(!handle){throwBindingError("Cannot use deleted val. handle = "+handle)}return emval_handle_array[handle].value},toHandle:value=>{switch(value){case undefined:return 1;case null:return 2;case true:return 3;case false:return 4;default:{var handle=emval_free_list.length?emval_free_list.pop():emval_handle_array.length;emval_handle_array[handle]={refcount:1,value:value};return handle}}}};function __embind_register_emval(rawType,name){name=readLatin1String(name);registerType(rawType,{name:name,"fromWireType":function(handle){var rv=Emval.toValue(handle);__emval_decref(handle);return rv},"toWireType":function(destructors,value){return Emval.toHandle(value)},"argPackAdvance":8,"readValueFromPointer":simpleReadValueFromPointer,destructorFunction:null})}function enumReadValueFromPointer(name,shift,signed){switch(shift){case 0:return function(pointer){var heap=signed?HEAP8:HEAPU8;return this["fromWireType"](heap[pointer])};case 1:return function(pointer){var heap=signed?HEAP16:HEAPU16;return this["fromWireType"](heap[pointer>>1])};case 2:return function(pointer){var heap=signed?HEAP32:HEAPU32;return this["fromWireType"](heap[pointer>>2])};default:throw new TypeError("Unknown integer type: "+name)}}function __embind_register_enum(rawType,name,size,isSigned){var shift=getShiftFromSize(size);name=readLatin1String(name);function ctor(){}ctor.values={};registerType(rawType,{name:name,constructor:ctor,"fromWireType":function(c){return this.constructor.values[c]},"toWireType":function(destructors,c){return c.value},"argPackAdvance":8,"readValueFromPointer":enumReadValueFromPointer(name,shift,isSigned),destructorFunction:null});exposePublicSymbol(name,ctor)}function requireRegisteredType(rawType,humanName){var impl=registeredTypes[rawType];if(undefined===impl){throwBindingError(humanName+" has unknown type "+getTypeName(rawType))}return impl}function __embind_register_enum_value(rawEnumType,name,enumValue){var enumType=requireRegisteredType(rawEnumType,"enum");name=readLatin1String(name);var Enum=enumType.constructor;var Value=Object.create(enumType.constructor.prototype,{value:{value:enumValue},constructor:{value:createNamedFunction(enumType.name+"_"+name,function(){})}});Enum.values[enumValue]=Value;Enum[name]=Value}function 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 floatReadValueFromPointer(name,shift){switch(shift){case 2:return function(pointer){return this["fromWireType"](HEAPF32[pointer>>2])};case 3:return function(pointer){return this["fromWireType"](HEAPF64[pointer>>3])};default:throw new TypeError("Unknown float type: "+name)}}function __embind_register_float(rawType,name,size){var shift=getShiftFromSize(size);name=readLatin1String(name);registerType(rawType,{name:name,"fromWireType":function(value){return value},"toWireType":function(destructors,value){return value},"argPackAdvance":8,"readValueFromPointer":floatReadValueFromPointer(name,shift),destructorFunction:null})}function integerReadValueFromPointer(name,shift,signed){switch(shift){case 0:return signed?function readS8FromPointer(pointer){return HEAP8[pointer]}:function readU8FromPointer(pointer){return HEAPU8[pointer]};case 1:return signed?function readS16FromPointer(pointer){return HEAP16[pointer>>1]}:function readU16FromPointer(pointer){return HEAPU16[pointer>>1]};case 2:return signed?function readS32FromPointer(pointer){return HEAP32[pointer>>2]}:function readU32FromPointer(pointer){return HEAPU32[pointer>>2]};default:throw new TypeError("Unknown integer type: "+name)}}function __embind_register_integer(primitiveType,name,size,minRange,maxRange){name=readLatin1String(name);if(maxRange===-1){maxRange=4294967295}var shift=getShiftFromSize(size);var fromWireType=value=>value;if(minRange===0){var bitshift=32-8*size;fromWireType=value=>value<>>bitshift}var isUnsignedType=name.includes("unsigned");var checkAssertions=(value,toTypeName)=>{};var toWireType;if(isUnsignedType){toWireType=function(destructors,value){checkAssertions(value,this.name);return value>>>0}}else{toWireType=function(destructors,value){checkAssertions(value,this.name);return value}}registerType(primitiveType,{name:name,"fromWireType":fromWireType,"toWireType":toWireType,"argPackAdvance":8,"readValueFromPointer":integerReadValueFromPointer(name,shift,minRange!==0),destructorFunction:null})}function __embind_register_memory_view(rawType,dataTypeIndex,name){var typeMapping=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];var TA=typeMapping[dataTypeIndex];function decodeMemoryView(handle){handle=handle>>2;var heap=HEAPU32;var size=heap[handle];var data=heap[handle+1];return new TA(heap.buffer,data,size)}name=readLatin1String(name);registerType(rawType,{name:name,"fromWireType":decodeMemoryView,"argPackAdvance":8,"readValueFromPointer":decodeMemoryView},{ignoreDuplicateRegistrations:true})}function __embind_register_std_string(rawType,name){name=readLatin1String(name);var stdStringIsUTF8=name==="std::string";registerType(rawType,{name:name,"fromWireType":function(value){var length=HEAPU32[value>>2];var payload=value+4;var str;if(stdStringIsUTF8){var decodeStartPtr=payload;for(var i=0;i<=length;++i){var currentBytePtr=payload+i;if(i==length||HEAPU8[currentBytePtr]==0){var maxRead=currentBytePtr-decodeStartPtr;var stringSegment=UTF8ToString(decodeStartPtr,maxRead);if(str===undefined){str=stringSegment}else{str+=String.fromCharCode(0);str+=stringSegment}decodeStartPtr=currentBytePtr+1}}}else{var a=new Array(length);for(var i=0;i>2]=length;if(stdStringIsUTF8&&valueIsOfTypeString){stringToUTF8(value,ptr,length+1)}else{if(valueIsOfTypeString){for(var i=0;i255){_free(ptr);throwBindingError("String has UTF-16 code units that do not fit in 8 bits")}HEAPU8[ptr+i]=charCode}}else{for(var i=0;i>1;var maxIdx=idx+maxBytesToRead/2;while(!(idx>=maxIdx)&&HEAPU16[idx])++idx;endPtr=idx<<1;if(endPtr-ptr>32&&UTF16Decoder)return UTF16Decoder.decode(HEAPU8.subarray(ptr,endPtr));var str="";for(var i=0;!(i>=maxBytesToRead/2);++i){var codeUnit=HEAP16[ptr+i*2>>1];if(codeUnit==0)break;str+=String.fromCharCode(codeUnit)}return str}function stringToUTF16(str,outPtr,maxBytesToWrite){if(maxBytesToWrite===undefined){maxBytesToWrite=2147483647}if(maxBytesToWrite<2)return 0;maxBytesToWrite-=2;var startPtr=outPtr;var numCharsToWrite=maxBytesToWrite>1]=codeUnit;outPtr+=2}HEAP16[outPtr>>1]=0;return outPtr-startPtr}function lengthBytesUTF16(str){return str.length*2}function UTF32ToString(ptr,maxBytesToRead){var i=0;var str="";while(!(i>=maxBytesToRead/4)){var utf32=HEAP32[ptr+i*4>>2];if(utf32==0)break;++i;if(utf32>=65536){var ch=utf32-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}else{str+=String.fromCharCode(utf32)}}return str}function stringToUTF32(str,outPtr,maxBytesToWrite){if(maxBytesToWrite===undefined){maxBytesToWrite=2147483647}if(maxBytesToWrite<4)return 0;var startPtr=outPtr;var endPtr=startPtr+maxBytesToWrite-4;for(var i=0;i=55296&&codeUnit<=57343){var trailSurrogate=str.charCodeAt(++i);codeUnit=65536+((codeUnit&1023)<<10)|trailSurrogate&1023}HEAP32[outPtr>>2]=codeUnit;outPtr+=4;if(outPtr+4>endPtr)break}HEAP32[outPtr>>2]=0;return outPtr-startPtr}function lengthBytesUTF32(str){var len=0;for(var i=0;i=55296&&codeUnit<=57343)++i;len+=4}return len}function __embind_register_std_wstring(rawType,charSize,name){name=readLatin1String(name);var decodeString,encodeString,getHeap,lengthBytesUTF,shift;if(charSize===2){decodeString=UTF16ToString;encodeString=stringToUTF16;lengthBytesUTF=lengthBytesUTF16;getHeap=()=>HEAPU16;shift=1}else if(charSize===4){decodeString=UTF32ToString;encodeString=stringToUTF32;lengthBytesUTF=lengthBytesUTF32;getHeap=()=>HEAPU32;shift=2}registerType(rawType,{name:name,"fromWireType":function(value){var length=HEAPU32[value>>2];var HEAP=getHeap();var str;var decodeStartPtr=value+4;for(var i=0;i<=length;++i){var currentBytePtr=value+4+i*charSize;if(i==length||HEAP[currentBytePtr>>shift]==0){var maxReadBytes=currentBytePtr-decodeStartPtr;var stringSegment=decodeString(decodeStartPtr,maxReadBytes);if(str===undefined){str=stringSegment}else{str+=String.fromCharCode(0);str+=stringSegment}decodeStartPtr=currentBytePtr+charSize}}_free(value);return str},"toWireType":function(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]=length>>shift;encodeString(value,ptr+4,length+charSize);if(destructors!==null){destructors.push(_free,ptr)}return ptr},"argPackAdvance":8,"readValueFromPointer":simpleReadValueFromPointer,destructorFunction:function(ptr){_free(ptr)}})}function __embind_register_value_array(rawType,name,constructorSignature,rawConstructor,destructorSignature,rawDestructor){tupleRegistrations[rawType]={name:readLatin1String(name),rawConstructor:embind__requireFunction(constructorSignature,rawConstructor),rawDestructor:embind__requireFunction(destructorSignature,rawDestructor),elements:[]}}function __embind_register_value_array_element(rawTupleType,getterReturnType,getterSignature,getter,getterContext,setterArgumentType,setterSignature,setter,setterContext){tupleRegistrations[rawTupleType].elements.push({getterReturnType:getterReturnType,getter:embind__requireFunction(getterSignature,getter),getterContext:getterContext,setterArgumentType:setterArgumentType,setter:embind__requireFunction(setterSignature,setter),setterContext:setterContext})}function __embind_register_value_object(rawType,name,constructorSignature,rawConstructor,destructorSignature,rawDestructor){structRegistrations[rawType]={name:readLatin1String(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){structRegistrations[structType].fields.push({fieldName:readLatin1String(fieldName),getterReturnType:getterReturnType,getter:embind__requireFunction(getterSignature,getter),getterContext:getterContext,setterArgumentType:setterArgumentType,setter:embind__requireFunction(setterSignature,setter),setterContext:setterContext})}function __embind_register_void(rawType,name){name=readLatin1String(name);registerType(rawType,{isVoid:true,name:name,"argPackAdvance":0,"fromWireType":function(){return undefined},"toWireType":function(destructors,o){return undefined}})}function __emval_as(handle,returnType,destructorsRef){handle=Emval.toValue(handle);returnType=requireRegisteredType(returnType,"emval::as");var destructors=[];var rd=Emval.toHandle(destructors);HEAPU32[destructorsRef>>2]=rd;return returnType["toWireType"](destructors,handle)}function emval_allocateDestructors(destructorsRef){var destructors=[];HEAPU32[destructorsRef>>2]=Emval.toHandle(destructors);return destructors}var emval_symbols={};function getStringOrSymbol(address){var symbol=emval_symbols[address];if(symbol===undefined){return readLatin1String(address)}return symbol}var emval_methodCallers=[];function __emval_call_method(caller,handle,methodName,destructorsRef,args){caller=emval_methodCallers[caller];handle=Emval.toValue(handle);methodName=getStringOrSymbol(methodName);return caller(handle,methodName,emval_allocateDestructors(destructorsRef),args)}function __emval_call_void_method(caller,handle,methodName,args){caller=emval_methodCallers[caller];handle=Emval.toValue(handle);methodName=getStringOrSymbol(methodName);caller(handle,methodName,null,args)}function __emval_equals(first,second){first=Emval.toValue(first);second=Emval.toValue(second);return first==second}function emval_get_global(){if(typeof globalThis=="object"){return globalThis}return function(){return Function}()("return this")()}function __emval_get_global(name){if(name===0){return Emval.toHandle(emval_get_global())}else{name=getStringOrSymbol(name);return Emval.toHandle(emval_get_global()[name])}}function emval_addMethodCaller(caller){var id=emval_methodCallers.length;emval_methodCallers.push(caller);return id}function emval_lookupTypes(argCount,argTypes){var a=new Array(argCount);for(var i=0;i>2],"parameter "+i)}return a}var emval_registeredMethods=[];function __emval_get_method_caller(argCount,argTypes){var types=emval_lookupTypes(argCount,argTypes);var retType=types[0];var signatureName=retType.name+"_$"+types.slice(1).map(function(t){return t.name}).join("_")+"$";var returnId=emval_registeredMethods[signatureName];if(returnId!==undefined){return returnId}var params=["retType"];var args=[retType];var argsList="";for(var i=0;i4){emval_handle_array[handle].refcount+=1}}function __emval_instanceof(object,constructor){object=Emval.toValue(object);constructor=Emval.toValue(constructor);return object instanceof constructor}function __emval_is_number(handle){handle=Emval.toValue(handle);return typeof handle=="number"}function __emval_is_string(handle){handle=Emval.toValue(handle);return typeof handle=="string"}function craftEmvalAllocator(argCount){var argsList="";for(var i=0;iHEAPU32;var functionBody="return function emval_allocator_"+argCount+"(constructor, argTypes, args) {\n"+" var HEAPU32 = getMemory();\n";for(var i=0;i>2)], 'parameter "+i+"');\n"+"var arg"+i+" = argType"+i+".readValueFromPointer(args);\n"+"args += argType"+i+"['argPackAdvance'];\n"+"argTypes += 4;\n"}functionBody+="var obj = new constructor("+argsList+");\n"+"return valueToHandle(obj);\n"+"}\n";return new Function("requireRegisteredType","Module","valueToHandle","getMemory",functionBody)(requireRegisteredType,Module,Emval.toHandle,getMemory)}var emval_newers={};function __emval_new(handle,argCount,argTypes,args){handle=Emval.toValue(handle);var newer=emval_newers[argCount];if(!newer){newer=craftEmvalAllocator(argCount);emval_newers[argCount]=newer}return newer(handle,argTypes,args)}function __emval_new_array(){return Emval.toHandle([])}function __emval_new_cstring(v){return Emval.toHandle(getStringOrSymbol(v))}function __emval_new_object(){return Emval.toHandle({})}function __emval_run_destructors(handle){var destructors=Emval.toValue(handle);runDestructors(destructors);__emval_decref(handle)}function __emval_set_property(handle,key,value){handle=Emval.toValue(handle);key=Emval.toValue(key);value=Emval.toValue(value);handle[key]=value}function __emval_take_value(type,arg){type=requireRegisteredType(type,"_emval_take_value");var v=type["readValueFromPointer"](arg);return Emval.toHandle(v)}function readI53FromI64(ptr){return HEAPU32[ptr>>2]+HEAP32[ptr+4>>2]*4294967296}function __gmtime_js(time,tmPtr){var date=new Date(readI53FromI64(time)*1e3);HEAP32[tmPtr>>2]=date.getUTCSeconds();HEAP32[tmPtr+4>>2]=date.getUTCMinutes();HEAP32[tmPtr+8>>2]=date.getUTCHours();HEAP32[tmPtr+12>>2]=date.getUTCDate();HEAP32[tmPtr+16>>2]=date.getUTCMonth();HEAP32[tmPtr+20>>2]=date.getUTCFullYear()-1900;HEAP32[tmPtr+24>>2]=date.getUTCDay();var start=Date.UTC(date.getUTCFullYear(),0,1,0,0,0,0);var yday=(date.getTime()-start)/(1e3*60*60*24)|0;HEAP32[tmPtr+28>>2]=yday}function __isLeapYear(year){return 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];function __yday_from_date(date){var isLeapYear=__isLeapYear(date.getFullYear());var monthDaysCumulative=isLeapYear?__MONTH_DAYS_LEAP_CUMULATIVE:__MONTH_DAYS_REGULAR_CUMULATIVE;var yday=monthDaysCumulative[date.getMonth()]+date.getDate()-1;return yday}function __localtime_js(time,tmPtr){var date=new Date(readI53FromI64(time)*1e3);HEAP32[tmPtr>>2]=date.getSeconds();HEAP32[tmPtr+4>>2]=date.getMinutes();HEAP32[tmPtr+8>>2]=date.getHours();HEAP32[tmPtr+12>>2]=date.getDate();HEAP32[tmPtr+16>>2]=date.getMonth();HEAP32[tmPtr+20>>2]=date.getFullYear()-1900;HEAP32[tmPtr+24>>2]=date.getDay();var yday=__yday_from_date(date)|0;HEAP32[tmPtr+28>>2]=yday;HEAP32[tmPtr+36>>2]=-(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]=dst}function __mktime_js(tmPtr){var date=new Date(HEAP32[tmPtr+20>>2]+1900,HEAP32[tmPtr+16>>2],HEAP32[tmPtr+12>>2],HEAP32[tmPtr+8>>2],HEAP32[tmPtr+4>>2],HEAP32[tmPtr>>2],0);var dst=HEAP32[tmPtr+32>>2];var guessedOffset=date.getTimezoneOffset();var start=new Date(date.getFullYear(),0,1);var summerOffset=new Date(date.getFullYear(),6,1).getTimezoneOffset();var winterOffset=start.getTimezoneOffset();var dstOffset=Math.min(winterOffset,summerOffset);if(dst<0){HEAP32[tmPtr+32>>2]=Number(summerOffset!=winterOffset&&dstOffset==guessedOffset)}else if(dst>0!=(dstOffset==guessedOffset)){var nonDstOffset=Math.max(winterOffset,summerOffset);var trueOffset=dst>0?dstOffset:nonDstOffset;date.setTime(date.getTime()+(trueOffset-guessedOffset)*6e4)}HEAP32[tmPtr+24>>2]=date.getDay();var yday=__yday_from_date(date)|0;HEAP32[tmPtr+28>>2]=yday;HEAP32[tmPtr>>2]=date.getSeconds();HEAP32[tmPtr+4>>2]=date.getMinutes();HEAP32[tmPtr+8>>2]=date.getHours();HEAP32[tmPtr+12>>2]=date.getDate();HEAP32[tmPtr+16>>2]=date.getMonth();HEAP32[tmPtr+20>>2]=date.getYear();return date.getTime()/1e3|0}function allocateUTF8(str){var size=lengthBytesUTF8(str)+1;var ret=_malloc(size);if(ret)stringToUTF8Array(str,HEAP8,ret,size);return ret}function __tzset_js(timezone,daylight,tzname){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]=stdTimezoneOffset*60;HEAP32[daylight>>2]=Number(winterOffset!=summerOffset);function extractZone(date){var match=date.toTimeString().match(/\(([A-Za-z ]+)\)$/);return match?match[1]:"GMT"}var winterName=extractZone(winter);var summerName=extractZone(summer);var winterNamePtr=allocateUTF8(winterName);var summerNamePtr=allocateUTF8(summerName);if(summerOffset>2]=winterNamePtr;HEAPU32[tzname+4>>2]=summerNamePtr}else{HEAPU32[tzname>>2]=summerNamePtr;HEAPU32[tzname+4>>2]=winterNamePtr}}function _abort(){abort("")}function _emscripten_date_now(){return Date.now()}function getHeapMax(){return 2147483648}var _emscripten_get_now;if(ENVIRONMENT_IS_NODE){_emscripten_get_now=()=>{var t=process["hrtime"]();return t[0]*1e3+t[1]/1e6}}else _emscripten_get_now=()=>performance.now();function emscripten_realloc_buffer(size){var b=wasmMemory.buffer;try{wasmMemory.grow(size-b.byteLength+65535>>>16);updateMemoryViews();return 1}catch(e){}}function _emscripten_resize_heap(requestedSize){var oldSize=HEAPU8.length;requestedSize=requestedSize>>>0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}let alignUp=(x,multiple)=>x+(multiple-x%multiple)%multiple;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,alignUp(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=emscripten_realloc_buffer(newSize);if(replacement){return true}}return false}var ENV={};function getExecutableName(){return thisProgram||"./this.program"}function getEnvStrings(){if(!getEnvStrings.strings){var lang=(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"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 writeAsciiToMemory(str,buffer,dontAddNull){for(var i=0;i>0]=str.charCodeAt(i)}if(!dontAddNull)HEAP8[buffer>>0]=0}function _environ_get(__environ,environ_buf){var bufSize=0;getEnvStrings().forEach(function(string,i){var ptr=environ_buf+bufSize;HEAPU32[__environ+i*4>>2]=ptr;writeAsciiToMemory(string,ptr);bufSize+=string.length+1});return 0}function _environ_sizes_get(penviron_count,penviron_buf_size){var strings=getEnvStrings();HEAPU32[penviron_count>>2]=strings.length;var bufSize=0;strings.forEach(function(string){bufSize+=string.length+1});HEAPU32[penviron_buf_size>>2]=bufSize;return 0}function _fd_close(fd){try{var stream=SYSCALLS.getStreamFromFD(fd);FS.close(stream);return 0}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return e.errno}}function doReadv(stream,iov,iovcnt,offset){var ret=0;for(var i=0;i>2];var len=HEAPU32[iov+4>>2];iov+=8;var curr=FS.read(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr;if(curr>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return e.errno}}function _fd_seek(fd,offset_low,offset_high,whence,newOffset){try{var offset=convertI32PairToI53Checked(offset_low,offset_high);if(isNaN(offset))return 61;var stream=SYSCALLS.getStreamFromFD(fd);FS.llseek(stream,offset,whence);tempI64=[stream.position>>>0,(tempDouble=stream.position,+Math.abs(tempDouble)>=1?tempDouble>0?(Math.min(+Math.floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[newOffset>>2]=tempI64[0],HEAP32[newOffset+4>>2]=tempI64[1];if(stream.getdents&&offset===0&&whence===0)stream.getdents=null;return 0}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return e.errno}}function doWritev(stream,iov,iovcnt,offset){var ret=0;for(var i=0;i>2];var len=HEAPU32[iov+4>>2];iov+=8;var curr=FS.write(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr;if(typeof offset!=="undefined"){offset+=curr}}return ret}function _fd_write(fd,iov,iovcnt,pnum){try{var stream=SYSCALLS.getStreamFromFD(fd);var num=doWritev(stream,iov,iovcnt);HEAPU32[pnum>>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return e.errno}}var FSNode=function(parent,name,mode,rdev){if(!parent){parent=this}this.parent=parent;this.mount=parent.mount;this.mounted=null;this.id=FS.nextInode++;this.name=name;this.mode=mode;this.node_ops={};this.stream_ops={};this.rdev=rdev};var readMode=292|73;var writeMode=146;Object.defineProperties(FSNode.prototype,{read:{get:function(){return(this.mode&readMode)===readMode},set:function(val){val?this.mode|=readMode:this.mode&=~readMode}},write:{get:function(){return(this.mode&writeMode)===writeMode},set:function(val){val?this.mode|=writeMode:this.mode&=~writeMode}},isFolder:{get:function(){return FS.isDir(this.mode)}},isDevice:{get:function(){return FS.isChrdev(this.mode)}}});FS.FSNode=FSNode;FS.staticInit();InternalError=Module["InternalError"]=extendError(Error,"InternalError");embind_init_charCodes();BindingError=Module["BindingError"]=extendError(Error,"BindingError");init_ClassHandle();init_embind();init_RegisteredPointer();UnboundTypeError=Module["UnboundTypeError"]=extendError(Error,"UnboundTypeError");init_emval();var asmLibraryArg={"v":___cxa_throw,"U":___syscall_connect,"ea":___syscall_faccessat,"o":___syscall_fcntl64,"Z":___syscall_fstat64,"S":___syscall_ftruncate64,"K":___syscall_ioctl,"W":___syscall_lstat64,"X":___syscall_newfstatat,"G":___syscall_openat,"F":___syscall_socket,"Y":___syscall_stat64,"r":__embind_finalize_value_array,"ka":__embind_finalize_value_object,"T":__embind_register_bigint,"ga":__embind_register_bool,"e":__embind_register_class,"f":__embind_register_class_class_function,"g":__embind_register_class_constructor,"b":__embind_register_class_function,"a":__embind_register_class_property,"fa":__embind_register_emval,"i":__embind_register_enum,"d":__embind_register_enum_value,"M":__embind_register_float,"p":__embind_register_integer,"l":__embind_register_memory_view,"L":__embind_register_std_string,"B":__embind_register_std_wstring,"q":__embind_register_value_array,"ia":__embind_register_value_array_element,"ja":__embind_register_value_object,"N":__embind_register_value_object_field,"ha":__embind_register_void,"t":__emval_as,"la":__emval_call_method,"P":__emval_call_void_method,"c":__emval_decref,"Q":__emval_equals,"y":__emval_get_global,"C":__emval_get_method_caller,"E":__emval_get_module_property,"w":__emval_get_property,"m":__emval_incref,"D":__emval_instanceof,"na":__emval_is_number,"ma":__emval_is_string,"O":__emval_new,"n":__emval_new_array,"u":__emval_new_cstring,"k":__emval_new_object,"s":__emval_run_destructors,"j":__emval_set_property,"h":__emval_take_value,"aa":__gmtime_js,"ba":__localtime_js,"ca":__mktime_js,"da":__tzset_js,"z":_abort,"I":_emscripten_date_now,"H":_emscripten_get_now,"V":_emscripten_resize_heap,"_":_environ_get,"$":_environ_sizes_get,"x":_fd_close,"J":_fd_read,"R":_fd_seek,"A":_fd_write};var asm=createWasm();var ___wasm_call_ctors=Module["___wasm_call_ctors"]=function(){return(___wasm_call_ctors=Module["___wasm_call_ctors"]=Module["asm"]["pa"]).apply(null,arguments)};var _malloc=Module["_malloc"]=function(){return(_malloc=Module["_malloc"]=Module["asm"]["ra"]).apply(null,arguments)};var _free=Module["_free"]=function(){return(_free=Module["_free"]=Module["asm"]["sa"]).apply(null,arguments)};var ___errno_location=Module["___errno_location"]=function(){return(___errno_location=Module["___errno_location"]=Module["asm"]["ta"]).apply(null,arguments)};var ___getTypeName=Module["___getTypeName"]=function(){return(___getTypeName=Module["___getTypeName"]=Module["asm"]["ua"]).apply(null,arguments)};var __embind_initialize_bindings=Module["__embind_initialize_bindings"]=function(){return(__embind_initialize_bindings=Module["__embind_initialize_bindings"]=Module["asm"]["va"]).apply(null,arguments)};var _htons=Module["_htons"]=function(){return(_htons=Module["_htons"]=Module["asm"]["wa"]).apply(null,arguments)};var _ntohs=Module["_ntohs"]=function(){return(_ntohs=Module["_ntohs"]=Module["asm"]["xa"]).apply(null,arguments)};var ___cxa_is_pointer_type=Module["___cxa_is_pointer_type"]=function(){return(___cxa_is_pointer_type=Module["___cxa_is_pointer_type"]=Module["asm"]["ya"]).apply(null,arguments)};var dynCall_ji=Module["dynCall_ji"]=function(){return(dynCall_ji=Module["dynCall_ji"]=Module["asm"]["za"]).apply(null,arguments)};var dynCall_vij=Module["dynCall_vij"]=function(){return(dynCall_vij=Module["dynCall_vij"]=Module["asm"]["Aa"]).apply(null,arguments)};var dynCall_jiji=Module["dynCall_jiji"]=function(){return(dynCall_jiji=Module["dynCall_jiji"]=Module["asm"]["Ba"]).apply(null,arguments)};var calledRun;dependenciesFulfilled=function runCaller(){if(!calledRun)run();if(!calledRun)dependenciesFulfilled=runCaller};function run(args){args=args||arguments_;if(runDependencies>0){return}preRun();if(runDependencies>0){return}function doRun(){if(calledRun)return;calledRun=true;Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve(Module);if(Module["onRuntimeInitialized"])Module["onRuntimeInitialized"]();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(function(){setTimeout(function(){Module["setStatus"]("")},1);doRun()},1)}else{doRun()}}if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].pop()()}}run(); - - - return rhino3dm.ready -} -); -})(); -export default rhino3dm; \ No newline at end of file diff --git a/public/assets/lib/vendor/three/rhino3dm/rhino3dm.module.min.js b/public/assets/lib/vendor/three/rhino3dm/rhino3dm.module.min.js deleted file mode 100644 index 43b0bef7..00000000 --- a/public/assets/lib/vendor/three/rhino3dm/rhino3dm.module.min.js +++ /dev/null @@ -1 +0,0 @@ -var rhino3dm=(()=>{var e=import.meta.url;return async function(r){var t,n,o=r||{},a=void 0!==o?o:{};a.ready=new Promise(function(e,r){t=e,n=r});var i,s,u,c=Object.assign({},a),l=[],f="./this.program",d="object"==typeof window,p="function"==typeof importScripts,h="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,m="";if(h){const{createRequire:e}=await import("module");var v=e(import.meta.url),w=v("fs"),y=v("path");m=p?y.dirname(m)+"/":v("url").fileURLToPath(new URL("./",import.meta.url)),i=((e,r)=>(e=oe(e)?new URL(e):y.normalize(e),w.readFileSync(e,r?void 0:"utf8"))),u=(e=>{var r=i(e,!0);return r.buffer||(r=new Uint8Array(r)),r}),s=((e,r,t)=>{e=oe(e)?new URL(e):y.normalize(e),w.readFile(e,function(e,n){e?t(e):r(n.buffer)})}),process.argv.length>1&&(f=process.argv[1].replace(/\\/g,"/")),l=process.argv.slice(2),process.on("uncaughtException",function(e){if(!(e instanceof ie))throw e}),process.on("unhandledRejection",function(e){throw e}),(e,r)=>{if(T)throw process.exitCode=e,r;!function(e){if(e instanceof ie)return;E("exiting due to exception: "+e)}(r),process.exit(e)},a.inspect=function(){return"[Emscripten Module object]"}}else(d||p)&&(p?m=self.location.href:"undefined"!=typeof document&&document.currentScript&&(m=document.currentScript.src),e&&(m=e),m=0!==m.indexOf("blob:")?m.substr(0,m.replace(/[?#].*/,"").lastIndexOf("/")+1):"",i=(e=>{var r=new XMLHttpRequest;return r.open("GET",e,!1),r.send(null),r.responseText}),p&&(u=(e=>{var r=new XMLHttpRequest;return r.open("GET",e,!1),r.responseType="arraybuffer",r.send(null),new Uint8Array(r.response)})),s=((e,r,t)=>{var n=new XMLHttpRequest;n.open("GET",e,!0),n.responseType="arraybuffer",n.onload=(()=>{200==n.status||0==n.status&&n.response?r(n.response):t()}),n.onerror=t,n.send(null)}),e=>document.title=e);var g=a.print||console.log.bind(console),E=a.printErr||console.warn.bind(console);Object.assign(a,c),c=null,a.arguments&&(l=a.arguments),a.thisProgram&&(f=a.thisProgram),a.quit&&a.quit;var b,_=4;a.wasmBinary&&(b=a.wasmBinary);var k,T=a.noExitRuntime||!0;"object"!=typeof WebAssembly&&Z("no native wasm support detected");var P=!1;function C(e,r){e||Z(r)}var S,D,A,F,$,M,O,j,x="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function R(e,r,t){for(var n=r+t,o=r;e[o]&&!(o>=n);)++o;if(o-r>16&&e.buffer&&x)return x.decode(e.subarray(r,o));for(var a="";r>10,56320|1023&c)}}else a+=String.fromCharCode((31&i)<<6|s)}else a+=String.fromCharCode(i)}return a}function N(e,r){return e?R(D,e,r):""}function z(e,r,t,n){if(!(n>0))return 0;for(var o=t,a=t+n-1,i=0;i=55296&&s<=57343)s=65536+((1023&s)<<10)|1023&e.charCodeAt(++i);if(s<=127){if(t>=a)break;r[t++]=s}else if(s<=2047){if(t+1>=a)break;r[t++]=192|s>>6,r[t++]=128|63&s}else if(s<=65535){if(t+2>=a)break;r[t++]=224|s>>12,r[t++]=128|s>>6&63,r[t++]=128|63&s}else{if(t+3>=a)break;r[t++]=240|s>>18,r[t++]=128|s>>12&63,r[t++]=128|s>>6&63,r[t++]=128|63&s}}return r[t]=0,t-o}function U(e){for(var r=0,t=0;t=55296&&n<=57343?(r+=4,++t):r+=3}return r}function W(){var e=k.buffer;a.HEAP8=S=new Int8Array(e),a.HEAP16=A=new Int16Array(e),a.HEAP32=$=new Int32Array(e),a.HEAPU8=D=new Uint8Array(e),a.HEAPU16=F=new Uint16Array(e),a.HEAPU32=M=new Uint32Array(e),a.HEAPF32=O=new Float32Array(e),a.HEAPF64=j=new Float64Array(e)}a.INITIAL_MEMORY;var B,L=[],I=[],H=[];var V=0,q=null,G=null;function X(e){return e}function Y(e){V++,a.monitorRunDependencies&&a.monitorRunDependencies(V)}function K(e){if(V--,a.monitorRunDependencies&&a.monitorRunDependencies(V),0==V&&(null!==q&&(clearInterval(q),q=null),G)){var r=G;G=null,r()}}function Z(e){a.onAbort&&a.onAbort(e),E(e="Aborted("+e+")"),P=!0,1,e+=". Build with -sASSERTIONS for more info.";var r=new WebAssembly.RuntimeError(e);throw n(r),r}var J,Q,ee,re,te="data:application/octet-stream;base64,";function ne(e){return e.startsWith(te)}function oe(e){return e.startsWith("file://")}function ae(e){try{if(e==J&&b)return new Uint8Array(b);if(u)return u(e);throw"both async and sync fetching of the wasm failed"}catch(e){Z(e)}}function ie(e){this.name="ExitStatus",this.message="Program terminated with exit("+e+")",this.status=e}function se(e){for(;e.length>0;)e.shift()(a)}a.locateFile?ne(J="rhino3dm.wasm")||(Q=J,J=a.locateFile?a.locateFile(Q,m):m+Q):J=new URL("rhino3dm.wasm",import.meta.url).href;var ue={isAbs:e=>"/"===e.charAt(0),splitPath:e=>{return/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(e).slice(1)},normalizeArray:(e,r)=>{for(var t=0,n=e.length-1;n>=0;n--){var o=e[n];"."===o?e.splice(n,1):".."===o?(e.splice(n,1),t++):t&&(e.splice(n,1),t--)}if(r)for(;t;t--)e.unshift("..");return e},normalize:e=>{var r=ue.isAbs(e),t="/"===e.substr(-1);return(e=ue.normalizeArray(e.split("/").filter(e=>!!e),!r).join("/"))||r||(e="."),e&&t&&(e+="/"),(r?"/":"")+e},dirname:e=>{var r=ue.splitPath(e),t=r[0],n=r[1];return t||n?(n&&(n=n.substr(0,n.length-1)),t+n):"."},basename:e=>{if("/"===e)return"/";var r=(e=(e=ue.normalize(e)).replace(/\/$/,"")).lastIndexOf("/");return-1===r?e:e.substr(r+1)},join:function(){var e=Array.prototype.slice.call(arguments);return ue.normalize(e.join("/"))},join2:(e,r)=>ue.normalize(e+"/"+r)},ce={resolve:function(){for(var e="",r=!1,t=arguments.length-1;t>=-1&&!r;t--){var n=t>=0?arguments[t]:he.cwd();if("string"!=typeof n)throw new TypeError("Arguments to path.resolve must be strings");if(!n)return"";e=n+"/"+e,r=ue.isAbs(n)}return(r?"/":"")+(e=ue.normalizeArray(e.split("/").filter(e=>!!e),!r).join("/"))||"."},relative:(e,r)=>{function t(e){for(var r=0;r=0&&""===e[t];t--);return r>t?[]:e.slice(r,t-r+1)}e=ce.resolve(e).substr(1),r=ce.resolve(r).substr(1);for(var n=t(e.split("/")),o=t(r.split("/")),a=Math.min(n.length,o.length),i=a,s=0;s0?t:U(e)+1,o=new Array(n),a=z(e,o,0,o.length);return r&&(o.length=a),o}var fe={ttys:[],init:function(){},shutdown:function(){},register:function(e,r){fe.ttys[e]={input:[],output:[],ops:r},he.registerDevice(e,fe.stream_ops)},stream_ops:{open:function(e){var r=fe.ttys[e.node.rdev];if(!r)throw new he.ErrnoError(43);e.tty=r,e.seekable=!1},close:function(e){e.tty.ops.fsync(e.tty)},fsync:function(e){e.tty.ops.fsync(e.tty)},read:function(e,r,t,n,o){if(!e.tty||!e.tty.ops.get_char)throw new he.ErrnoError(60);for(var a=0,i=0;i0?t.slice(0,n).toString("utf-8"):null}else"undefined"!=typeof window&&"function"==typeof window.prompt?null!==(r=window.prompt("Input: "))&&(r+="\n"):"function"==typeof readline&&null!==(r=readline())&&(r+="\n");if(!r)return null;e.input=le(r,!0)}return e.input.shift()},put_char:function(e,r){null===r||10===r?(g(R(e.output,0)),e.output=[]):0!=r&&e.output.push(r)},fsync:function(e){e.output&&e.output.length>0&&(g(R(e.output,0)),e.output=[])}},default_tty1_ops:{put_char:function(e,r){null===r||10===r?(E(R(e.output,0)),e.output=[]):0!=r&&e.output.push(r)},fsync:function(e){e.output&&e.output.length>0&&(E(R(e.output,0)),e.output=[])}}};function de(e){Z()}var pe={ops_table:null,mount:function(e){return pe.createNode(null,"/",16895,0)},createNode:function(e,r,t,n){if(he.isBlkdev(t)||he.isFIFO(t))throw new he.ErrnoError(63);pe.ops_table||(pe.ops_table={dir:{node:{getattr:pe.node_ops.getattr,setattr:pe.node_ops.setattr,lookup:pe.node_ops.lookup,mknod:pe.node_ops.mknod,rename:pe.node_ops.rename,unlink:pe.node_ops.unlink,rmdir:pe.node_ops.rmdir,readdir:pe.node_ops.readdir,symlink:pe.node_ops.symlink},stream:{llseek:pe.stream_ops.llseek}},file:{node:{getattr:pe.node_ops.getattr,setattr:pe.node_ops.setattr},stream:{llseek:pe.stream_ops.llseek,read:pe.stream_ops.read,write:pe.stream_ops.write,allocate:pe.stream_ops.allocate,mmap:pe.stream_ops.mmap,msync:pe.stream_ops.msync}},link:{node:{getattr:pe.node_ops.getattr,setattr:pe.node_ops.setattr,readlink:pe.node_ops.readlink},stream:{}},chrdev:{node:{getattr:pe.node_ops.getattr,setattr:pe.node_ops.setattr},stream:he.chrdev_stream_ops}});var o=he.createNode(e,r,t,n);return he.isDir(o.mode)?(o.node_ops=pe.ops_table.dir.node,o.stream_ops=pe.ops_table.dir.stream,o.contents={}):he.isFile(o.mode)?(o.node_ops=pe.ops_table.file.node,o.stream_ops=pe.ops_table.file.stream,o.usedBytes=0,o.contents=null):he.isLink(o.mode)?(o.node_ops=pe.ops_table.link.node,o.stream_ops=pe.ops_table.link.stream):he.isChrdev(o.mode)&&(o.node_ops=pe.ops_table.chrdev.node,o.stream_ops=pe.ops_table.chrdev.stream),o.timestamp=Date.now(),e&&(e.contents[r]=o,e.timestamp=o.timestamp),o},getFileDataAsTypedArray:function(e){return e.contents?e.contents.subarray?e.contents.subarray(0,e.usedBytes):new Uint8Array(e.contents):new Uint8Array(0)},expandFileStorage:function(e,r){var t=e.contents?e.contents.length:0;if(!(t>=r)){r=Math.max(r,t*(t<1048576?2:1.125)>>>0),0!=t&&(r=Math.max(r,256));var n=e.contents;e.contents=new Uint8Array(r),e.usedBytes>0&&e.contents.set(n.subarray(0,e.usedBytes),0)}},resizeFileStorage:function(e,r){if(e.usedBytes!=r)if(0==r)e.contents=null,e.usedBytes=0;else{var t=e.contents;e.contents=new Uint8Array(r),t&&e.contents.set(t.subarray(0,Math.min(r,e.usedBytes))),e.usedBytes=r}},node_ops:{getattr:function(e){var r={};return r.dev=he.isChrdev(e.mode)?e.id:1,r.ino=e.id,r.mode=e.mode,r.nlink=1,r.uid=0,r.gid=0,r.rdev=e.rdev,he.isDir(e.mode)?r.size=4096:he.isFile(e.mode)?r.size=e.usedBytes:he.isLink(e.mode)?r.size=e.link.length:r.size=0,r.atime=new Date(e.timestamp),r.mtime=new Date(e.timestamp),r.ctime=new Date(e.timestamp),r.blksize=4096,r.blocks=Math.ceil(r.size/r.blksize),r},setattr:function(e,r){void 0!==r.mode&&(e.mode=r.mode),void 0!==r.timestamp&&(e.timestamp=r.timestamp),void 0!==r.size&&pe.resizeFileStorage(e,r.size)},lookup:function(e,r){throw he.genericErrors[44]},mknod:function(e,r,t,n){return pe.createNode(e,r,t,n)},rename:function(e,r,t){if(he.isDir(e.mode)){var n;try{n=he.lookupNode(r,t)}catch(e){}if(n)for(var o in n.contents)throw new he.ErrnoError(55)}delete e.parent.contents[e.name],e.parent.timestamp=Date.now(),e.name=t,r.contents[t]=e,r.timestamp=e.parent.timestamp,e.parent=r},unlink:function(e,r){delete e.contents[r],e.timestamp=Date.now()},rmdir:function(e,r){var t=he.lookupNode(e,r);for(var n in t.contents)throw new he.ErrnoError(55);delete e.contents[r],e.timestamp=Date.now()},readdir:function(e){var r=[".",".."];for(var t in e.contents)e.contents.hasOwnProperty(t)&&r.push(t);return r},symlink:function(e,r,t){var n=pe.createNode(e,r,41471,0);return n.link=t,n},readlink:function(e){if(!he.isLink(e.mode))throw new he.ErrnoError(28);return e.link}},stream_ops:{read:function(e,r,t,n,o){var a=e.node.contents;if(o>=e.node.usedBytes)return 0;var i=Math.min(e.node.usedBytes-o,n);if(i>8&&a.subarray)r.set(a.subarray(o,o+i),t);else for(var s=0;s0||t+r{if(!(e=ce.resolve(e)))return{path:"",node:null};if((r=Object.assign({follow_mount:!0,recurse_count:0},r)).recurse_count>8)throw new he.ErrnoError(32);for(var t=e.split("/").filter(e=>!!e),n=he.root,o="/",a=0;a40)throw new he.ErrnoError(32)}}return{path:o,node:n}},getPath:e=>{for(var r;;){if(he.isRoot(e)){var t=e.mount.mountpoint;return r?"/"!==t[t.length-1]?t+"/"+r:t+r:t}r=r?e.name+"/"+r:e.name,e=e.parent}},hashName:(e,r)=>{for(var t=0,n=0;n>>0)%he.nameTable.length},hashAddNode:e=>{var r=he.hashName(e.parent.id,e.name);e.name_next=he.nameTable[r],he.nameTable[r]=e},hashRemoveNode:e=>{var r=he.hashName(e.parent.id,e.name);if(he.nameTable[r]===e)he.nameTable[r]=e.name_next;else for(var t=he.nameTable[r];t;){if(t.name_next===e){t.name_next=e.name_next;break}t=t.name_next}},lookupNode:(e,r)=>{var t=he.mayLookup(e);if(t)throw new he.ErrnoError(t,e);for(var n=he.hashName(e.id,r),o=he.nameTable[n];o;o=o.name_next){var a=o.name;if(o.parent.id===e.id&&a===r)return o}return he.lookup(e,r)},createNode:(e,r,t,n)=>{var o=new he.FSNode(e,r,t,n);return he.hashAddNode(o),o},destroyNode:e=>{he.hashRemoveNode(e)},isRoot:e=>e===e.parent,isMountpoint:e=>!!e.mounted,isFile:e=>32768==(61440&e),isDir:e=>16384==(61440&e),isLink:e=>40960==(61440&e),isChrdev:e=>8192==(61440&e),isBlkdev:e=>24576==(61440&e),isFIFO:e=>4096==(61440&e),isSocket:e=>49152==(49152&e),flagModes:{r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090},modeStringToFlags:e=>{var r=he.flagModes[e];if(void 0===r)throw new Error("Unknown file open mode: "+e);return r},flagsToPermissionString:e=>{var r=["r","w","rw"][3&e];return 512&e&&(r+="w"),r},nodePermissions:(e,r)=>he.ignorePermissions?0:(!r.includes("r")||292&e.mode)&&(!r.includes("w")||146&e.mode)&&(!r.includes("x")||73&e.mode)?0:2,mayLookup:e=>{var r=he.nodePermissions(e,"x");return r||(e.node_ops.lookup?0:2)},mayCreate:(e,r)=>{try{he.lookupNode(e,r);return 20}catch(e){}return he.nodePermissions(e,"wx")},mayDelete:(e,r,t)=>{var n;try{n=he.lookupNode(e,r)}catch(e){return e.errno}var o=he.nodePermissions(e,"wx");if(o)return o;if(t){if(!he.isDir(n.mode))return 54;if(he.isRoot(n)||he.getPath(n)===he.cwd())return 10}else if(he.isDir(n.mode))return 31;return 0},mayOpen:(e,r)=>e?he.isLink(e.mode)?32:he.isDir(e.mode)&&("r"!==he.flagsToPermissionString(r)||512&r)?31:he.nodePermissions(e,he.flagsToPermissionString(r)):44,MAX_OPEN_FDS:4096,nextfd:(e=0,r=he.MAX_OPEN_FDS)=>{for(var t=e;t<=r;t++)if(!he.streams[t])return t;throw new he.ErrnoError(33)},getStream:e=>he.streams[e],createStream:(e,r,t)=>{he.FSStream||(he.FSStream=function(){this.shared={}},he.FSStream.prototype={},Object.defineProperties(he.FSStream.prototype,{object:{get:function(){return this.node},set:function(e){this.node=e}},isRead:{get:function(){return 1!=(2097155&this.flags)}},isWrite:{get:function(){return 0!=(2097155&this.flags)}},isAppend:{get:function(){return 1024&this.flags}},flags:{get:function(){return this.shared.flags},set:function(e){this.shared.flags=e}},position:{get:function(){return this.shared.position},set:function(e){this.shared.position=e}}})),e=Object.assign(new he.FSStream,e);var n=he.nextfd(r,t);return e.fd=n,he.streams[n]=e,e},closeStream:e=>{he.streams[e]=null},chrdev_stream_ops:{open:e=>{var r=he.getDevice(e.node.rdev);e.stream_ops=r.stream_ops,e.stream_ops.open&&e.stream_ops.open(e)},llseek:()=>{throw new he.ErrnoError(70)}},major:e=>e>>8,minor:e=>255&e,makedev:(e,r)=>e<<8|r,registerDevice:(e,r)=>{he.devices[e]={stream_ops:r}},getDevice:e=>he.devices[e],getMounts:e=>{for(var r=[],t=[e];t.length;){var n=t.pop();r.push(n),t.push.apply(t,n.mounts)}return r},syncfs:(e,r)=>{"function"==typeof e&&(r=e,e=!1),he.syncFSRequests++,he.syncFSRequests>1&&E("warning: "+he.syncFSRequests+" FS.syncfs operations in flight at once, probably just doing extra work");var t=he.getMounts(he.root.mount),n=0;function o(e){return he.syncFSRequests--,r(e)}function a(e){if(e)return a.errored?void 0:(a.errored=!0,o(e));++n>=t.length&&o(null)}t.forEach(r=>{if(!r.type.syncfs)return a(null);r.type.syncfs(r,e,a)})},mount:(e,r,t)=>{var n,o="/"===t,a=!t;if(o&&he.root)throw new he.ErrnoError(10);if(!o&&!a){var i=he.lookupPath(t,{follow_mount:!1});if(t=i.path,n=i.node,he.isMountpoint(n))throw new he.ErrnoError(10);if(!he.isDir(n.mode))throw new he.ErrnoError(54)}var s={type:e,opts:r,mountpoint:t,mounts:[]},u=e.mount(s);return u.mount=s,s.root=u,o?he.root=u:n&&(n.mounted=s,n.mount&&n.mount.mounts.push(s)),u},unmount:e=>{var r=he.lookupPath(e,{follow_mount:!1});if(!he.isMountpoint(r.node))throw new he.ErrnoError(28);var t=r.node,n=t.mounted,o=he.getMounts(n);Object.keys(he.nameTable).forEach(e=>{for(var r=he.nameTable[e];r;){var t=r.name_next;o.includes(r.mount)&&he.destroyNode(r),r=t}}),t.mounted=null;var a=t.mount.mounts.indexOf(n);t.mount.mounts.splice(a,1)},lookup:(e,r)=>e.node_ops.lookup(e,r),mknod:(e,r,t)=>{var n=he.lookupPath(e,{parent:!0}).node,o=ue.basename(e);if(!o||"."===o||".."===o)throw new he.ErrnoError(28);var a=he.mayCreate(n,o);if(a)throw new he.ErrnoError(a);if(!n.node_ops.mknod)throw new he.ErrnoError(63);return n.node_ops.mknod(n,o,r,t)},create:(e,r)=>(r=void 0!==r?r:438,r&=4095,r|=32768,he.mknod(e,r,0)),mkdir:(e,r)=>(r=void 0!==r?r:511,r&=1023,r|=16384,he.mknod(e,r,0)),mkdirTree:(e,r)=>{for(var t=e.split("/"),n="",o=0;o(void 0===t&&(t=r,r=438),r|=8192,he.mknod(e,r,t)),symlink:(e,r)=>{if(!ce.resolve(e))throw new he.ErrnoError(44);var t=he.lookupPath(r,{parent:!0}).node;if(!t)throw new he.ErrnoError(44);var n=ue.basename(r),o=he.mayCreate(t,n);if(o)throw new he.ErrnoError(o);if(!t.node_ops.symlink)throw new he.ErrnoError(63);return t.node_ops.symlink(t,n,e)},rename:(e,r)=>{var t,n,o=ue.dirname(e),a=ue.dirname(r),i=ue.basename(e),s=ue.basename(r);if(t=he.lookupPath(e,{parent:!0}).node,n=he.lookupPath(r,{parent:!0}).node,!t||!n)throw new he.ErrnoError(44);if(t.mount!==n.mount)throw new he.ErrnoError(75);var u,c=he.lookupNode(t,i),l=ce.relative(e,a);if("."!==l.charAt(0))throw new he.ErrnoError(28);if("."!==(l=ce.relative(r,o)).charAt(0))throw new he.ErrnoError(55);try{u=he.lookupNode(n,s)}catch(e){}if(c!==u){var f=he.isDir(c.mode),d=he.mayDelete(t,i,f);if(d)throw new he.ErrnoError(d);if(d=u?he.mayDelete(n,s,f):he.mayCreate(n,s))throw new he.ErrnoError(d);if(!t.node_ops.rename)throw new he.ErrnoError(63);if(he.isMountpoint(c)||u&&he.isMountpoint(u))throw new he.ErrnoError(10);if(n!==t&&(d=he.nodePermissions(t,"w")))throw new he.ErrnoError(d);he.hashRemoveNode(c);try{t.node_ops.rename(c,n,s)}catch(e){throw e}finally{he.hashAddNode(c)}}},rmdir:e=>{var r=he.lookupPath(e,{parent:!0}).node,t=ue.basename(e),n=he.lookupNode(r,t),o=he.mayDelete(r,t,!0);if(o)throw new he.ErrnoError(o);if(!r.node_ops.rmdir)throw new he.ErrnoError(63);if(he.isMountpoint(n))throw new he.ErrnoError(10);r.node_ops.rmdir(r,t),he.destroyNode(n)},readdir:e=>{var r=he.lookupPath(e,{follow:!0}).node;if(!r.node_ops.readdir)throw new he.ErrnoError(54);return r.node_ops.readdir(r)},unlink:e=>{var r=he.lookupPath(e,{parent:!0}).node;if(!r)throw new he.ErrnoError(44);var t=ue.basename(e),n=he.lookupNode(r,t),o=he.mayDelete(r,t,!1);if(o)throw new he.ErrnoError(o);if(!r.node_ops.unlink)throw new he.ErrnoError(63);if(he.isMountpoint(n))throw new he.ErrnoError(10);r.node_ops.unlink(r,t),he.destroyNode(n)},readlink:e=>{var r=he.lookupPath(e).node;if(!r)throw new he.ErrnoError(44);if(!r.node_ops.readlink)throw new he.ErrnoError(28);return ce.resolve(he.getPath(r.parent),r.node_ops.readlink(r))},stat:(e,r)=>{var t=he.lookupPath(e,{follow:!r}).node;if(!t)throw new he.ErrnoError(44);if(!t.node_ops.getattr)throw new he.ErrnoError(63);return t.node_ops.getattr(t)},lstat:e=>he.stat(e,!0),chmod:(e,r,t)=>{var n;"string"==typeof e?n=he.lookupPath(e,{follow:!t}).node:n=e;if(!n.node_ops.setattr)throw new he.ErrnoError(63);n.node_ops.setattr(n,{mode:4095&r|-4096&n.mode,timestamp:Date.now()})},lchmod:(e,r)=>{he.chmod(e,r,!0)},fchmod:(e,r)=>{var t=he.getStream(e);if(!t)throw new he.ErrnoError(8);he.chmod(t.node,r)},chown:(e,r,t,n)=>{var o;"string"==typeof e?o=he.lookupPath(e,{follow:!n}).node:o=e;if(!o.node_ops.setattr)throw new he.ErrnoError(63);o.node_ops.setattr(o,{timestamp:Date.now()})},lchown:(e,r,t)=>{he.chown(e,r,t,!0)},fchown:(e,r,t)=>{var n=he.getStream(e);if(!n)throw new he.ErrnoError(8);he.chown(n.node,r,t)},truncate:(e,r)=>{if(r<0)throw new he.ErrnoError(28);var t;"string"==typeof e?t=he.lookupPath(e,{follow:!0}).node:t=e;if(!t.node_ops.setattr)throw new he.ErrnoError(63);if(he.isDir(t.mode))throw new he.ErrnoError(31);if(!he.isFile(t.mode))throw new he.ErrnoError(28);var n=he.nodePermissions(t,"w");if(n)throw new he.ErrnoError(n);t.node_ops.setattr(t,{size:r,timestamp:Date.now()})},ftruncate:(e,r)=>{var t=he.getStream(e);if(!t)throw new he.ErrnoError(8);if(0==(2097155&t.flags))throw new he.ErrnoError(28);he.truncate(t.node,r)},utime:(e,r,t)=>{var n=he.lookupPath(e,{follow:!0}).node;n.node_ops.setattr(n,{timestamp:Math.max(r,t)})},open:(e,r,t)=>{if(""===e)throw new he.ErrnoError(44);var n;if(t=void 0===t?438:t,t=64&(r="string"==typeof r?he.modeStringToFlags(r):r)?4095&t|32768:0,"object"==typeof e)n=e;else{e=ue.normalize(e);try{n=he.lookupPath(e,{follow:!(131072&r)}).node}catch(e){}}var o=!1;if(64&r)if(n){if(128&r)throw new he.ErrnoError(20)}else n=he.mknod(e,t,0),o=!0;if(!n)throw new he.ErrnoError(44);if(he.isChrdev(n.mode)&&(r&=-513),65536&r&&!he.isDir(n.mode))throw new he.ErrnoError(54);if(!o){var i=he.mayOpen(n,r);if(i)throw new he.ErrnoError(i)}512&r&&!o&&he.truncate(n,0),r&=-131713;var s=he.createStream({node:n,path:he.getPath(n),flags:r,seekable:!0,position:0,stream_ops:n.stream_ops,ungotten:[],error:!1});return s.stream_ops.open&&s.stream_ops.open(s),!a.logReadFiles||1&r||(he.readFiles||(he.readFiles={}),e in he.readFiles||(he.readFiles[e]=1)),s},close:e=>{if(he.isClosed(e))throw new he.ErrnoError(8);e.getdents&&(e.getdents=null);try{e.stream_ops.close&&e.stream_ops.close(e)}catch(e){throw e}finally{he.closeStream(e.fd)}e.fd=null},isClosed:e=>null===e.fd,llseek:(e,r,t)=>{if(he.isClosed(e))throw new he.ErrnoError(8);if(!e.seekable||!e.stream_ops.llseek)throw new he.ErrnoError(70);if(0!=t&&1!=t&&2!=t)throw new he.ErrnoError(28);return e.position=e.stream_ops.llseek(e,r,t),e.ungotten=[],e.position},read:(e,r,t,n,o)=>{if(n<0||o<0)throw new he.ErrnoError(28);if(he.isClosed(e))throw new he.ErrnoError(8);if(1==(2097155&e.flags))throw new he.ErrnoError(8);if(he.isDir(e.node.mode))throw new he.ErrnoError(31);if(!e.stream_ops.read)throw new he.ErrnoError(28);var a=void 0!==o;if(a){if(!e.seekable)throw new he.ErrnoError(70)}else o=e.position;var i=e.stream_ops.read(e,r,t,n,o);return a||(e.position+=i),i},write:(e,r,t,n,o,a)=>{if(n<0||o<0)throw new he.ErrnoError(28);if(he.isClosed(e))throw new he.ErrnoError(8);if(0==(2097155&e.flags))throw new he.ErrnoError(8);if(he.isDir(e.node.mode))throw new he.ErrnoError(31);if(!e.stream_ops.write)throw new he.ErrnoError(28);e.seekable&&1024&e.flags&&he.llseek(e,0,2);var i=void 0!==o;if(i){if(!e.seekable)throw new he.ErrnoError(70)}else o=e.position;var s=e.stream_ops.write(e,r,t,n,o,a);return i||(e.position+=s),s},allocate:(e,r,t)=>{if(he.isClosed(e))throw new he.ErrnoError(8);if(r<0||t<=0)throw new he.ErrnoError(28);if(0==(2097155&e.flags))throw new he.ErrnoError(8);if(!he.isFile(e.node.mode)&&!he.isDir(e.node.mode))throw new he.ErrnoError(43);if(!e.stream_ops.allocate)throw new he.ErrnoError(138);e.stream_ops.allocate(e,r,t)},mmap:(e,r,t,n,o)=>{if(0!=(2&n)&&0==(2&o)&&2!=(2097155&e.flags))throw new he.ErrnoError(2);if(1==(2097155&e.flags))throw new he.ErrnoError(2);if(!e.stream_ops.mmap)throw new he.ErrnoError(43);return e.stream_ops.mmap(e,r,t,n,o)},msync:(e,r,t,n,o)=>e.stream_ops.msync?e.stream_ops.msync(e,r,t,n,o):0,munmap:e=>0,ioctl:(e,r,t)=>{if(!e.stream_ops.ioctl)throw new he.ErrnoError(59);return e.stream_ops.ioctl(e,r,t)},readFile:(e,r={})=>{if(r.flags=r.flags||0,r.encoding=r.encoding||"binary","utf8"!==r.encoding&&"binary"!==r.encoding)throw new Error('Invalid encoding type "'+r.encoding+'"');var t,n=he.open(e,r.flags),o=he.stat(e).size,a=new Uint8Array(o);return he.read(n,a,0,o,0),"utf8"===r.encoding?t=R(a,0):"binary"===r.encoding&&(t=a),he.close(n),t},writeFile:(e,r,t={})=>{t.flags=t.flags||577;var n=he.open(e,t.flags,t.mode);if("string"==typeof r){var o=new Uint8Array(U(r)+1),a=z(r,o,0,o.length);he.write(n,o,0,a,void 0,t.canOwn)}else{if(!ArrayBuffer.isView(r))throw new Error("Unsupported data type");he.write(n,r,0,r.byteLength,void 0,t.canOwn)}he.close(n)},cwd:()=>he.currentPath,chdir:e=>{var r=he.lookupPath(e,{follow:!0});if(null===r.node)throw new he.ErrnoError(44);if(!he.isDir(r.node.mode))throw new he.ErrnoError(54);var t=he.nodePermissions(r.node,"x");if(t)throw new he.ErrnoError(t);he.currentPath=r.path},createDefaultDirectories:()=>{he.mkdir("/tmp"),he.mkdir("/home"),he.mkdir("/home/web_user")},createDefaultDevices:()=>{he.mkdir("/dev"),he.registerDevice(he.makedev(1,3),{read:()=>0,write:(e,r,t,n,o)=>n}),he.mkdev("/dev/null",he.makedev(1,3)),fe.register(he.makedev(5,0),fe.default_tty_ops),fe.register(he.makedev(6,0),fe.default_tty1_ops),he.mkdev("/dev/tty",he.makedev(5,0)),he.mkdev("/dev/tty1",he.makedev(6,0));var e=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var e=new Uint8Array(1);return()=>(crypto.getRandomValues(e),e[0])}if(h)try{var r=v("crypto");return()=>r.randomBytes(1)[0]}catch(e){}return()=>Z("randomDevice")}();he.createDevice("/dev","random",e),he.createDevice("/dev","urandom",e),he.mkdir("/dev/shm"),he.mkdir("/dev/shm/tmp")},createSpecialDirectories:()=>{he.mkdir("/proc");var e=he.mkdir("/proc/self");he.mkdir("/proc/self/fd"),he.mount({mount:()=>{var r=he.createNode(e,"fd",16895,73);return r.node_ops={lookup:(e,r)=>{var t=+r,n=he.getStream(t);if(!n)throw new he.ErrnoError(8);var o={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>n.path}};return o.parent=o,o}},r}},{},"/proc/self/fd")},createStandardStreams:()=>{a.stdin?he.createDevice("/dev","stdin",a.stdin):he.symlink("/dev/tty","/dev/stdin"),a.stdout?he.createDevice("/dev","stdout",null,a.stdout):he.symlink("/dev/tty","/dev/stdout"),a.stderr?he.createDevice("/dev","stderr",null,a.stderr):he.symlink("/dev/tty1","/dev/stderr");he.open("/dev/stdin",0),he.open("/dev/stdout",1),he.open("/dev/stderr",1)},ensureErrnoError:()=>{he.ErrnoError||(he.ErrnoError=function(e,r){this.node=r,this.setErrno=function(e){this.errno=e},this.setErrno(e),this.message="FS error"},he.ErrnoError.prototype=new Error,he.ErrnoError.prototype.constructor=he.ErrnoError,[44].forEach(e=>{he.genericErrors[e]=new he.ErrnoError(e),he.genericErrors[e].stack=""}))},staticInit:()=>{he.ensureErrnoError(),he.nameTable=new Array(4096),he.mount(pe,{},"/"),he.createDefaultDirectories(),he.createDefaultDevices(),he.createSpecialDirectories(),he.filesystems={MEMFS:pe}},init:(e,r,t)=>{he.init.initialized=!0,he.ensureErrnoError(),a.stdin=e||a.stdin,a.stdout=r||a.stdout,a.stderr=t||a.stderr,he.createStandardStreams()},quit:()=>{he.init.initialized=!1;for(var e=0;e{var t=0;return e&&(t|=365),r&&(t|=146),t},findObject:(e,r)=>{var t=he.analyzePath(e,r);return t.exists?t.object:null},analyzePath:(e,r)=>{try{e=(n=he.lookupPath(e,{follow:!r})).path}catch(e){}var t={isRoot:!1,exists:!1,error:0,name:null,path:null,object:null,parentExists:!1,parentPath:null,parentObject:null};try{var n=he.lookupPath(e,{parent:!0});t.parentExists=!0,t.parentPath=n.path,t.parentObject=n.node,t.name=ue.basename(e),n=he.lookupPath(e,{follow:!r}),t.exists=!0,t.path=n.path,t.object=n.node,t.name=n.node.name,t.isRoot="/"===n.path}catch(e){t.error=e.errno}return t},createPath:(e,r,t,n)=>{e="string"==typeof e?e:he.getPath(e);for(var o=r.split("/").reverse();o.length;){var a=o.pop();if(a){var i=ue.join2(e,a);try{he.mkdir(i)}catch(e){}e=i}}return i},createFile:(e,r,t,n,o)=>{var a=ue.join2("string"==typeof e?e:he.getPath(e),r),i=he.getMode(n,o);return he.create(a,i)},createDataFile:(e,r,t,n,o,a)=>{var i=r;e&&(e="string"==typeof e?e:he.getPath(e),i=r?ue.join2(e,r):e);var s=he.getMode(n,o),u=he.create(i,s);if(t){if("string"==typeof t){for(var c=new Array(t.length),l=0,f=t.length;l{var o=ue.join2("string"==typeof e?e:he.getPath(e),r),a=he.getMode(!!t,!!n);he.createDevice.major||(he.createDevice.major=64);var i=he.makedev(he.createDevice.major++,0);return he.registerDevice(i,{open:e=>{e.seekable=!1},close:e=>{n&&n.buffer&&n.buffer.length&&n(10)},read:(e,r,n,o,a)=>{for(var i=0,s=0;s{for(var i=0;i{if(e.isDevice||e.isFolder||e.link||e.contents)return!0;if("undefined"!=typeof XMLHttpRequest)throw new Error("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.");if(!i)throw new Error("Cannot load without read() or XMLHttpRequest.");try{e.contents=le(i(e.url),!0),e.usedBytes=e.contents.length}catch(e){throw new he.ErrnoError(29)}},createLazyFile:(e,r,t,n,o)=>{function a(){this.lengthKnown=!1,this.chunks=[]}if(a.prototype.get=function(e){if(!(e>this.length-1||e<0)){var r=e%this.chunkSize,t=e/this.chunkSize|0;return this.getter(t)[r]}},a.prototype.setDataGetter=function(e){this.getter=e},a.prototype.cacheLength=function(){var e=new XMLHttpRequest;if(e.open("HEAD",t,!1),e.send(null),!(e.status>=200&&e.status<300||304===e.status))throw new Error("Couldn't load "+t+". Status: "+e.status);var r,n=Number(e.getResponseHeader("Content-length")),o=(r=e.getResponseHeader("Accept-Ranges"))&&"bytes"===r,a=(r=e.getResponseHeader("Content-Encoding"))&&"gzip"===r,i=1048576;o||(i=n);var s=this;s.setDataGetter(e=>{var r=e*i,o=(e+1)*i-1;if(o=Math.min(o,n-1),void 0===s.chunks[e]&&(s.chunks[e]=((e,r)=>{if(e>r)throw new Error("invalid range ("+e+", "+r+") or no bytes requested!");if(r>n-1)throw new Error("only "+n+" bytes available! programmer error!");var o=new XMLHttpRequest;if(o.open("GET",t,!1),n!==i&&o.setRequestHeader("Range","bytes="+e+"-"+r),o.responseType="arraybuffer",o.overrideMimeType&&o.overrideMimeType("text/plain; charset=x-user-defined"),o.send(null),!(o.status>=200&&o.status<300||304===o.status))throw new Error("Couldn't load "+t+". Status: "+o.status);return void 0!==o.response?new Uint8Array(o.response||[]):le(o.responseText||"",!0)})(r,o)),void 0===s.chunks[e])throw new Error("doXHR failed!");return s.chunks[e]}),!a&&n||(i=n=1,n=this.getter(0).length,i=n,g("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=n,this._chunkSize=i,this.lengthKnown=!0},"undefined"!=typeof XMLHttpRequest){if(!p)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var i=new a;Object.defineProperties(i,{length:{get:function(){return this.lengthKnown||this.cacheLength(),this._length}},chunkSize:{get:function(){return this.lengthKnown||this.cacheLength(),this._chunkSize}}});var s={isDevice:!1,contents:i}}else s={isDevice:!1,url:t};var u=he.createFile(e,r,s,n,o);s.contents?u.contents=s.contents:s.url&&(u.contents=null,u.url=s.url),Object.defineProperties(u,{usedBytes:{get:function(){return this.contents.length}}});var c={};function l(e,r,t,n,o){var a=e.node.contents;if(o>=a.length)return 0;var i=Math.min(a.length-o,n);if(a.slice)for(var s=0;s{var r=u.stream_ops[e];c[e]=function(){return he.forceLoadFile(u),r.apply(null,arguments)}}),c.read=((e,r,t,n,o)=>(he.forceLoadFile(u),l(e,r,t,n,o))),c.mmap=((e,r,t,n,o)=>{he.forceLoadFile(u);var a=de();if(!a)throw new he.ErrnoError(48);return l(e,S,a,r,t),{ptr:a,allocated:!0}}),u.stream_ops=c,u},createPreloadedFile:(e,r,t,n,o,a,i,u,c,l)=>{var f=r?ce.resolve(ue.join2(e,r)):e;X("cp "+f);function d(t){function s(t){l&&l(),u||he.createDataFile(e,r,t,n,o,c),a&&a(),K()}Browser.handledByPreloadPlugin(t,f,s,()=>{i&&i(),K()})||s(t)}Y(),"string"==typeof t?function(e,r,t,n){var o=n?"":X("al "+e);s(e,t=>{C(t,'Loading data file "'+e+'" failed (no arrayBuffer).'),r(new Uint8Array(t)),o&&K()},r=>{if(!t)throw'Loading data file "'+e+'" failed.';t()}),o&&Y()}(t,e=>d(e),i):d(t)},indexedDB:()=>window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB,DB_NAME:()=>"EM_FS_"+window.location.pathname,DB_VERSION:20,DB_STORE_NAME:"FILE_DATA",saveFilesToDB:(e,r,t)=>{r=r||(()=>{}),t=t||(()=>{});var n=he.indexedDB();try{var o=n.open(he.DB_NAME(),he.DB_VERSION)}catch(e){return t(e)}o.onupgradeneeded=(()=>{g("creating db"),o.result.createObjectStore(he.DB_STORE_NAME)}),o.onsuccess=(()=>{var n=o.result.transaction([he.DB_STORE_NAME],"readwrite"),a=n.objectStore(he.DB_STORE_NAME),i=0,s=0,u=e.length;function c(){0==s?r():t()}e.forEach(e=>{var r=a.put(he.analyzePath(e).object.contents,e);r.onsuccess=(()=>{++i+s==u&&c()}),r.onerror=(()=>{i+ ++s==u&&c()})}),n.onerror=t}),o.onerror=t},loadFilesFromDB:(e,r,t)=>{r=r||(()=>{}),t=t||(()=>{});var n=he.indexedDB();try{var o=n.open(he.DB_NAME(),he.DB_VERSION)}catch(e){return t(e)}o.onupgradeneeded=t,o.onsuccess=(()=>{var n=o.result;try{var a=n.transaction([he.DB_STORE_NAME],"readonly")}catch(e){return void t(e)}var i=a.objectStore(he.DB_STORE_NAME),s=0,u=0,c=e.length;function l(){0==u?r():t()}e.forEach(e=>{var r=i.get(e);r.onsuccess=(()=>{he.analyzePath(e).exists&&he.unlink(e),he.createDataFile(ue.dirname(e),ue.basename(e),r.result,!0,!0,!0),++s+u==c&&l()}),r.onerror=(()=>{s+ ++u==c&&l()})}),a.onerror=t}),o.onerror=t}},me={mount:function(e){return a.websocket=a.websocket&&"object"==typeof a.websocket?a.websocket:{},a.websocket._callbacks={},a.websocket.on=function(e,r){return"function"==typeof r&&(this._callbacks[e]=r),this},a.websocket.emit=function(e,r){"function"==typeof this._callbacks[e]&&this._callbacks[e].call(this,r)},he.createNode(null,"/",16895,0)},createSocket:function(e,r,t){if(1==(r&=-526337)&&t&&6!=t)throw new he.ErrnoError(66);var n={family:e,type:r,protocol:t,server:null,error:null,peers:{},pending:[],recv_queue:[],sock_ops:me.websocket_sock_ops},o=me.nextname(),a=he.createNode(me.root,o,49152,0);a.sock=n;var i=he.createStream({path:o,node:a,flags:2,seekable:!1,stream_ops:me.stream_ops});return n.stream=i,n},getSocket:function(e){var r=he.getStream(e);return r&&he.isSocket(r.node.mode)?r.node.sock:null},stream_ops:{poll:function(e){var r=e.node.sock;return r.sock_ops.poll(r)},ioctl:function(e,r,t){var n=e.node.sock;return n.sock_ops.ioctl(n,r,t)},read:function(e,r,t,n,o){var a=e.node.sock,i=a.sock_ops.recvmsg(a,n);return i?(r.set(i.buffer,t),i.buffer.length):0},write:function(e,r,t,n,o){var a=e.node.sock;return a.sock_ops.sendmsg(a,r,t,n)},close:function(e){var r=e.node.sock;r.sock_ops.close(r)}},nextname:function(){return me.nextname.current||(me.nextname.current=0),"socket["+me.nextname.current+++"]"},websocket_sock_ops:{createPeer:function(e,r,t){var n;if("object"==typeof r&&(n=r,r=null,t=null),n)if(n._socket)r=n._socket.remoteAddress,t=n._socket.remotePort;else{var o=/ws[s]?:\/\/([^:]+):(\d+)/.exec(n.url);if(!o)throw new Error("WebSocket URL must be in the format ws(s)://address:port");r=o[1],t=parseInt(o[2],10)}else try{var i=a.websocket&&"object"==typeof a.websocket,s="ws:#".replace("#","//");if(i&&"string"==typeof a.websocket.url&&(s=a.websocket.url),"ws://"===s||"wss://"===s){var u=r.split("/");s=s+u[0]+":"+t+"/"+u.slice(1).join("/")}var c="binary";i&&"string"==typeof a.websocket.subprotocol&&(c=a.websocket.subprotocol);var l=void 0;"null"!==c&&(l=c=c.replace(/^ +| +$/g,"").split(/ *, */)),i&&null===a.websocket.subprotocol&&(c="null",l=void 0),(n=new(h?v("ws"):WebSocket)(s,l)).binaryType="arraybuffer"}catch(e){throw new he.ErrnoError(23)}var f={addr:r,port:t,socket:n,dgram_send_queue:[]};return me.websocket_sock_ops.addPeer(e,f),me.websocket_sock_ops.handlePeerEvents(e,f),2===e.type&&void 0!==e.sport&&f.dgram_send_queue.push(new Uint8Array([255,255,255,255,"p".charCodeAt(0),"o".charCodeAt(0),"r".charCodeAt(0),"t".charCodeAt(0),(65280&e.sport)>>8,255&e.sport])),f},getPeer:function(e,r,t){return e.peers[r+":"+t]},addPeer:function(e,r){e.peers[r.addr+":"+r.port]=r},removePeer:function(e,r){delete e.peers[r.addr+":"+r.port]},handlePeerEvents:function(e,r){var t=!0,n=function(){a.websocket.emit("open",e.stream.fd);try{for(var t=r.dgram_send_queue.shift();t;)r.socket.send(t),t=r.dgram_send_queue.shift()}catch(e){r.socket.close()}};function o(n){if("string"==typeof n){n=(new TextEncoder).encode(n)}else{if(C(void 0!==n.byteLength),0==n.byteLength)return;n=new Uint8Array(n)}var o=t;if(t=!1,o&&10===n.length&&255===n[0]&&255===n[1]&&255===n[2]&&255===n[3]&&n[4]==="p".charCodeAt(0)&&n[5]==="o".charCodeAt(0)&&n[6]==="r".charCodeAt(0)&&n[7]==="t".charCodeAt(0)){var i=n[8]<<8|n[9];return me.websocket_sock_ops.removePeer(e,r),r.port=i,void me.websocket_sock_ops.addPeer(e,r)}e.recv_queue.push({addr:r.addr,port:r.port,data:n}),a.websocket.emit("message",e.stream.fd)}h?(r.socket.on("open",n),r.socket.on("message",function(e,r){r&&o(new Uint8Array(e).buffer)}),r.socket.on("close",function(){a.websocket.emit("close",e.stream.fd)}),r.socket.on("error",function(r){e.error=14,a.websocket.emit("error",[e.stream.fd,e.error,"ECONNREFUSED: Connection refused"])})):(r.socket.onopen=n,r.socket.onclose=function(){a.websocket.emit("close",e.stream.fd)},r.socket.onmessage=function(e){o(e.data)},r.socket.onerror=function(r){e.error=14,a.websocket.emit("error",[e.stream.fd,e.error,"ECONNREFUSED: Connection refused"])})},poll:function(e){if(1===e.type&&e.server)return e.pending.length?65:0;var r=0,t=1===e.type?me.websocket_sock_ops.getPeer(e,e.daddr,e.dport):null;return(e.recv_queue.length||!t||t&&t.socket.readyState===t.socket.CLOSING||t&&t.socket.readyState===t.socket.CLOSED)&&(r|=65),(!t||t&&t.socket.readyState===t.socket.OPEN)&&(r|=4),(t&&t.socket.readyState===t.socket.CLOSING||t&&t.socket.readyState===t.socket.CLOSED)&&(r|=16),r},ioctl:function(e,r,t){switch(r){case 21531:var n=0;return e.recv_queue.length&&(n=e.recv_queue[0].data.length),$[t>>2]=n,0;default:return 28}},close:function(e){if(e.server){try{e.server.close()}catch(e){}e.server=null}for(var r=Object.keys(e.peers),t=0;t>8&255)+"."+(e>>16&255)+"."+(e>>24&255)}function we(e,r){var t,n=A[e>>1],o=mt(F[e+2>>1]);switch(n){case 2:if(16!==r)return{errno:28};t=ve(t=$[e+4>>2]);break;case 10:if(28!==r)return{errno:28};t=function(e){var r="",t=0,n=0,o=0,a=0,i=0,s=0,u=[65535&e[0],e[0]>>16,65535&e[1],e[1]>>16,65535&e[2],e[2]>>16,65535&e[3],e[3]>>16],c=!0,l="";for(s=0;s<5;s++)if(0!==u[s]){c=!1;break}if(c){if(l=ve(u[6]|u[7]<<16),-1===u[5])return r="::ffff:",r+=l;if(0===u[5])return r="::","0.0.0.0"===l&&(l=""),"0.0.0.1"===l&&(l="1"),r+=l}for(t=0;t<8;t++)0===u[t]&&(t-o>1&&(i=0),o=t,i++),i>n&&(a=t-(n=i)+1);for(t=0;t<8;t++)n>1&&0===u[t]&&t>=a&&t>2],$[e+12>>2],$[e+16>>2],$[e+20>>2]]);break;default:return{errno:5}}return{family:n,addr:t,port:o}}function ye(e){return parseInt(e)}var ge={address_map:{id:1,addrs:{},names:{}},lookup_name:function(e){var r,t=function(e){for(var r=e.split("."),t=0;t<4;t++){var n=Number(r[t]);if(isNaN(n))return null;r[t]=n}return(r[0]|r[1]<<8|r[2]<<16|r[3]<<24)>>>0}(e);if(null!==t)return e;if(null!==(t=function(e){var r,t,n,o,a=[];if(!/^((?=.*::)(?!.*::.+::)(::)?([\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.test(e))return null;if("::"===e)return[0,0,0,0,0,0,0,0];for((e=e.startsWith("::")?e.replace("::","Z:"):e.replace("::",":Z:")).indexOf(".")>0?((r=(e=e.replace(new RegExp("[.]","g"),":")).split(":"))[r.length-4]=ye(r[r.length-4])+256*ye(r[r.length-3]),r[r.length-3]=ye(r[r.length-2])+256*ye(r[r.length-1]),r=r.slice(0,r.length-2)):r=e.split(":"),n=0,o=0,t=0;t>2]=n.dev,$[t+8>>2]=n.ino,$[t+12>>2]=n.mode,M[t+16>>2]=n.nlink,$[t+20>>2]=n.uid,$[t+24>>2]=n.gid,$[t+28>>2]=n.rdev,re=[n.size>>>0,(ee=n.size,+Math.abs(ee)>=1?ee>0?(0|Math.min(+Math.floor(ee/4294967296),4294967295))>>>0:~~+Math.ceil((ee-+(~~ee>>>0))/4294967296)>>>0:0)],$[t+40>>2]=re[0],$[t+44>>2]=re[1],$[t+48>>2]=4096,$[t+52>>2]=n.blocks;var o=n.atime.getTime(),a=n.mtime.getTime(),i=n.ctime.getTime();return re=[Math.floor(o/1e3)>>>0,(ee=Math.floor(o/1e3),+Math.abs(ee)>=1?ee>0?(0|Math.min(+Math.floor(ee/4294967296),4294967295))>>>0:~~+Math.ceil((ee-+(~~ee>>>0))/4294967296)>>>0:0)],$[t+56>>2]=re[0],$[t+60>>2]=re[1],M[t+64>>2]=o%1e3*1e3,re=[Math.floor(a/1e3)>>>0,(ee=Math.floor(a/1e3),+Math.abs(ee)>=1?ee>0?(0|Math.min(+Math.floor(ee/4294967296),4294967295))>>>0:~~+Math.ceil((ee-+(~~ee>>>0))/4294967296)>>>0:0)],$[t+72>>2]=re[0],$[t+76>>2]=re[1],M[t+80>>2]=a%1e3*1e3,re=[Math.floor(i/1e3)>>>0,(ee=Math.floor(i/1e3),+Math.abs(ee)>=1?ee>0?(0|Math.min(+Math.floor(ee/4294967296),4294967295))>>>0:~~+Math.ceil((ee-+(~~ee>>>0))/4294967296)>>>0:0)],$[t+88>>2]=re[0],$[t+92>>2]=re[1],M[t+96>>2]=i%1e3*1e3,re=[n.ino>>>0,(ee=n.ino,+Math.abs(ee)>=1?ee>0?(0|Math.min(+Math.floor(ee/4294967296),4294967295))>>>0:~~+Math.ceil((ee-+(~~ee>>>0))/4294967296)>>>0:0)],$[t+104>>2]=re[0],$[t+108>>2]=re[1],0},doMsync:function(e,r,t,n,o){if(!he.isFile(r.node.mode))throw new he.ErrnoError(43);if(2&n)return 0;var a=D.slice(e,e+t);he.msync(r,a,o,t,n)},varargs:void 0,get:function(){return Ee.varargs+=4,$[Ee.varargs-4>>2]},getStr:function(e){return N(e)},getStreamFromFD:function(e){var r=he.getStream(e);if(!r)throw new he.ErrnoError(8);return r}};function be(e,r){return r+2097152>>>0<4194305-!!e?(e>>>0)+4294967296*r:NaN}var _e={};function ke(e){for(;e.length;){var r=e.pop();e.pop()(r)}}function Te(e){return this.fromWireType($[e>>2])}var Pe={},Ce={},Se={},De=48,Ae=57;function Fe(e){if(void 0===e)return"_unknown";var r=(e=e.replace(/[^a-zA-Z0-9_]/g,"$")).charCodeAt(0);return r>=De&&r<=Ae?"_"+e:e}function $e(e,r){return e=Fe(e),new Function("body","return function "+e+'() {\n "use strict"; return body.apply(this, arguments);\n};\n')(r)}function Me(e,r){var t=$e(r,function(e){this.name=r,this.message=e;var t=new Error(e).stack;void 0!==t&&(this.stack=this.toString()+"\n"+t.replace(/^Error(:[^\n]*)?\n/,""))});return t.prototype=Object.create(e.prototype),t.prototype.constructor=t,t.prototype.toString=function(){return void 0===this.message?this.name:this.name+": "+this.message},t}var Oe=void 0;function je(e){throw new Oe(e)}function xe(e,r,t){function n(r){var n=t(r);n.length!==e.length&&je("Mismatched type converter count");for(var o=0;o{Ce.hasOwnProperty(e)?o[r]=Ce[e]:(a.push(e),Pe.hasOwnProperty(e)||(Pe[e]=[]),Pe[e].push(()=>{o[r]=Ce[e],++i===a.length&&n(o)}))}),0===a.length&&n(o)}var Re={};function Ne(e){switch(e){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError("Unknown type size: "+e)}}var ze=void 0;function Ue(e){for(var r="",t=e;D[t];)r+=ze[D[t++]];return r}var We=void 0;function Be(e){throw new We(e)}function Le(e,r,t={}){if(!("argPackAdvance"in r))throw new TypeError("registerType registeredInstance requires argPackAdvance");var n=r.name;if(e||Be('type "'+n+'" must have a positive integer typeid pointer'),Ce.hasOwnProperty(e)){if(t.ignoreDuplicateRegistrations)return;Be("Cannot register type '"+n+"' twice")}if(Ce[e]=r,delete Se[e],Pe.hasOwnProperty(e)){var o=Pe[e];delete Pe[e],o.forEach(e=>e())}}function Ie(e){if(!(this instanceof lr))return!1;if(!(e instanceof lr))return!1;for(var r=this.$$.ptrType.registeredClass,t=this.$$.ptr,n=e.$$.ptrType.registeredClass,o=e.$$.ptr;r.baseClass;)t=r.upcast(t),r=r.baseClass;for(;n.baseClass;)o=n.upcast(o),n=n.baseClass;return r===n&&t===o}function He(e){Be(e.$$.ptrType.registeredClass.name+" instance already deleted")}var Ve=!1;function qe(e){}function Ge(e){e.count.value-=1,0===e.count.value&&function(e){e.smartPtr?e.smartPtrType.rawDestructor(e.smartPtr):e.ptrType.registeredClass.rawDestructor(e.ptr)}(e)}var Xe={};function Ye(){return Object.keys(rr).length}function Ke(){var e=[];for(var r in rr)rr.hasOwnProperty(r)&&e.push(rr[r]);return e}var Ze=[];function Je(){for(;Ze.length;){var e=Ze.pop();e.$$.deleteScheduled=!1,e.delete()}}var Qe=void 0;function er(e){Qe=e,Ze.length&&Qe&&Qe(Je)}var rr={};function tr(e,r){return r=function(e,r){for(void 0===r&&Be("ptr should not be undefined");e.baseClass;)r=e.upcast(r),e=e.baseClass;return r}(e,r),rr[r]}function nr(e,r){return r.ptrType&&r.ptr||je("makeClassHandle requires ptr and ptrType"),!!r.smartPtrType!==!!r.smartPtr&&je("Both smartPtrType and smartPtr must be specified"),r.count={value:1},ar(Object.create(e,{$$:{value:r}}))}function or(e){var r=this.getPointee(e);if(!r)return this.destructor(e),null;var t=tr(this.registeredClass,r);if(void 0!==t){if(0===t.$$.count.value)return t.$$.ptr=r,t.$$.smartPtr=e,t.clone();var n=t.clone();return this.destructor(e),n}function o(){return this.isSmartPointer?nr(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:r,smartPtrType:this,smartPtr:e}):nr(this.registeredClass.instancePrototype,{ptrType:this,ptr:e})}var a,i=this.registeredClass.getActualType(r),s=Xe[i];if(!s)return o.call(this);a=this.isConst?s.constPointerType:s.pointerType;var u=function e(r,t,n){if(t===n)return r;if(void 0===n.baseClass)return null;var o=e(r,t,n.baseClass);return null===o?null:n.downcast(o)}(r,this.registeredClass,a.registeredClass);return null===u?o.call(this):this.isSmartPointer?nr(a.registeredClass.instancePrototype,{ptrType:a,ptr:u,smartPtrType:this,smartPtr:e}):nr(a.registeredClass.instancePrototype,{ptrType:a,ptr:u})}function ar(e){return"undefined"==typeof FinalizationRegistry?(ar=(e=>e),e):(Ve=new FinalizationRegistry(e=>{Ge(e.$$)}),qe=(e=>Ve.unregister(e)),(ar=(e=>{var r=e.$$;if(!!r.smartPtr){var t={$$:r};Ve.register(e,t,e)}return e}))(e))}function ir(){if(this.$$.ptr||He(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var e,r=ar(Object.create(Object.getPrototypeOf(this),{$$:{value:(e=this.$$,{count:e.count,deleteScheduled:e.deleteScheduled,preservePointerOnDelete:e.preservePointerOnDelete,ptr:e.ptr,ptrType:e.ptrType,smartPtr:e.smartPtr,smartPtrType:e.smartPtrType})}}));return r.$$.count.value+=1,r.$$.deleteScheduled=!1,r}function sr(){this.$$.ptr||He(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&Be("Object already scheduled for deletion"),qe(this),Ge(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)}function ur(){return!this.$$.ptr}function cr(){return this.$$.ptr||He(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&Be("Object already scheduled for deletion"),Ze.push(this),1===Ze.length&&Qe&&Qe(Je),this.$$.deleteScheduled=!0,this}function lr(){}function fr(e,r,t){if(void 0===e[r].overloadTable){var n=e[r];e[r]=function(){return e[r].overloadTable.hasOwnProperty(arguments.length)||Be("Function '"+t+"' called with an invalid number of arguments ("+arguments.length+") - expects one of ("+e[r].overloadTable+")!"),e[r].overloadTable[arguments.length].apply(this,arguments)},e[r].overloadTable=[],e[r].overloadTable[n.argCount]=n}}function dr(e,r,t){a.hasOwnProperty(e)?((void 0===t||void 0!==a[e].overloadTable&&void 0!==a[e].overloadTable[t])&&Be("Cannot register public name '"+e+"' twice"),fr(a,e,e),a.hasOwnProperty(t)&&Be("Cannot register multiple overloads of a function with the same number of arguments ("+t+")!"),a[e].overloadTable[t]=r):(a[e]=r,void 0!==t&&(a[e].numArguments=t))}function pr(e,r,t){for(;r!==t;)r.upcast||Be("Expected null or instance of "+t.name+", got an instance of "+r.name),e=r.upcast(e),r=r.baseClass;return e}function hr(e,r){if(null===r)return this.isReference&&Be("null is not a valid "+this.name),0;r.$$||Be('Cannot pass "'+zr(r)+'" as a '+this.name),r.$$.ptr||Be("Cannot pass deleted object as a pointer of type "+this.name);var t=r.$$.ptrType.registeredClass;return pr(r.$$.ptr,t,this.registeredClass)}function mr(e,r){var t;if(null===r)return this.isReference&&Be("null is not a valid "+this.name),this.isSmartPointer?(t=this.rawConstructor(),null!==e&&e.push(this.rawDestructor,t),t):0;r.$$||Be('Cannot pass "'+zr(r)+'" as a '+this.name),r.$$.ptr||Be("Cannot pass deleted object as a pointer of type "+this.name),!this.isConst&&r.$$.ptrType.isConst&&Be("Cannot convert argument of type "+(r.$$.smartPtrType?r.$$.smartPtrType.name:r.$$.ptrType.name)+" to parameter type "+this.name);var n=r.$$.ptrType.registeredClass;if(t=pr(r.$$.ptr,n,this.registeredClass),this.isSmartPointer)switch(void 0===r.$$.smartPtr&&Be("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:r.$$.smartPtrType===this?t=r.$$.smartPtr:Be("Cannot convert argument of type "+(r.$$.smartPtrType?r.$$.smartPtrType.name:r.$$.ptrType.name)+" to parameter type "+this.name);break;case 1:t=r.$$.smartPtr;break;case 2:if(r.$$.smartPtrType===this)t=r.$$.smartPtr;else{var o=r.clone();t=this.rawShare(t,Rr.toHandle(function(){o.delete()})),null!==e&&e.push(this.rawDestructor,t)}break;default:Be("Unsupporting sharing policy")}return t}function vr(e,r){if(null===r)return this.isReference&&Be("null is not a valid "+this.name),0;r.$$||Be('Cannot pass "'+zr(r)+'" as a '+this.name),r.$$.ptr||Be("Cannot pass deleted object as a pointer of type "+this.name),r.$$.ptrType.isConst&&Be("Cannot convert argument of type "+r.$$.ptrType.name+" to parameter type "+this.name);var t=r.$$.ptrType.registeredClass;return pr(r.$$.ptr,t,this.registeredClass)}function wr(e){return this.rawGetPointee&&(e=this.rawGetPointee(e)),e}function yr(e){this.rawDestructor&&this.rawDestructor(e)}function gr(e){null!==e&&e.delete()}function Er(e,r,t,n,o,a,i,s,u,c,l){this.name=e,this.registeredClass=r,this.isReference=t,this.isConst=n,this.isSmartPointer=o,this.pointeeType=a,this.sharingPolicy=i,this.rawGetPointee=s,this.rawConstructor=u,this.rawShare=c,this.rawDestructor=l,o||void 0!==r.baseClass?this.toWireType=mr:n?(this.toWireType=hr,this.destructorFunction=null):(this.toWireType=vr,this.destructorFunction=null)}function br(e){return B.get(e)}function _r(e,r,t){return e.includes("j")?function(e,r,t){var n=a["dynCall_"+e];return t&&t.length?n.apply(null,[r].concat(t)):n.call(null,r)}(e,r,t):br(r).apply(null,t)}function kr(e,r){var t,n,o,a=(e=Ue(e)).includes("j")?(t=e,n=r,o=[],function(){return o.length=0,Object.assign(o,arguments),_r(t,n,o)}):br(r);return"function"!=typeof a&&Be("unknown function pointer with signature "+e+": "+r),a}var Tr=void 0;function Pr(e){var r=pt(e),t=Ue(r);return ft(r),t}function Cr(e,r){var t=[],n={};throw r.forEach(function e(r){n[r]||Ce[r]||(Se[r]?Se[r].forEach(e):(t.push(r),n[r]=!0))}),new Tr(e+": "+t.map(Pr).join([", "]))}function Sr(e,r){if(!(e instanceof Function))throw new TypeError("new_ called with constructor type "+typeof e+" which is not a function");var t=$e(e.name||"unknownFunctionName",function(){});t.prototype=e.prototype;var n=new t,o=e.apply(n,r);return o instanceof Object?o:n}function Dr(e,r,t,n,o){var a=r.length;a<2&&Be("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var i=null!==r[1]&&null!==t,s=!1,u=1;u0?", ":"")+f),d+=(c?"var rv = ":"")+"invoker(fn"+(f.length>0?", ":"")+f+");\n",s)d+="runDestructors(destructors);\n";else for(u=i?1:2;u>2]);return t}function Fr(e,r,t){return e instanceof Object||Be(t+' with invalid "this": '+e),e instanceof r.registeredClass.constructor||Be(t+' incompatible with "this" of type '+e.constructor.name),e.$$.ptr||Be("cannot call emscripten binding method "+t+" on deleted object"),pr(e.$$.ptr,e.$$.ptrType.registeredClass,r.registeredClass)}var $r=[],Mr=[{},{value:void 0},{value:null},{value:!0},{value:!1}];function Or(e){e>4&&0==--Mr[e].refcount&&(Mr[e]=void 0,$r.push(e))}function jr(){for(var e=0,r=5;r(e||Be("Cannot use deleted val. handle = "+e),Mr[e].value),toHandle:e=>{switch(e){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:var r=$r.length?$r.pop():Mr.length;return Mr[r]={refcount:1,value:e},r}}};function Nr(e,r){var t=Ce[e];return void 0===t&&Be(r+" has unknown type "+Pr(e)),t}function zr(e){if(null===e)return"null";var r=typeof e;return"object"===r||"array"===r||"function"===r?e.toString():""+e}var Ur="undefined"!=typeof TextDecoder?new TextDecoder("utf-16le"):void 0;function Wr(e,r){for(var t=e,n=t>>1,o=n+r/2;!(n>=o)&&F[n];)++n;if((t=n<<1)-e>32&&Ur)return Ur.decode(D.subarray(e,t));for(var a="",i=0;!(i>=r/2);++i){var s=A[e+2*i>>1];if(0==s)break;a+=String.fromCharCode(s)}return a}function Br(e,r,t){if(void 0===t&&(t=2147483647),t<2)return 0;for(var n=r,o=(t-=2)<2*e.length?t/2:e.length,a=0;a>1]=i,r+=2}return A[r>>1]=0,r-n}function Lr(e){return 2*e.length}function Ir(e,r){for(var t=0,n="";!(t>=r/4);){var o=$[e+4*t>>2];if(0==o)break;if(++t,o>=65536){var a=o-65536;n+=String.fromCharCode(55296|a>>10,56320|1023&a)}else n+=String.fromCharCode(o)}return n}function Hr(e,r,t){if(void 0===t&&(t=2147483647),t<4)return 0;for(var n=r,o=n+t-4,a=0;a=55296&&i<=57343)i=65536+((1023&i)<<10)|1023&e.charCodeAt(++a);if($[r>>2]=i,(r+=4)+4>o)break}return $[r>>2]=0,r-n}function Vr(e){for(var r=0,t=0;t=55296&&n<=57343&&++t,r+=4}return r}var qr={};function Gr(e){var r=qr[e];return void 0===r?Ue(e):r}var Xr=[];function Yr(){return"object"==typeof globalThis?globalThis:Function("return this")()}var Kr=[];var Zr={};function Jr(e){return M[e>>2]+4294967296*$[e+4>>2]}var Qr,et=[0,31,60,91,121,152,182,213,244,274,305,335],rt=[0,31,59,90,120,151,181,212,243,273,304,334];function tt(e){var r;return((r=e.getFullYear())%4==0&&(r%100!=0||r%400==0)?et:rt)[e.getMonth()]+e.getDate()-1}function nt(e){var r=U(e)+1,t=lt(r);return t&&z(e,S,t,r),t}function ot(e){var r=k.buffer;try{return k.grow(e-r.byteLength+65535>>>16),W(),1}catch(e){}}Qr=h?()=>{var e=process.hrtime();return 1e3*e[0]+e[1]/1e6}:()=>performance.now();var at={};function it(){if(!it.strings){var e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:f||"./this.program"};for(var r in at)void 0===at[r]?delete e[r]:e[r]=at[r];var t=[];for(var r in e)t.push(r+"="+e[r]);it.strings=t}return it.strings}var st=function(e,r,t,n){e||(e=this),this.parent=e,this.mount=e.mount,this.mounted=null,this.id=he.nextInode++,this.name=r,this.mode=t,this.node_ops={},this.stream_ops={},this.rdev=n};Object.defineProperties(st.prototype,{read:{get:function(){return 365==(365&this.mode)},set:function(e){e?this.mode|=365:this.mode&=-366}},write:{get:function(){return 146==(146&this.mode)},set:function(e){e?this.mode|=146:this.mode&=-147}},isFolder:{get:function(){return he.isDir(this.mode)}},isDevice:{get:function(){return he.isChrdev(this.mode)}}}),he.FSNode=st,he.staticInit(),Oe=a.InternalError=Me(Error,"InternalError"),function(){for(var e=new Array(256),r=0;r<256;++r)e[r]=String.fromCharCode(r);ze=e}(),We=a.BindingError=Me(Error,"BindingError"),lr.prototype.isAliasOf=Ie,lr.prototype.clone=ir,lr.prototype.delete=sr,lr.prototype.isDeleted=ur,lr.prototype.deleteLater=cr,a.getInheritedInstanceCount=Ye,a.getLiveInheritedInstances=Ke,a.flushPendingDeletes=Je,a.setDelayFunction=er,Er.prototype.getPointee=wr,Er.prototype.destructor=yr,Er.prototype.argPackAdvance=8,Er.prototype.readValueFromPointer=Te,Er.prototype.deleteObject=gr,Er.prototype.fromWireType=or,Tr=a.UnboundTypeError=Me(Error,"UnboundTypeError"),a.count_emval_handles=jr,a.get_first_emval=xr;var ut,ct={v:function(e,r,t){throw new function(e){this.excPtr=e,this.ptr=e-24,this.set_type=function(e){M[this.ptr+4>>2]=e},this.get_type=function(){return M[this.ptr+4>>2]},this.set_destructor=function(e){M[this.ptr+8>>2]=e},this.get_destructor=function(){return M[this.ptr+8>>2]},this.set_refcount=function(e){$[this.ptr>>2]=e},this.set_caught=function(e){e=e?1:0,S[this.ptr+12>>0]=e},this.get_caught=function(){return 0!=S[this.ptr+12>>0]},this.set_rethrown=function(e){e=e?1:0,S[this.ptr+13>>0]=e},this.get_rethrown=function(){return 0!=S[this.ptr+13>>0]},this.init=function(e,r){this.set_adjusted_ptr(0),this.set_type(e),this.set_destructor(r),this.set_refcount(0),this.set_caught(!1),this.set_rethrown(!1)},this.add_ref=function(){var e=$[this.ptr>>2];$[this.ptr>>2]=e+1},this.release_ref=function(){var e=$[this.ptr>>2];return $[this.ptr>>2]=e-1,1===e},this.set_adjusted_ptr=function(e){M[this.ptr+16>>2]=e},this.get_adjusted_ptr=function(){return M[this.ptr+16>>2]},this.get_exception_ptr=function(){if(vt(this.get_type()))return M[this.excPtr>>2];var e=this.get_adjusted_ptr();return 0!==e?e:this.excPtr}}(e).init(r,t),e,0,e},U:function(e,r,t){try{var n=function(e){var r=me.getSocket(e);if(!r)throw new he.ErrnoError(8);return r}(e),o=function(e,r,t){if(t&&0===e)return null;var n=we(e,r);if(n.errno)throw new he.ErrnoError(n.errno);return n.addr=ge.lookup_addr(n.addr)||n.addr,n}(r,t);return n.sock_ops.connect(n,o.addr,o.port),0}catch(e){if(void 0===he||!(e instanceof he.ErrnoError))throw e;return-e.errno}},ea:function(e,r,t,n){try{if(r=Ee.getStr(r),r=Ee.calculateAt(e,r),-8&t)return-28;var o=he.lookupPath(r,{follow:!0}).node;if(!o)return-44;var a="";return 4&t&&(a+="r"),2&t&&(a+="w"),1&t&&(a+="x"),a&&he.nodePermissions(o,a)?-2:0}catch(e){if(void 0===he||!(e instanceof he.ErrnoError))throw e;return-e.errno}},o:function(e,r,t){Ee.varargs=t;try{var n=Ee.getStreamFromFD(e);switch(r){case 0:return(o=Ee.get())<0?-28:he.createStream(n,o).fd;case 1:case 2:return 0;case 3:return n.flags;case 4:var o=Ee.get();return n.flags|=o,0;case 5:return o=Ee.get(),A[o+0>>1]=2,0;case 6:case 7:return 0;case 16:case 8:return-28;case 9:return a=28,$[dt()>>2]=a,-1;default:return-28}}catch(e){if(void 0===he||!(e instanceof he.ErrnoError))throw e;return-e.errno}var a},Z:function(e,r){try{var t=Ee.getStreamFromFD(e);return Ee.doStat(he.stat,t.path,r)}catch(e){if(void 0===he||!(e instanceof he.ErrnoError))throw e;return-e.errno}},S:function(e,r,t){try{var n=be(r,t);return isNaN(n)?-61:(he.ftruncate(e,n),0)}catch(e){if(void 0===he||!(e instanceof he.ErrnoError))throw e;return-e.errno}},K:function(e,r,t){Ee.varargs=t;try{var n=Ee.getStreamFromFD(e);switch(r){case 21509:case 21505:return n.tty?0:-59;case 21510:case 21511:case 21512:case 21506:case 21507:case 21508:return n.tty?0:-59;case 21519:if(!n.tty)return-59;var o=Ee.get();return $[o>>2]=0,0;case 21520:return n.tty?-28:-59;case 21531:return o=Ee.get(),he.ioctl(n,r,o);case 21523:case 21524:return n.tty?0:-59;default:return-28}}catch(e){if(void 0===he||!(e instanceof he.ErrnoError))throw e;return-e.errno}},W:function(e,r){try{return e=Ee.getStr(e),Ee.doStat(he.lstat,e,r)}catch(e){if(void 0===he||!(e instanceof he.ErrnoError))throw e;return-e.errno}},X:function(e,r,t,n){try{r=Ee.getStr(r);var o=256&n,a=4096&n;return n&=-6401,r=Ee.calculateAt(e,r,a),Ee.doStat(o?he.lstat:he.stat,r,t)}catch(e){if(void 0===he||!(e instanceof he.ErrnoError))throw e;return-e.errno}},G:function(e,r,t,n){Ee.varargs=n;try{r=Ee.getStr(r),r=Ee.calculateAt(e,r);var o=n?Ee.get():0;return he.open(r,t,o).fd}catch(e){if(void 0===he||!(e instanceof he.ErrnoError))throw e;return-e.errno}},F:function(e,r,t){try{return me.createSocket(e,r,t).stream.fd}catch(e){if(void 0===he||!(e instanceof he.ErrnoError))throw e;return-e.errno}},Y:function(e,r){try{return e=Ee.getStr(e),Ee.doStat(he.stat,e,r)}catch(e){if(void 0===he||!(e instanceof he.ErrnoError))throw e;return-e.errno}},r:function(e){var r=_e[e];delete _e[e];var t=r.elements,n=t.length,o=t.map(function(e){return e.getterReturnType}).concat(t.map(function(e){return e.setterArgumentType})),a=r.rawConstructor,i=r.rawDestructor;xe([e],o,function(e){return t.forEach((r,t)=>{var o=e[t],a=r.getter,i=r.getterContext,s=e[t+n],u=r.setter,c=r.setterContext;r.read=(e=>o.fromWireType(a(i,e))),r.write=((e,r)=>{var t=[];u(c,e,s.toWireType(t,r)),ke(t)})}),[{name:r.name,fromWireType:function(e){for(var r=new Array(n),o=0;o>a])},destructorFunction:null})},e:function(e,r,t,n,o,i,s,u,c,l,f,d,p){f=Ue(f),i=kr(o,i),u&&(u=kr(s,u)),l&&(l=kr(c,l)),p=kr(d,p);var h=Fe(f);dr(h,function(){Cr("Cannot construct "+f+" due to unbound types",[n])}),xe([e,r,t],n?[n]:[],function(r){var t,o;r=r[0],o=n?(t=r.registeredClass).instancePrototype:lr.prototype;var s=$e(h,function(){if(Object.getPrototypeOf(this)!==c)throw new We("Use 'new' to construct "+f);if(void 0===d.constructor_body)throw new We(f+" has no accessible constructor");var e=d.constructor_body[arguments.length];if(void 0===e)throw new We("Tried to invoke ctor of "+f+" with invalid number of parameters ("+arguments.length+") - expected ("+Object.keys(d.constructor_body).toString()+") parameters instead!");return e.apply(this,arguments)}),c=Object.create(o,{constructor:{value:s}});s.prototype=c;var d=new function(e,r,t,n,o,a,i,s){this.name=e,this.constructor=r,this.instancePrototype=t,this.rawDestructor=n,this.baseClass=o,this.getActualType=a,this.upcast=i,this.downcast=s,this.pureVirtualFunctions=[]}(f,s,c,p,t,i,u,l),m=new Er(f,d,!0,!1,!1),v=new Er(f+"*",d,!1,!1,!1),w=new Er(f+" const*",d,!1,!0,!1);return Xe[e]={pointerType:v,constPointerType:w},function(e,r,t){a.hasOwnProperty(e)||je("Replacing nonexistant public symbol"),void 0!==a[e].overloadTable&&void 0!==t?a[e].overloadTable[t]=r:(a[e]=r,a[e].argCount=t)}(h,s),[m,v,w]})},f:function(e,r,t,n,o,a,i){var s=Ar(t,n);r=Ue(r),a=kr(o,a),xe([],[e],function(e){var n=(e=e[0]).name+"."+r;function o(){Cr("Cannot call "+n+" due to unbound types",s)}r.startsWith("@@")&&(r=Symbol[r.substring(2)]);var u=e.registeredClass.constructor;return void 0===u[r]?(o.argCount=t-1,u[r]=o):(fr(u,r,n),u[r].overloadTable[t-1]=o),xe([],s,function(e){var o=[e[0],null].concat(e.slice(1)),s=Dr(n,o,null,a,i);return void 0===u[r].overloadTable?(s.argCount=t-1,u[r]=s):u[r].overloadTable[t-1]=s,[]}),[]})},g:function(e,r,t,n,o,a){C(r>0);var i=Ar(r,t);o=kr(n,o),xe([],[e],function(e){var t="constructor "+(e=e[0]).name;if(void 0===e.registeredClass.constructor_body&&(e.registeredClass.constructor_body=[]),void 0!==e.registeredClass.constructor_body[r-1])throw new We("Cannot register multiple constructors with identical number of parameters ("+(r-1)+") for class '"+e.name+"'! Overload resolution is currently only performed using the parameter count, not actual type info!");return e.registeredClass.constructor_body[r-1]=(()=>{Cr("Cannot construct "+e.name+" due to unbound types",i)}),xe([],i,function(n){return n.splice(1,0,null),e.registeredClass.constructor_body[r-1]=Dr(t,n,null,o,a),[]}),[]})},b:function(e,r,t,n,o,a,i,s){var u=Ar(t,n);r=Ue(r),a=kr(o,a),xe([],[e],function(e){var n=(e=e[0]).name+"."+r;function o(){Cr("Cannot call "+n+" due to unbound types",u)}r.startsWith("@@")&&(r=Symbol[r.substring(2)]),s&&e.registeredClass.pureVirtualFunctions.push(r);var c=e.registeredClass.instancePrototype,l=c[r];return void 0===l||void 0===l.overloadTable&&l.className!==e.name&&l.argCount===t-2?(o.argCount=t-2,o.className=e.name,c[r]=o):(fr(c,r,n),c[r].overloadTable[t-2]=o),xe([],u,function(o){var s=Dr(n,o,e,a,i);return void 0===c[r].overloadTable?(s.argCount=t-2,c[r]=s):c[r].overloadTable[t-2]=s,[]}),[]})},a:function(e,r,t,n,o,a,i,s,u,c){r=Ue(r),o=kr(n,o),xe([],[e],function(e){var n=(e=e[0]).name+"."+r,l={get:function(){Cr("Cannot access "+n+" due to unbound types",[t,i])},enumerable:!0,configurable:!0};return l.set=u?()=>{Cr("Cannot access "+n+" due to unbound types",[t,i])}:e=>{Be(n+" is a read-only property")},Object.defineProperty(e.registeredClass.instancePrototype,r,l),xe([],u?[t,i]:[t],function(t){var i=t[0],l={get:function(){var r=Fr(this,e,n+" getter");return i.fromWireType(o(a,r))},enumerable:!0};if(u){u=kr(s,u);var f=t[1];l.set=function(r){var t=Fr(this,e,n+" setter"),o=[];u(c,t,f.toWireType(o,r)),ke(o)}}return Object.defineProperty(e.registeredClass.instancePrototype,r,l),[]}),[]})},fa:function(e,r){Le(e,{name:r=Ue(r),fromWireType:function(e){var r=Rr.toValue(e);return Or(e),r},toWireType:function(e,r){return Rr.toHandle(r)},argPackAdvance:8,readValueFromPointer:Te,destructorFunction:null})},i:function(e,r,t,n){var o=Ne(t);function a(){}r=Ue(r),a.values={},Le(e,{name:r,constructor:a,fromWireType:function(e){return this.constructor.values[e]},toWireType:function(e,r){return r.value},argPackAdvance:8,readValueFromPointer:function(e,r,t){switch(r){case 0:return function(e){var r=t?S:D;return this.fromWireType(r[e])};case 1:return function(e){var r=t?A:F;return this.fromWireType(r[e>>1])};case 2:return function(e){var r=t?$:M;return this.fromWireType(r[e>>2])};default:throw new TypeError("Unknown integer type: "+e)}}(r,o,n),destructorFunction:null}),dr(r,a)},d:function(e,r,t){var n=Nr(e,"enum");r=Ue(r);var o=n.constructor,a=Object.create(n.constructor.prototype,{value:{value:t},constructor:{value:$e(n.name+"_"+r,function(){})}});o.values[t]=a,o[r]=a},M:function(e,r,t){var n=Ne(t);Le(e,{name:r=Ue(r),fromWireType:function(e){return e},toWireType:function(e,r){return r},argPackAdvance:8,readValueFromPointer:function(e,r){switch(r){case 2:return function(e){return this.fromWireType(O[e>>2])};case 3:return function(e){return this.fromWireType(j[e>>3])};default:throw new TypeError("Unknown float type: "+e)}}(r,n),destructorFunction:null})},p:function(e,r,t,n,o){r=Ue(r),-1===o&&(o=4294967295);var a=Ne(t),i=e=>e;if(0===n){var s=32-8*t;i=(e=>e<>>s)}var u=r.includes("unsigned");Le(e,{name:r,fromWireType:i,toWireType:u?function(e,r){return this.name,r>>>0}:function(e,r){return this.name,r},argPackAdvance:8,readValueFromPointer:function(e,r,t){switch(r){case 0:return t?function(e){return S[e]}:function(e){return D[e]};case 1:return t?function(e){return A[e>>1]}:function(e){return F[e>>1]};case 2:return t?function(e){return $[e>>2]}:function(e){return M[e>>2]};default:throw new TypeError("Unknown integer type: "+e)}}(r,a,0!==n),destructorFunction:null})},l:function(e,r,t){var n=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][r];function o(e){var r=M,t=r[e>>=2],o=r[e+1];return new n(r.buffer,o,t)}Le(e,{name:t=Ue(t),fromWireType:o,argPackAdvance:8,readValueFromPointer:o},{ignoreDuplicateRegistrations:!0})},L:function(e,r){var t="std::string"===(r=Ue(r));Le(e,{name:r,fromWireType:function(e){var r,n=M[e>>2],o=e+4;if(t)for(var a=o,i=0;i<=n;++i){var s=o+i;if(i==n||0==D[s]){var u=N(a,s-a);void 0===r?r=u:(r+=String.fromCharCode(0),r+=u),a=s+1}}else{var c=new Array(n);for(i=0;i>2]=n,t&&o)z(r,D,i,n+1);else if(o)for(var s=0;s255&&(ft(i),Be("String has UTF-16 code units that do not fit in 8 bits")),D[i+s]=u}else for(s=0;sF),s=1):4===r&&(n=Ir,o=Hr,i=Vr,a=(()=>M),s=2),Le(e,{name:t,fromWireType:function(e){for(var t,o=M[e>>2],i=a(),u=e+4,c=0;c<=o;++c){var l=e+4+c*r;if(c==o||0==i[l>>s]){var f=n(u,l-u);void 0===t?t=f:(t+=String.fromCharCode(0),t+=f),u=l+r}}return ft(e),t},toWireType:function(e,n){"string"!=typeof n&&Be("Cannot pass non-string to C++ string type "+t);var a=i(n),u=lt(4+a+r);return M[u>>2]=a>>s,o(n,u+4,a+r),null!==e&&e.push(ft,u),u},argPackAdvance:8,readValueFromPointer:Te,destructorFunction:function(e){ft(e)}})},q:function(e,r,t,n,o,a){_e[e]={name:Ue(r),rawConstructor:kr(t,n),rawDestructor:kr(o,a),elements:[]}},ia:function(e,r,t,n,o,a,i,s,u){_e[e].elements.push({getterReturnType:r,getter:kr(t,n),getterContext:o,setterArgumentType:a,setter:kr(i,s),setterContext:u})},ja:function(e,r,t,n,o,a){Re[e]={name:Ue(r),rawConstructor:kr(t,n),rawDestructor:kr(o,a),fields:[]}},N:function(e,r,t,n,o,a,i,s,u,c){Re[e].fields.push({fieldName:Ue(r),getterReturnType:t,getter:kr(n,o),getterContext:a,setterArgumentType:i,setter:kr(s,u),setterContext:c})},ha:function(e,r){Le(e,{isVoid:!0,name:r=Ue(r),argPackAdvance:0,fromWireType:function(){},toWireType:function(e,r){}})},t:function(e,r,t){e=Rr.toValue(e),r=Nr(r,"emval::as");var n=[],o=Rr.toHandle(n);return M[t>>2]=o,r.toWireType(n,e)},la:function(e,r,t,n,o){return(e=Xr[e])(r=Rr.toValue(r),t=Gr(t),function(e){var r=[];return M[e>>2]=Rr.toHandle(r),r}(n),o)},P:function(e,r,t,n){(e=Xr[e])(r=Rr.toValue(r),t=Gr(t),null,n)},c:Or,Q:function(e,r){return(e=Rr.toValue(e))==(r=Rr.toValue(r))},y:function(e){return 0===e?Rr.toHandle(Yr()):(e=Gr(e),Rr.toHandle(Yr()[e]))},C:function(e,r){var t=function(e,r){for(var t=new Array(e),n=0;n>2],"parameter "+n);return t}(e,r),n=t[0],o=n.name+"_$"+t.slice(1).map(function(e){return e.name}).join("_")+"$",a=Kr[o];if(void 0!==a)return a;for(var i=["retType"],s=[n],u="",c=0;c4&&(Mr[e].refcount+=1)},D:function(e,r){return(e=Rr.toValue(e))instanceof(r=Rr.toValue(r))},na:function(e){return"number"==typeof(e=Rr.toValue(e))},ma:function(e){return"string"==typeof(e=Rr.toValue(e))},O:function(e,r,t,n){e=Rr.toValue(e);var o=Zr[r];return o||(o=function(e){for(var r="",t=0;t>2)], 'parameter "+t+"');\nvar arg"+t+" = argType"+t+".readValueFromPointer(args);\nargs += argType"+t+"['argPackAdvance'];\nargTypes += 4;\n";return n+="var obj = new constructor("+r+");\nreturn valueToHandle(obj);\n}\n",new Function("requireRegisteredType","Module","valueToHandle","getMemory",n)(Nr,a,Rr.toHandle,()=>M)}(r),Zr[r]=o),o(e,t,n)},n:function(){return Rr.toHandle([])},u:function(e){return Rr.toHandle(Gr(e))},k:function(){return Rr.toHandle({})},s:function(e){ke(Rr.toValue(e)),Or(e)},j:function(e,r,t){e=Rr.toValue(e),r=Rr.toValue(r),t=Rr.toValue(t),e[r]=t},h:function(e,r){var t=(e=Nr(e,"_emval_take_value")).readValueFromPointer(r);return Rr.toHandle(t)},aa:function(e,r){var t=new Date(1e3*Jr(e));$[r>>2]=t.getUTCSeconds(),$[r+4>>2]=t.getUTCMinutes(),$[r+8>>2]=t.getUTCHours(),$[r+12>>2]=t.getUTCDate(),$[r+16>>2]=t.getUTCMonth(),$[r+20>>2]=t.getUTCFullYear()-1900,$[r+24>>2]=t.getUTCDay();var n=Date.UTC(t.getUTCFullYear(),0,1,0,0,0,0),o=(t.getTime()-n)/864e5|0;$[r+28>>2]=o},ba:function(e,r){var t=new Date(1e3*Jr(e));$[r>>2]=t.getSeconds(),$[r+4>>2]=t.getMinutes(),$[r+8>>2]=t.getHours(),$[r+12>>2]=t.getDate(),$[r+16>>2]=t.getMonth(),$[r+20>>2]=t.getFullYear()-1900,$[r+24>>2]=t.getDay();var n=0|tt(t);$[r+28>>2]=n,$[r+36>>2]=-60*t.getTimezoneOffset();var o=new Date(t.getFullYear(),0,1),a=new Date(t.getFullYear(),6,1).getTimezoneOffset(),i=o.getTimezoneOffset(),s=0|(a!=i&&t.getTimezoneOffset()==Math.min(i,a));$[r+32>>2]=s},ca:function(e){var r=new Date($[e+20>>2]+1900,$[e+16>>2],$[e+12>>2],$[e+8>>2],$[e+4>>2],$[e>>2],0),t=$[e+32>>2],n=r.getTimezoneOffset(),o=new Date(r.getFullYear(),0,1),a=new Date(r.getFullYear(),6,1).getTimezoneOffset(),i=o.getTimezoneOffset(),s=Math.min(i,a);if(t<0)$[e+32>>2]=Number(a!=i&&s==n);else if(t>0!=(s==n)){var u=Math.max(i,a),c=t>0?s:u;r.setTime(r.getTime()+6e4*(c-n))}$[e+24>>2]=r.getDay();var l=0|tt(r);return $[e+28>>2]=l,$[e>>2]=r.getSeconds(),$[e+4>>2]=r.getMinutes(),$[e+8>>2]=r.getHours(),$[e+12>>2]=r.getDate(),$[e+16>>2]=r.getMonth(),$[e+20>>2]=r.getYear(),r.getTime()/1e3|0},da:function(e,r,t){var n=(new Date).getFullYear(),o=new Date(n,0,1),a=new Date(n,6,1),i=o.getTimezoneOffset(),s=a.getTimezoneOffset(),u=Math.max(i,s);function c(e){var r=e.toTimeString().match(/\(([A-Za-z ]+)\)$/);return r?r[1]:"GMT"}M[e>>2]=60*u,$[r>>2]=Number(i!=s);var l=c(o),f=c(a),d=nt(l),p=nt(f);s>2]=d,M[t+4>>2]=p):(M[t>>2]=p,M[t+4>>2]=d)},z:function(){Z("")},I:function(){return Date.now()},H:Qr,V:function(e){var r=D.length;if((e>>>=0)>2147483648)return!1;let t=(e,r)=>e+(r-e%r)%r;for(var n=1;n<=4;n*=2){var o=r*(1+.2/n);if(o=Math.min(o,e+100663296),ot(Math.min(2147483648,t(Math.max(e,o),65536))))return!0}return!1},_:function(e,r){var t=0;return it().forEach(function(n,o){var a=r+t;M[e+4*o>>2]=a,function(e,r,t){for(var n=0;n>0]=e.charCodeAt(n);t||(S[r>>0]=0)}(n,a),t+=n.length+1}),0},$:function(e,r){var t=it();M[e>>2]=t.length;var n=0;return t.forEach(function(e){n+=e.length+1}),M[r>>2]=n,0},x:function(e){try{var r=Ee.getStreamFromFD(e);return he.close(r),0}catch(e){if(void 0===he||!(e instanceof he.ErrnoError))throw e;return e.errno}},J:function(e,r,t,n){try{var o=function(e,r,t,n){for(var o=0,a=0;a>2],s=M[r+4>>2];r+=8;var u=he.read(e,S,i,s,n);if(u<0)return-1;if(o+=u,u>2]=o,0}catch(e){if(void 0===he||!(e instanceof he.ErrnoError))throw e;return e.errno}},R:function(e,r,t,n,o){try{var a=be(r,t);if(isNaN(a))return 61;var i=Ee.getStreamFromFD(e);return he.llseek(i,a,n),re=[i.position>>>0,(ee=i.position,+Math.abs(ee)>=1?ee>0?(0|Math.min(+Math.floor(ee/4294967296),4294967295))>>>0:~~+Math.ceil((ee-+(~~ee>>>0))/4294967296)>>>0:0)],$[o>>2]=re[0],$[o+4>>2]=re[1],i.getdents&&0===a&&0===n&&(i.getdents=null),0}catch(e){if(void 0===he||!(e instanceof he.ErrnoError))throw e;return e.errno}},A:function(e,r,t,n){try{var o=function(e,r,t,n){for(var o=0,a=0;a>2],s=M[r+4>>2];r+=8;var u=he.write(e,S,i,s,n);if(u<0)return-1;o+=u,void 0!==n&&(n+=u)}return o}(Ee.getStreamFromFD(e),r,t);return M[n>>2]=o,0}catch(e){if(void 0===he||!(e instanceof he.ErrnoError))throw e;return e.errno}}},lt=(function(){var e={a:ct};function r(e,r){var t,n=e.exports;a.asm=n,k=a.asm.oa,W(),B=a.asm.qa,t=a.asm.pa,I.unshift(t),K()}function t(e){r(e.instance)}function o(r){return function(){if(!b&&(d||p)){if("function"==typeof fetch&&!oe(J))return fetch(J,{credentials:"same-origin"}).then(function(e){if(!e.ok)throw"failed to load wasm binary file at '"+J+"'";return e.arrayBuffer()}).catch(function(){return ae(J)});if(s)return new Promise(function(e,r){s(J,function(r){e(new Uint8Array(r))},r)})}return Promise.resolve().then(function(){return ae(J)})}().then(function(r){return WebAssembly.instantiate(r,e)}).then(function(e){return e}).then(r,function(e){E("failed to asynchronously prepare wasm: "+e),Z(e)})}if(Y(),a.instantiateWasm)try{return a.instantiateWasm(e,r)}catch(e){E("Module.instantiateWasm callback failed with error: "+e),n(e)}(b||"function"!=typeof WebAssembly.instantiateStreaming||ne(J)||oe(J)||h||"function"!=typeof fetch?o(t):fetch(J,{credentials:"same-origin"}).then(function(r){return WebAssembly.instantiateStreaming(r,e).then(t,function(e){return E("wasm streaming compile failed: "+e),E("falling back to ArrayBuffer instantiation"),o(t)})})).catch(n)}(),a.___wasm_call_ctors=function(){return(a.___wasm_call_ctors=a.asm.pa).apply(null,arguments)},a._malloc=function(){return(lt=a._malloc=a.asm.ra).apply(null,arguments)}),ft=a._free=function(){return(ft=a._free=a.asm.sa).apply(null,arguments)},dt=a.___errno_location=function(){return(dt=a.___errno_location=a.asm.ta).apply(null,arguments)},pt=a.___getTypeName=function(){return(pt=a.___getTypeName=a.asm.ua).apply(null,arguments)},ht=(a.__embind_initialize_bindings=function(){return(a.__embind_initialize_bindings=a.asm.va).apply(null,arguments)},a._htons=function(){return(ht=a._htons=a.asm.wa).apply(null,arguments)}),mt=a._ntohs=function(){return(mt=a._ntohs=a.asm.xa).apply(null,arguments)},vt=a.___cxa_is_pointer_type=function(){return(vt=a.___cxa_is_pointer_type=a.asm.ya).apply(null,arguments)};a.dynCall_ji=function(){return(a.dynCall_ji=a.asm.za).apply(null,arguments)},a.dynCall_vij=function(){return(a.dynCall_vij=a.asm.Aa).apply(null,arguments)},a.dynCall_jiji=function(){return(a.dynCall_jiji=a.asm.Ba).apply(null,arguments)};function wt(e){function r(){ut||(ut=!0,a.calledRun=!0,P||(!0,me.root=he.mount(me,{},null),a.noFSInit||he.init.initialized||he.init(),he.ignorePermissions=!1,fe.init(),se(I),t(a),a.onRuntimeInitialized&&a.onRuntimeInitialized(),function(){if(a.postRun)for("function"==typeof a.postRun&&(a.postRun=[a.postRun]);a.postRun.length;)e=a.postRun.shift(),H.unshift(e);var e;se(H)}()))}e=e||l,V>0||(!function(){if(a.preRun)for("function"==typeof a.preRun&&(a.preRun=[a.preRun]);a.preRun.length;)e=a.preRun.shift(),L.unshift(e);var e;se(L)}(),V>0||(a.setStatus?(a.setStatus("Running..."),setTimeout(function(){setTimeout(function(){a.setStatus("")},1),r()},1)):r()))}if(G=function e(){ut||wt(),ut||(G=e)},a.preInit)for("function"==typeof a.preInit&&(a.preInit=[a.preInit]);a.preInit.length>0;)a.preInit.pop()();return wt(),o.ready}})();export default rhino3dm; \ No newline at end of file diff --git a/public/assets/lib/vendor/three/rhino3dm/rhino3dm.wasm b/public/assets/lib/vendor/three/rhino3dm/rhino3dm.wasm deleted file mode 100644 index de621362..00000000 Binary files a/public/assets/lib/vendor/three/rhino3dm/rhino3dm.wasm and /dev/null differ diff --git a/public/assets/model/plugin.js b/public/assets/model/plugin.js new file mode 100644 index 00000000..8d49305d --- /dev/null +++ b/public/assets/model/plugin.js @@ -0,0 +1,28 @@ +import rxjs from "../lib/rx.js"; +import ajax from "../lib/ajax.js"; + +const plugin$ = ajax({ + url: "api/plugin", + method: "GET", + responseType: "json", +}).pipe( + rxjs.map(({ responseJSON }) => responseJSON.result), +); + +let plugins = {}; + +export async function init() { + plugins = await plugin$.toPromise(); +} + +export function get(mime) { + return plugins[mime]; +} + +export async function load(mime) { + const specs = plugins[mime]; + if (!specs) return null; + const [_, url] = specs; + const module = await import(url); + return module.default; +} diff --git a/public/assets/pages/viewerpage/application_3d.js b/public/assets/pages/viewerpage/application_3d.js index 2f421a65..6be4fa45 100644 --- a/public/assets/pages/viewerpage/application_3d.js +++ b/public/assets/pages/viewerpage/application_3d.js @@ -1,6 +1,7 @@ import { createElement, createRender, nop } from "../../lib/skeleton/index.js"; import rxjs, { effect } from "../../lib/rx.js"; import { qs } from "../../lib/dom.js"; +import { load as loadPlugin } from "../../model/plugin.js"; import { loadCSS } from "../../helpers/loader.js"; import { createLoader } from "../../components/loader.js"; import ctrlError from "../ctrl_error.js"; @@ -8,11 +9,19 @@ import ctrlError from "../ctrl_error.js"; import componentDownloader, { init as initDownloader } from "./application_downloader.js"; import { renderMenubar, buttonDownload } from "./component_menubar.js"; -import setup3D, { getLoader, is2D } from "./application_3d/init.js"; +import * as THREE from "../../../lib/vendor/three/three.module.js"; +import setup3D from "./application_3d/init.js"; import withLight from "./application_3d/scene_light.js"; import withCube from "./application_3d/scene_cube.js"; import ctrlToolbar from "./application_3d/toolbar.js"; +class I3DLoader { + constructor() {} + load() { throw new Error("NOT_IMPLEMENTED"); } + transform() { throw new Error("NOT_IMPLEMENTED"); } + is2D() { return false; } +} + export default async function(render, { mime, acl$, getDownloadUrl = nop, getFilename = nop, hasCube = true, hasMenubar = true }) { const $page = createElement(`
@@ -33,38 +42,44 @@ export default async function(render, { mime, acl$, getDownloadUrl = nop, getFil const $toolbar = qs($page, ".toolbar"); const removeLoader = createLoader($draw); - await effect(rxjs.of(getLoader(mime)).pipe( - rxjs.mergeMap(([loader, createMesh]) => { + await effect(rxjs.from(loadPlugin(mime)).pipe( + rxjs.mergeMap(async (loader) => { if (!loader) { componentDownloader(render, { mime, acl$, getFilename, getDownloadUrl }); return rxjs.EMPTY; } - return rxjs.of([loader, createMesh]); + return new (await loader(I3DLoader, { THREE }))(); }), - rxjs.mergeMap(([loader, createMesh]) => new rxjs.Observable((observer) => loader.load( + rxjs.mergeMap((loader) => new rxjs.Observable((observer) => loader.load( getDownloadUrl(), - (object) => observer.next(createMesh(object)), + (object) => observer.next(loader.transform(object)), null, (err) => observer.error(err), - ))), - removeLoader, - rxjs.mergeMap((mesh) => create3DScene({ mesh, $draw, $toolbar, $menubar, hasCube, mime })), + )).pipe( + removeLoader, + rxjs.mergeMap((mesh) => create3DScene({ + mesh, + $draw, $toolbar, $menubar, + hasCube, mime, is2D: loader.is2D, + })), + )), rxjs.catchError(ctrlError()), )); } -function create3DScene({ mesh, $draw, $toolbar, $menubar, hasCube, mime }) { +function create3DScene({ mesh, $draw, $toolbar, $menubar, hasCube, is2D }) { const refresh = []; const { renderer, camera, scene, controls, box } = setup3D({ + THREE, $page: $draw, mesh, refresh, $menubar, - mime, + is2D, }); withLight({ scene, box }); - if (hasCube && !is2D(mime)) withCube({ camera, renderer, refresh, controls }); + if (hasCube && !is2D()) withCube({ camera, renderer, refresh, controls }); ctrlToolbar(createRender($toolbar), { mesh, controls, @@ -72,6 +87,7 @@ function create3DScene({ mesh, $draw, $toolbar, $menubar, hasCube, mime }) { refresh, $menubar, $toolbar, + is2D, }); return rxjs.animationFrames().pipe(rxjs.tap(() => { diff --git a/public/assets/pages/viewerpage/application_3d/init.js b/public/assets/pages/viewerpage/application_3d/init.js index dc89b387..8d163d6c 100644 --- a/public/assets/pages/viewerpage/application_3d/init.js +++ b/public/assets/pages/viewerpage/application_3d/init.js @@ -1,18 +1,7 @@ import { createElement, onDestroy } from "../../../lib/skeleton/index.js"; -import { join } from "../../../lib/path.js"; +import { OrbitControls } from "../../../../lib/vendor/three/OrbitControls.js"; -import * as THREE from "../../../lib/vendor/three/three.module.js"; -import { OrbitControls } from "../../../lib/vendor/three/OrbitControls.js"; - -import { toCreasedNormals } from "../../../lib/vendor/three/utils/BufferGeometryUtils.js"; -import { GLTFLoader } from "../../../lib/vendor/three/GLTFLoader.js"; -import { OBJLoader } from "../../../lib/vendor/three/OBJLoader.js"; -import { STLLoader } from "../../../lib/vendor/three/STLLoader.js"; -import { FBXLoader } from "../../../lib/vendor/three/FBXLoader.js"; -import { SVGLoader } from "../../../lib/vendor/three/SVGLoader.js"; -import { Rhino3dmLoader } from "../../../lib/vendor/three/3DMLoader.js"; - -export default function({ $page, $menubar, mesh, refresh, mime }) { +export default function({ THREE, $page, $menubar, mesh, refresh, is2D }) { // setup the dom const renderer = new THREE.WebGLRenderer({ antialias: true, shadowMapEnabled: true }); renderer.shadowMap.enabled = true; @@ -39,7 +28,7 @@ export default function({ $page, $menubar, mesh, refresh, mime }) { ); const controls = new OrbitControls(camera, renderer.domElement); controls.zoomToCursor = true; - if (is2D(mime)) { + if (is2D()) { controls.enableRotate = false; controls.mouseButtons = { LEFT: THREE.MOUSE.PAN, @@ -51,7 +40,7 @@ export default function({ $page, $menubar, mesh, refresh, mime }) { scene.add(mesh); mesh.castShadow = true; mesh.receiveShadow = true; - camera.position.set(center.x, center.y, center.z + maxDim * (is2D(mime) ? 1.3 : 1.8)); + camera.position.set(center.x, center.y, center.z + maxDim * (is2D() ? 1.3 : 1.8)); controls.target.copy(center); const mixer = new THREE.AnimationMixer(mesh); @@ -89,118 +78,3 @@ export default function({ $page, $menubar, mesh, refresh, mime }) { return { renderer, scene, camera, controls, box }; } - -export function is2D(mime) { - return ["image/svg+xml", "application/acad"].indexOf(mime) !== -1; -} - -export function getLoader(mime) { - const identity = (s) => s; - switch (mime) { - case "application/object": - return [ - new OBJLoader(), - (obj) => { - obj.name = "All"; - obj.traverse((child) => { - if (child.isMesh) { - child.material = new THREE.MeshPhongMaterial({ - color: 0x40464b, - emissive: 0x40464b, - specular: 0xf9f9fa, - shininess: 10, - transparent: true, - }); - // smooth the edges: https://discourse.threejs.org/t/how-to-smooth-an-obj-with-threejs/3950/16 - child.geometry = toCreasedNormals(child.geometry, (30 / 180) * Math.PI); - } - }); - return obj; - }, - ]; - case "model/3dm": - THREE.Object3D.DEFAULT_UP.set(0, 0, 1); - const loader = new Rhino3dmLoader(); - loader.setLibraryPath(join(import.meta.url, "../../../lib/vendor/three/rhino3dm/")); - return [loader, identity]; - case "model/gtlt-binary": - case "model/gltf+json": - return [new GLTFLoader(), (gltf) => gltf.scene]; - case "model/stl": - return [new STLLoader(), (geometry) => { - const material = new THREE.MeshPhongMaterial({ - emissive: 0x40464b, - specular: 0xf9f9fa, - shininess: 15, - transparent: true, - }); - if (geometry.hasColors) material.vertexColors = true; - else material.color = material.emissive; - return new THREE.Mesh(geometry, material); - }]; - case "image/svg+xml": - const createMaterial = (color, opacity = 1) => new THREE.MeshBasicMaterial({ - color: new THREE.Color().setStyle(color), - opacity, - transparent: true, - side: THREE.DoubleSide, - depthWrite: false, - wireframe: false, - }); - const threecolor = (color) => { - if (color && color.substr && color.substr(0, 4) === "RGB(") { - function componentToHex(c) { - const hex = c.toString(16); - return hex.length === 1 ? "0" + hex : hex; - } - const [r, g, b] = color.replace(/^RGB\(/, "").replace(/\)/, "").split(",").map((i) => parseInt(i)); - return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b); - } - return color; - }; - return [new SVGLoader(), (data) => { - const group = new THREE.Group(); - group.name = "All"; - group.scale.y *= -1; - let renderOrder = 0; - for (const path of data.paths) { - const fillColor = threecolor(path.userData.style.fill); - if (fillColor !== undefined && fillColor !== "none") { - const material = createMaterial( - fillColor, - path.userData.style.fillOpacity, - ); - const shapes = SVGLoader.createShapes(path); - for (const shape of shapes) { - const mesh = new THREE.Mesh( - new THREE.ShapeGeometry(shape), - material, - ); - mesh.renderOrder = renderOrder++; - group.add(mesh); - } - } - const strokeColor = threecolor(path.userData.style.stroke); - if (strokeColor !== undefined && strokeColor !== "none") { - const material = createMaterial(strokeColor); - for (const subPath of path.subPaths) { - const geometry = SVGLoader.pointsToStroke(subPath.getPoints(), path.userData.style); - if (geometry) { - const mesh = new THREE.Mesh(geometry, material); - mesh.renderOrder = renderOrder++; - group.add(mesh); - } - } - } - } - return group; - }]; - case "application/fbx": - return [new FBXLoader(), (obj) => { - obj.name = "All"; - return obj; - }]; - default: - return [null, null]; - } -} diff --git a/public/assets/pages/viewerpage/application_3d/scene_cube.js b/public/assets/pages/viewerpage/application_3d/scene_cube.js index 4f428005..b3bc8af0 100644 --- a/public/assets/pages/viewerpage/application_3d/scene_cube.js +++ b/public/assets/pages/viewerpage/application_3d/scene_cube.js @@ -1,5 +1,5 @@ import { onDestroy } from "../../../lib/skeleton/index.js"; -import { ViewCubeGizmo, SimpleCameraControls, ObjectPosition } from "../../../lib/vendor/three/viewcube.js"; +import { ViewCubeGizmo, SimpleCameraControls, ObjectPosition } from "../../../../lib/vendor/three/viewcube.js"; export default function({ camera, renderer, refresh, controls }) { const viewCubeGizmo = new ViewCubeGizmo(camera, renderer, { diff --git a/public/assets/pages/viewerpage/application_3d/scene_light.js b/public/assets/pages/viewerpage/application_3d/scene_light.js index 85fb8385..06b22ca0 100644 --- a/public/assets/pages/viewerpage/application_3d/scene_light.js +++ b/public/assets/pages/viewerpage/application_3d/scene_light.js @@ -1,5 +1,5 @@ import { settings_get } from "../../../lib/settings.js"; -import * as THREE from "../../../lib/vendor/three/three.module.js"; +import * as THREE from "../../../../lib/vendor/three/three.module.js"; const LIGHT_COLOR = 0xf5f5f5; diff --git a/public/assets/pages/viewerpage/application_3d/toolbar.js b/public/assets/pages/viewerpage/application_3d/toolbar.js index 50a49c4b..3d5050fb 100644 --- a/public/assets/pages/viewerpage/application_3d/toolbar.js +++ b/public/assets/pages/viewerpage/application_3d/toolbar.js @@ -1,8 +1,8 @@ import { createElement } from "../../../lib/skeleton/index.js"; import { qs } from "../../../lib/dom.js"; -import * as THREE from "../../../lib/vendor/three/three.module.js"; +import * as THREE from "../../../../lib/vendor/three/three.module.js"; -export default function(render, { camera, controls, mesh, $menubar, $toolbar }) { +export default function(render, { camera, controls, mesh, $menubar, $toolbar, is2D }) { if (mesh.children.length <= 1) return; $menubar.add(buttonLayers({ $toolbar })); @@ -10,7 +10,7 @@ export default function(render, { camera, controls, mesh, $menubar, $toolbar }) document.createDocumentFragment(), mesh, 0, - { camera, controls } + { camera, controls, is2D } )); } @@ -25,13 +25,15 @@ function createChild($fragment, mesh, child = 0, opts) { buildDOM($fragment, mesh, child, opts); if (mesh.children.length > 0 && child < 4) { for (let i=0; i
@@ -43,7 +45,8 @@ function buildDOM($fragment, child, left, { camera, controls }) { `); qs($label, "input").onchange = () => child.visible = !child.visible; $label.onclick = async(e) => { - if (e.target.nodeName === "INPUT" || e.target.classList.contains("component_checkbox")) return; + if (is2D()) return; + else if (e.target.nodeName === "INPUT" || e.target.classList.contains("component_checkbox")) return; e.preventDefault(); e.stopPropagation(); getRootObject(child).traverse((c) => { if (!c.material) return; diff --git a/public/assets/pages/viewerpage/application_table.js b/public/assets/pages/viewerpage/application_table.js index 7b772dc4..80a4995b 100644 --- a/public/assets/pages/viewerpage/application_table.js +++ b/public/assets/pages/viewerpage/application_table.js @@ -4,12 +4,20 @@ import { qs, qsa } from "../../lib/dom.js"; import ajax from "../../lib/ajax.js"; import { loadCSS } from "../../helpers/loader.js"; import t from "../../locales/index.js"; +import { get as getPlugin } from "../../model/plugin.js"; import ctrlError from "../ctrl_error.js"; import { renderMenubar, buttonDownload } from "./component_menubar.js"; -import { getLoader } from "./application_table/loader.js"; import { transition } from "./common.js"; +const MAX_ROWS = 200; + +class ITable { + contructor() {} + getHeader() { throw new Error("NOT_IMPLEMENTED"); } + getBody() { throw new Error("NOT_IMPLEMENTED"); } +} + export default async function(render, { mime, getDownloadUrl = nop, getFilename = nop, hasMenubar = true }) { const $page = createElement(`
@@ -32,76 +40,51 @@ export default async function(render, { mime, getDownloadUrl = nop, getFilename tbody: qs($page, ".tbody"), }; const padding = 10; + const STATE = { + header: {}, + body: [], + rows: [], + }; // feature: initial render const init$ = ajax({ url: getDownloadUrl(), responseType: "arraybuffer" }).pipe( rxjs.mergeMap(async({ response }) => { - const table = new (await getLoader(mime))(response); + const loader = getPlugin(mime); + if (!loader) throw new TypeError(`unsupported mimetype "${mime}"`); + const [_, url] = loader; + const module = await import(url); + const table = new (await module.default(ITable))(response, { $menubar }); + STATE.header = table.getHeader(); + STATE.body = table.getBody(); + STATE.rows = STATE.body; - // build head - const $tr = createElement(`
`); - table.getHeader().forEach(({ name, size }) => { - const $th = createElement(` -
- ${name} - -
- `); - let ascending = null; - qs($th, "img").onclick = (e) => { - ascending = !ascending; - sortBy(qsa($dom.tbody, `.tr [data-column="${name}"]`), ascending); - qsa(e.target.closest(".tr"), "img").forEach(($img) => { - $img.style.transform = "rotate(0deg)"; - }); - if (ascending) e.target.style.transform = "rotate(180deg)"; - }; - $tr.appendChild($th); - }); - $dom.thead.appendChild($tr); - - // build body - const body = table.getBody(); - body.forEach((obj) => { - const $tr = createElement(`
`); - table.getHeader().forEach(({ name, size }) => { - $tr.appendChild(createElement(` -
- ${obj[name] || "-"} -
- `)); - }); - $dom.tbody.appendChild($tr); - }); - if (body.length === 0) $dom.tbody.appendChild(createElement(` -

- ${t("Empty")} -

- `)); - transition($dom.tbody.parentElement); + buildHead(STATE, $dom, padding); + buildRows(STATE.rows.slice(0, MAX_ROWS), STATE.header, $dom.tbody, padding, true, false); }), - rxjs.share(), rxjs.catchError(ctrlError()), + rxjs.share(), ); effect(init$); // feature: search const $search = createElement(``); - $menubar.add($search); - effect(rxjs.fromEvent($search, "keydown").pipe( - rxjs.debounceTime(200), + effect(init$.pipe( + rxjs.tap(() => $menubar.add($search)), + rxjs.mergeMap(() => rxjs.fromEvent($search, "keydown").pipe(rxjs.debounceTime(200))), rxjs.tap((e) => { - const terms = e.target.value.toLowerCase().split(" "); - qsa($page, ".table .tbody .tr").forEach(($row) => { - const str = $row.innerText.toLowerCase(); + const terms = e.target.value.toLowerCase().trim().split(" "); + $dom.tbody.scrollTo(0, 0); + if (terms === "") STATE.rows = STATE.body; + else STATE.rows = STATE.body.filter((row) => { + const line = Object.values(row).join("").toLowerCase(); for (let i=0; i $dom.tbody.scrollTo($dom.thead.scrollLeft, $dom.tbody.scrollTop)) )); + // feature: infinite scroll + effect(rxjs.fromEvent($dom.tbody, "scroll").pipe( + rxjs.mergeMap(async (e) => { + const scrollBottom = e.target.scrollHeight - (e.target.scrollTop + e.target.clientHeight); + if (scrollBottom > 0) return; + else if (STATE.rows.length <= MAX_ROWS) return; + else if (STATE.rows.length <= $dom.tbody.children.length) return; + + const current = $dom.tbody.children.length; + const newRows = STATE.rows.slice(current, current + 10); + buildRows(newRows, STATE.header, $dom.tbody, padding, false, false); + }), + )); + // feature: make the last column to always fit the viewport effect(rxjs.merge( init$, init$.pipe( rxjs.mergeMap(() => rxjs.fromEvent(window, "resize")), - rxjs.debounceTime(100), + rxjs.debounce((e) => e.debounce === false ? rxjs.of(null) : rxjs.timer(100)), ), ).pipe( rxjs.tap(() => resizeLastColumnIfNeeded({ @@ -140,6 +137,61 @@ export function init() { ]); } +async function buildRows(rows, legends, $tbody, padding, isInit, withClear) { + if (withClear) $tbody.innerHTML = ""; + for (let i=0; i
`); + legends.forEach(({ name, size }, i) => { + $tr.appendChild(createElement(` +
+ ${obj[name] || "-"} +
+ `)); + }); + $tbody.appendChild($tr); + } + $tbody.style.opacity = "0"; + if (rows.length === 0) $tbody.appendChild(createElement(` +

+ ${t("Empty")} +

+ `)); + if (!isInit) { + const e = new Event("resize"); + e.debounce = false; + window.dispatchEvent(e); + await new Promise(requestAnimationFrame); + } + $tbody.style.opacity = "1"; + if (isInit) transition($tbody.parentElement); +} + +function buildHead(STATE, $dom, padding) { + const $tr = createElement(`
`); + STATE.header.forEach(({ name, size }, i) => { + const $th = createElement(` +
+ ${name} + +
+ `); + let ascending = null; + qs($th, "img").onclick = (e) => { + ascending = !ascending; + STATE.rows = sortBy(STATE.rows, ascending, name); + qsa(e.target.closest(".tr"), "img").forEach(($img) => { + $img.style.transform = "rotate(0deg)"; + }); + if (ascending) e.target.style.transform = "rotate(180deg)"; + $dom.tbody.scrollTo(0, 0); + buildRows(STATE.rows.slice(0, MAX_ROWS), STATE.header, $dom.tbody, padding, false, true); + }; + $tr.appendChild($th); + }); + $dom.thead.appendChild($tr); +} + function styleCell(l, name, padding) { const maxSize = 40; const charSize = 7; @@ -148,8 +200,8 @@ function styleCell(l, name, padding) { return `width: ${sizeInChar*charSize+padding*2}px;`; } -function withCenter(className, fieldLength) { - if (fieldLength > 4) return className; +function withCenter(className, fieldLength, isLast) { + if (fieldLength > 4 || isLast) return className; return `${className} center`; } @@ -157,20 +209,17 @@ function resizeLastColumnIfNeeded({ $target, $childs, padding = 0 }) { const fullWidth = $target.clientWidth; let currWidth = 0; $childs.childNodes.forEach(($node) => currWidth += $node.clientWidth); - if (currWidth < fullWidth) { + if (currWidth < fullWidth && $childs.lastChild !== null) { const lastWidth = ($childs.lastChild.clientWidth - padding * 2) + fullWidth - currWidth; $childs.lastChild.setAttribute("style", `width: ${lastWidth}px`); } } -function sortBy($columns, ascending) { +function sortBy(rows, ascending, key) { const o = ascending ? 1 : -1; - const $new = [...$columns].sort(($el1, $el2) => { - if ($el1.innerText === $el2.innerText) return 0; - else if ($el1.innerText < $el2.innerText) return -o; + return rows.sort((a, b) => { + if (a[key] === b[key]) return 0; + else if (a[key] < b[key]) return -o return o; }); - const $root = $columns[0].parentElement.parentElement; - $root.innerHTML = ""; - $new.forEach(($node) => $root.appendChild($node.parentElement)); } diff --git a/public/assets/pages/viewerpage/application_table/Makefile b/public/assets/pages/viewerpage/application_table/Makefile deleted file mode 100644 index 9a7ddbc9..00000000 --- a/public/assets/pages/viewerpage/application_table/Makefile +++ /dev/null @@ -1,2 +0,0 @@ -all: - emcc loader_symbol.c -o loader_symbol.wasm -O2 --no-entry diff --git a/public/assets/pages/viewerpage/application_table/loader.js b/public/assets/pages/viewerpage/application_table/loader.js deleted file mode 100644 index 4a638d3e..00000000 --- a/public/assets/pages/viewerpage/application_table/loader.js +++ /dev/null @@ -1,24 +0,0 @@ -// import loaderDBase from "./loader_dbase.js"; -// import loaderSymbol from "./loader_symbol.js"; - -class ITable { - contructor() {} - getHeader() { throw new Error("NOT_IMPLEMENTED"); } - getBody() { throw new Error("NOT_IMPLEMENTED"); } -} - -export async function getLoader(mime) { - let module = null; - switch (mime) { - case "application/dbf": - module = await import("./loader_dbase.js"); - break; - case "application/x-archive": - module = await import("./loader_symbol.js"); - break; - default: - throw new TypeError(`unsupported mimetype '${mime}'`); - } - - return module.default(ITable); -} diff --git a/public/assets/pages/viewerpage/application_table/loader_dbase.js b/public/assets/pages/viewerpage/application_table/loader_dbase.js deleted file mode 100644 index d112b19e..00000000 --- a/public/assets/pages/viewerpage/application_table/loader_dbase.js +++ /dev/null @@ -1,26 +0,0 @@ -export default async function(ITable) { - const module = await import("../../../lib/vendor/shp-to-geojson.browser.js"); - - return class TableImpl extends ITable { - constructor(response) { - super(); - this.data = new module.DBase(module.Buffer.from(response)); - } - - getHeader() { - return this.data.properties.map(({ fieldName, fieldLength }) => ({ - name: fieldName, - size: fieldLength, - })); - } - - getBody() { - const body = []; - for (let i =0; i { + if (child.isMesh) { + child.material = new THREE.MeshPhongMaterial({ + color: 0x40464b, + emissive: 0x40464b, + specular: 0xf9f9fa, + shininess: 10, + transparent: true, + }); + // smooth the edges: https://discourse.threejs.org/t/how-to-smooth-an-obj-with-threejs/3950/16 + child.geometry = toCreasedNormals(child.geometry, (30 / 180) * Math.PI); + } + }); + return obj; + } + } +} diff --git a/server/plugin/plg_application_3d/index_stl.js b/server/plugin/plg_application_3d/index_stl.js new file mode 100644 index 00000000..e07cada2 --- /dev/null +++ b/server/plugin/plg_application_3d/index_stl.js @@ -0,0 +1,25 @@ +export default async function(I3D, { THREE }) { + const module = await import("./vendor/STLLoader.js"); + + return class Impl extends I3D { + constructor() { + super(); + } + + load(url, onLoad, onProgress, onError) { + return (new module.STLLoader()).load(url, onLoad, onProgress, onError); + } + + transform(geometry) { + const material = new THREE.MeshPhongMaterial({ + emissive: 0x40464b, + specular: 0xf9f9fa, + shininess: 15, + transparent: true, + }); + if (geometry.hasColors) material.vertexColors = true; + else material.color = material.emissive; + return new THREE.Mesh(geometry, material); + } + } +} diff --git a/server/plugin/plg_application_3d/index_svg.js b/server/plugin/plg_application_3d/index_svg.js new file mode 100644 index 00000000..b75e4ef2 --- /dev/null +++ b/server/plugin/plg_application_3d/index_svg.js @@ -0,0 +1,76 @@ +export default async function(I3D, { THREE }) { + const module = await import("./vendor/SVGLoader.js"); + + const threecolor = (color) => { + if (color && color.substr && color.substr(0, 4) === "RGB(") { + function componentToHex(c) { + const hex = c.toString(16); + return hex.length === 1 ? "0" + hex : hex; + } + const [r, g, b] = color.replace(/^RGB\(/, "").replace(/\)/, "").split(",").map((i) => parseInt(i)); + return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b); + } + return color; + }; + + const createMaterial = (color, opacity = 1) => new THREE.MeshBasicMaterial({ + color: new THREE.Color().setStyle(color), + opacity, + transparent: true, + side: THREE.DoubleSide, + depthWrite: false, + wireframe: false, + }); + + return class Impl extends I3D { + constructor() { + super(); + } + + load(url, onLoad, onProgress, onError) { + return (new module.SVGLoader()).load(url, onLoad, onProgress, onError); + } + + transform(data) { + const group = new THREE.Group(); + group.name = "All"; + group.scale.y *= -1; + let renderOrder = 0; + for (const path of data.paths) { + const fillColor = threecolor(path.userData.style.fill); + if (fillColor !== undefined && fillColor !== "none") { + const material = createMaterial( + fillColor, + path.userData.style.fillOpacity, + ); + const shapes = module.SVGLoader.createShapes(path); + for (const shape of shapes) { + const mesh = new THREE.Mesh( + new THREE.ShapeGeometry(shape), + material, + ); + mesh.renderOrder = renderOrder++; + group.add(mesh); + } + } + const strokeColor = threecolor(path.userData.style.stroke); + if (strokeColor !== undefined && strokeColor !== "none") { + const material = createMaterial(strokeColor); + for (const subPath of path.subPaths) { + const geometry = module.SVGLoader.pointsToStroke(subPath.getPoints(), path.userData.style); + if (geometry) { + const mesh = new THREE.Mesh(geometry, material); + mesh.renderOrder = renderOrder++; + group.add(mesh); + } + } + } + } + return group; + } + + is2D() { + return true; + } + } +} diff --git a/server/plugin/plg_application_3d/manifest.json b/server/plugin/plg_application_3d/manifest.json new file mode 100644 index 00000000..f2a785ef --- /dev/null +++ b/server/plugin/plg_application_3d/manifest.json @@ -0,0 +1,36 @@ +{ + "author": "Filestash Pty Ltd", + "version": "v0.0", + "modules": [ + { + "type": "xdg-open", + "mime": "application/fbx", + "entrypoint": "/index_fbx.js", + "application": "3d" + }, + { + "type": "xdg-open", + "mime": "model/gltf-binary", + "entrypoint": "/index_gltf.js", + "application": "3d" + }, + { + "type": "xdg-open", + "mime": "application/object", + "entrypoint": "/index_obj.js", + "application": "3d" + }, + { + "type": "xdg-open", + "mime": "model/stl", + "entrypoint": "/index_stl.js", + "application": "3d" + }, + { + "type": "xdg-open", + "mime": "image/svg+xml", + "entrypoint": "/index_svg.js", + "application": "3d" + } + ] +} diff --git a/public/assets/lib/vendor/three/FBXLoader.js b/server/plugin/plg_application_3d/vendor/FBXLoader.js similarity index 99% rename from public/assets/lib/vendor/three/FBXLoader.js rename to server/plugin/plg_application_3d/vendor/FBXLoader.js index 4436dac5..65777752 100644 --- a/public/assets/lib/vendor/three/FBXLoader.js +++ b/server/plugin/plg_application_3d/vendor/FBXLoader.js @@ -43,7 +43,7 @@ import { VectorKeyframeTrack, SRGBColorSpace, ShapeUtils -} from './three.module.js'; +} from '../../../assets/lib/vendor/three/three.module.js'; import * as fflate from './libs/fflate.module.js'; import { NURBSCurve } from './curves/NURBSCurve.js'; diff --git a/public/assets/lib/vendor/three/GLTFLoader.js b/server/plugin/plg_application_3d/vendor/GLTFLoader.js similarity index 99% rename from public/assets/lib/vendor/three/GLTFLoader.js rename to server/plugin/plg_application_3d/vendor/GLTFLoader.js index 68c38ccc..0af20869 100644 --- a/public/assets/lib/vendor/three/GLTFLoader.js +++ b/server/plugin/plg_application_3d/vendor/GLTFLoader.js @@ -65,7 +65,7 @@ import { VectorKeyframeTrack, SRGBColorSpace, InstancedBufferAttribute -} from './three.module.js'; +} from '../../../assets/lib/vendor/three/three.module.js'; import { toTrianglesDrawMode } from './utils/BufferGeometryUtils.js'; class GLTFLoader extends Loader { diff --git a/public/assets/lib/vendor/three/OBJLoader.js b/server/plugin/plg_application_3d/vendor/OBJLoader.js similarity index 99% rename from public/assets/lib/vendor/three/OBJLoader.js rename to server/plugin/plg_application_3d/vendor/OBJLoader.js index dd64ad94..67a3f5d9 100644 --- a/public/assets/lib/vendor/three/OBJLoader.js +++ b/server/plugin/plg_application_3d/vendor/OBJLoader.js @@ -14,7 +14,7 @@ import { PointsMaterial, Vector3, Color -} from './three.module.js'; +} from '../../../assets/lib/vendor/three/three.module.js'; // o object_name | g group_name const _object_pattern = /^[og]\s*(.+)?/; diff --git a/public/assets/lib/vendor/three/STLLoader.js b/server/plugin/plg_application_3d/vendor/STLLoader.js similarity index 99% rename from public/assets/lib/vendor/three/STLLoader.js rename to server/plugin/plg_application_3d/vendor/STLLoader.js index 21c57eea..58c24c83 100644 --- a/public/assets/lib/vendor/three/STLLoader.js +++ b/server/plugin/plg_application_3d/vendor/STLLoader.js @@ -7,7 +7,7 @@ import { Float32BufferAttribute, Loader, Vector3 -} from './three.module.js'; +} from '../../../assets/lib/vendor/three/three.module.js'; /** * Description: A THREE loader for STL ASCII files, as created by Solidworks and other CAD programs. diff --git a/public/assets/lib/vendor/three/SVGLoader.js b/server/plugin/plg_application_3d/vendor/SVGLoader.js similarity index 99% rename from public/assets/lib/vendor/three/SVGLoader.js rename to server/plugin/plg_application_3d/vendor/SVGLoader.js index dbe232a3..0b81b02f 100644 --- a/public/assets/lib/vendor/three/SVGLoader.js +++ b/server/plugin/plg_application_3d/vendor/SVGLoader.js @@ -13,7 +13,7 @@ import { SRGBColorSpace, Vector2, Vector3 -} from './three.module.js'; +} from '../../../assets/lib/vendor/three/three.module.js'; const COLOR_SPACE_SVG = SRGBColorSpace; diff --git a/public/assets/lib/vendor/three/curves/NURBSCurve.js b/server/plugin/plg_application_3d/vendor/curves/NURBSCurve.js similarity index 96% rename from public/assets/lib/vendor/three/curves/NURBSCurve.js rename to server/plugin/plg_application_3d/vendor/curves/NURBSCurve.js index 237a76cd..4d2a0894 100644 --- a/public/assets/lib/vendor/three/curves/NURBSCurve.js +++ b/server/plugin/plg_application_3d/vendor/curves/NURBSCurve.js @@ -3,7 +3,7 @@ import { Curve, Vector3, Vector4 -} from '../three.module.js'; +} from '../../../../assets/lib/vendor/three/three.module.js'; import * as NURBSUtils from './NURBSUtils.js'; /** diff --git a/public/assets/lib/vendor/three/curves/NURBSUtils.js b/server/plugin/plg_application_3d/vendor/curves/NURBSUtils.js similarity index 99% rename from public/assets/lib/vendor/three/curves/NURBSUtils.js rename to server/plugin/plg_application_3d/vendor/curves/NURBSUtils.js index 1696fda4..0b448cc2 100644 --- a/public/assets/lib/vendor/three/curves/NURBSUtils.js +++ b/server/plugin/plg_application_3d/vendor/curves/NURBSUtils.js @@ -2,7 +2,7 @@ import { Vector3, Vector4 -} from '../three.module.js'; +} from '../../../../assets/lib/vendor/three/three.module.js'; /** * NURBS utils diff --git a/public/assets/lib/vendor/three/libs/fflate.module.js b/server/plugin/plg_application_3d/vendor/libs/fflate.module.js similarity index 100% rename from public/assets/lib/vendor/three/libs/fflate.module.js rename to server/plugin/plg_application_3d/vendor/libs/fflate.module.js diff --git a/public/assets/lib/vendor/three/utils/BufferGeometryUtils.js b/server/plugin/plg_application_3d/vendor/utils/BufferGeometryUtils.js similarity index 99% rename from public/assets/lib/vendor/three/utils/BufferGeometryUtils.js rename to server/plugin/plg_application_3d/vendor/utils/BufferGeometryUtils.js index 8cf87421..5a508711 100644 --- a/public/assets/lib/vendor/three/utils/BufferGeometryUtils.js +++ b/server/plugin/plg_application_3d/vendor/utils/BufferGeometryUtils.js @@ -10,7 +10,7 @@ import { TriangleStripDrawMode, TrianglesDrawMode, Vector3, -} from '../three.module.js'; +} from '../../../../assets/lib/vendor/three/three.module.js'; function computeMikkTSpaceTangents( geometry, MikkTSpace, negateSign = true ) { diff --git a/server/plugin/plg_application_dev/Makefile b/server/plugin/plg_application_dev/Makefile new file mode 100644 index 00000000..beb85082 --- /dev/null +++ b/server/plugin/plg_application_dev/Makefile @@ -0,0 +1,15 @@ +all: + make build + make install + make clean + +build: + emcc -O2 -c loader_symbol.c + emcc --no-entry loader_symbol.o -o loader_symbol.wasm + +install: + zip -r application_dev.zip . + mv application_dev.zip ../../../dist/data/state/plugins/ + +clean: + rm *.o *.wasm diff --git a/public/assets/pages/viewerpage/application_table/loader_symbol.js b/server/plugin/plg_application_dev/index.js similarity index 91% rename from public/assets/pages/viewerpage/application_table/loader_symbol.js rename to server/plugin/plg_application_dev/index.js index 2c0c9d3e..4b6094f6 100644 --- a/public/assets/pages/viewerpage/application_table/loader_symbol.js +++ b/server/plugin/plg_application_dev/index.js @@ -1,5 +1,5 @@ -import assert from "../../../lib/assert.js"; -import loadWASM, { writeFS, readFS } from "../../../helpers/loader_wasm.js"; +import assert from "../../assets/lib/assert.js"; +import loadWASM, { writeFS, readFS } from "../../assets/helpers/loader_wasm.js"; export default async function(ITable) { const { instance } = await loadWASM(import.meta.url, "./loader_symbol.wasm"); diff --git a/public/assets/pages/viewerpage/application_table/loader_symbol.c b/server/plugin/plg_application_dev/loader_symbol.c similarity index 96% rename from public/assets/pages/viewerpage/application_table/loader_symbol.c rename to server/plugin/plg_application_dev/loader_symbol.c index c3e6dabc..dbb69843 100644 --- a/public/assets/pages/viewerpage/application_table/loader_symbol.c +++ b/server/plugin/plg_application_dev/loader_symbol.c @@ -48,7 +48,7 @@ EMSCRIPTEN_KEEPALIVE int execute(int fdinput, int fdoutput) { return 1; } if (strncmp(magic, ARMAG, SARMAG) != 0) { - fprintf(stderr, "ERROR file is not of the expected shape"); + fprintf(stderr, "ERROR bad magic value"); fclose(finput); fclose(foutput); return 1; @@ -81,6 +81,7 @@ EMSCRIPTEN_KEEPALIVE int execute(int fdinput, int fdoutput) { fseek(finput, (size + 1) & ~1, SEEK_CUR); } + fprintf(stdout, "hello world!\n"); fflush(foutput); fclose(foutput); fclose(finput); diff --git a/server/plugin/plg_application_dev/manifest.json b/server/plugin/plg_application_dev/manifest.json new file mode 100644 index 00000000..ff197f8d --- /dev/null +++ b/server/plugin/plg_application_dev/manifest.json @@ -0,0 +1,11 @@ +{ + "author": "Filestash Pty Ltd", + "version": "v0.0", + "modules": [ + { + "type": "xdg-open", + "mime": "application/x-archive", + "application": "table" + } + ] +} diff --git a/server/routes.go b/server/routes.go index 9a54a7d2..da39edd7 100644 --- a/server/routes.go +++ b/server/routes.go @@ -91,6 +91,7 @@ func Build(a App) *mux.Router { // Application Resources middlewares = []Middleware{ApiHeaders, SecureHeaders, PluginInjector} r.HandleFunc(WithBase("/api/backend"), NewMiddlewareChain(AdminBackend, middlewares, a)).Methods("GET") + r.HandleFunc(WithBase("/api/plugin"), NewMiddlewareChain(PluginExportHandler, middlewares, a)).Methods("GET") r.HandleFunc(WithBase("/api/config"), NewMiddlewareChain(PublicConfigHandler, append(middlewares, PublicCORS), a)).Methods("GET", "OPTIONS") middlewares = []Middleware{StaticHeaders, SecureHeaders, PublicCORS, PluginInjector} if os.Getenv("CANARY") == "" { // TODO: remove after migration is done @@ -100,6 +101,7 @@ func Build(a App) *mux.Router { } else { // TODO: remove this after migration is done r.PathPrefix(WithBase("/assets")).Handler(http.HandlerFunc(NewMiddlewareChain(ServeFile("/"), middlewares, a))).Methods("GET", "OPTIONS") r.HandleFunc(WithBase("/favicon.ico"), NewMiddlewareChain(ServeFavicon, middlewares, a)).Methods("GET") + r.HandleFunc(WithBase("/plugin/{name}/{path:.+}"), NewMiddlewareChain(PluginStaticHandler, middlewares, a)).Methods("GET") } // Other endpoints