diff --git a/.gitattributes b/.gitattributes index 6cd0abc..0de2ff9 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,2 +1,5 @@ # Review the viewer source; this reproducible bundle includes upstream GLSL text. src/dvidia_training/reference_replay.bundle.js linguist-generated=true -diff +src/dvidia_training/workstation.bundle.js linguist-generated=true -diff +src/dvidia_training/workstation_worker.bundle.js linguist-generated=true -diff +src/dvidia_training/mujoco.wasm binary diff --git a/.github/workflows/workstation.yml b/.github/workflows/workstation.yml new file mode 100644 index 0000000..2e590cc --- /dev/null +++ b/.github/workflows/workstation.yml @@ -0,0 +1,71 @@ +name: Live workstation +on: + push: + pull_request: + workflow_dispatch: +permissions: + contents: read +concurrency: + group: workstation-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true +jobs: + native-browser: + runs-on: ubuntu-latest + timeout-minutes: 20 + env: + OPENBLAS_NUM_THREADS: "1" + OMP_NUM_THREADS: "1" + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 + with: + persist-credentials: false + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 + with: + python-version: "3.12" + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 + with: + node-version: "22" + - name: Reproduce pinned browser runtime + run: | + npm ci --ignore-scripts --prefix viewer + npm run --prefix viewer build:workstation + git diff --exit-code -- src/dvidia_training/workstation.bundle.js src/dvidia_training/workstation_worker.bundle.js src/dvidia_training/mujoco.wasm src/dvidia_training/workstation.third-party.txt + node --test tests/browser/workstation_control.mjs tests/browser/workstation_assets.mjs + - name: Install native mechanics and verify contracts + run: | + python -m pip install '.[arm]' + dvidia-robot-sim fetch piper --output runs/workstation-assets + DVIDIA_ROBOT_PROFILE_ASSETS=runs/workstation-assets python -m unittest tests.test_workstation tests.test_workstation_benchmark -v + dvidia-workstation --assets runs/workstation-assets --output runs/workstation + dvidia-workstation-benchmark --assets runs/workstation-assets --output runs/workstation-benchmark --stability-seconds 10 + - name: Compare native and WASM state with loaded-contact counts + run: | + python scripts/workstation-parity-fixture.py --scene runs/workstation --output runs/native-parity.json + python - <<'PY' + import json, subprocess + result = subprocess.run(['node','tests/browser/workstation_parity.mjs','runs/workstation','runs/native-parity.json','runs/wasm-parity.json']) + report = json.load(open('runs/wasm-parity.json')) + assert result.returncode in (0,1) + assert report['valid'] and report['numerical_parity_passed'] and report['active_contact_count_parity_passed'] + print('Raw contact count parity is retained separately:', report['strict_parity_passed']) + PY + - name: Exercise actual browser controls and live physics + run: | + viewer/node_modules/.bin/playwright install --with-deps chromium + python -m http.server 8295 --bind 127.0.0.1 --directory runs/workstation > /tmp/workstation-http.log 2>&1 & + server_pid=$! + trap 'kill "$server_pid"' EXIT + DVIDIA_PLAYWRIGHT_MODULE="$GITHUB_WORKSPACE/viewer/node_modules/playwright" DVIDIA_BENCH_SECONDS=20 node tests/browser/workstation_live.cjs http://127.0.0.1:8295/ runs/workstation-browser + node tests/browser/workstation_download.cjs http://127.0.0.1:8295/ runs/workstation-download-recovery + - name: Retain all results including failed attempts + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + with: + name: live-workstation-evidence + path: | + runs/workstation-benchmark + runs/workstation-browser + runs/workstation-download-recovery + runs/native-parity.json + runs/wasm-parity.json + if-no-files-found: ignore diff --git a/README.md b/README.md index cb6579d..ae575cd 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,14 @@ **Research alpha.** The recorded demo covers the original one-scene simulation pilot; the frozen benchmark is a separate experiment. Training runs locally. No human-video action bridge or hardware skill is established. +**[Open the live PiPER shoe workstation](https://dvidia-robot-simulation-lab.static.hf.space/workstation/v01/index.html).** +Drag the tool target, move the native gripper, nudge a free shoe and inspect the +resulting contacts. MuJoCo 3.15.0 runs locally in a browser worker; a warm 3D +workstation makes the native mechanics directly interactive. The shoe remains a +rigid synthetic asset and the controller is authored. Read the +[local setup and benchmark guide](docs/live-workstation.md) and +[research results](https://research.dvidia.org/papers/live-piper-shoe-workstation-v01/). + The new [native grasp task benchmark](docs/native-task-benchmark.md) connects the pinned six-axis arm and coupled gripper to free-object grasp, carry and release attempts. It retains matched open-jaw/hold controls, frozen protocols and local diff --git a/docs/live-workstation.md b/docs/live-workstation.md new file mode 100644 index 0000000..2eead9c --- /dev/null +++ b/docs/live-workstation.md @@ -0,0 +1,161 @@ +# Live PiPER shoe workstation v0.1 + +[Open the workstation](https://dvidia-robot-simulation-lab.static.hf.space/workstation/v01/index.html) +or read the [research and complete benchmark evidence](https://research.dvidia.org/papers/live-piper-shoe-workstation-v01/). + +The six-axis PiPER and its native gripper respond to dragged or typed tool-position +targets. A free rigid trainer falls, settles on the worktop and moves under a +bounded physical nudge. Pause, reset, camera views, collision geometry and a local +session receipt make the mechanics inspectable. No account or inference service +is needed to run the hosted workstation. + +## Run a complete copy locally + +Use Python 3.12 or newer and the published source revision. Provision the package +and upstream robot assets once: + +```sh +git clone --branch feat/live-piper-workstation-v01 https://github.com/Dvidia-Inference/dvidia-training.git +cd dvidia-training +python3.12 -m venv .venv +source .venv/bin/activate +python -m pip install '.[arm]' +dvidia-robot-sim fetch piper --output ./robot-assets +dvidia-workstation --assets ./robot-assets --output ./live-workstation +python -m http.server 8000 --bind 127.0.0.1 --directory ./live-workstation +``` + +Open http://localhost:8000. Keep the exported folder together. All meshes, +JavaScript, WASM, geometry, catalog and license notices are local. Later sessions +work offline. On Windows use `py -3.12 -m venv .venv` and the corresponding +executables under `.venv\Scripts`; activation is optional. + +The browser fetches one gzip bundle for all 84 native robot meshes, concurrently +with the physics engine and scene. It verifies the bundle, bounds decompression, +and checks every original mesh hash before compiling the model. The original +individual meshes remain in the export for reproduction. This changes delivery +only; the scene, controller, contacts and engine binary are unchanged. First-load +time still depends on the connection and device; it is measured separately from +steady-state simulation speed. + +The WASM engine downloads as `mujoco.wasm.gz` (2.54 MB instead of 10.37 MB), +then decompresses to the exact original engine bytes verified by SHA-256. +The original uncompressed engine remains in the export. Geometry, engine and +mesh downloads share a bounded downloader: at most three total attempts, +30 seconds without incoming data before an attempt is stopped, and a +120-second total deadline per resource. Only transient network/body-stream +failures and selected temporary HTTP errors retry; invalid sizes, checksums or +destinations fail immediately. Loading progress names retries; a terminal +failure exposes **Reload and retry**. Reload starts a new session. + +The official Hugging Face Space downloads three known compressed assets from +content-addressed URLs on `research.dvidia.org`. The requested size and SHA-256 +must match the published mirror inventory, and the received bytes are checked +before use. A temporary mirror failure falls back to Hugging Face within the +same retry and time budget; a checksum, size or redirect-policy failure stops. +This routing applies only to the exact official Space and asset paths. Local +exports and other deployments use their own included files. + +On 2026-10-13 the earlier Hugging Face startup failure could not be reproduced +as a deterministic CORS, gzip or corrupt-asset defect. Fresh diagnostics verified +all three old binary assets. The exact historical network event was not captured; +the confirmed defect was the absence of bounded transfer recovery. The download +regression test deliberately interrupts each large download and verifies native +control after recovery, then exhausts retries and tests a manual reload: + +```sh +node tests/browser/workstation_download.cjs http://localhost:8000/ ./download-recovery-evidence +``` + +The export includes an integrity inventory and hashed upstream assets. To inspect: + +```sh +python -c "from dvidia_training.workstation import inspect_export; print(inspect_export('./live-workstation')['file_count'])" +``` + +## Controls and mechanics + +- Drag a colored target axis or enter X/Y/Z in millimeters. Height and keyboard + controls provide alternatives to pointer dragging. +- The controller holds one declared tool orientation while solving six arm joint + targets. The allowed input box is a command bound, not a promise that every + point is reachable at that orientation. The measured target error stays visible. +- Finger travel spans 0–35 mm for one side of the coupled gripper. It is a native + position command, not a calibrated jaw gap or force. +- Nudge applies at most 0.12 N·s for one physics tick. It is an explicit user + disturbance, never a hidden lifting or attachment force. +- Reset restores the declared initial state. Hidden tabs pause; resume explicitly + after returning. Session receipts retain a bounded recent history and disclose + dropped samples and resets. + +MuJoCo advances at a fixed 2 ms physics timestep. Differential IK runs every +20 ms. Joint-command rates and original servo limits remain enforced. Browser +state updates and rendering run separately, with bounded catch-up and disclosed +lag when a device cannot keep up. There is no shoe weld, object teleport during +interaction, neural policy or physical robot connection. + +## Reproduce the benchmarks + +```sh +dvidia-workstation-benchmark --assets ./robot-assets --output ./workstation-benchmark +``` + +The protocol records two resets for eight target positions, jaw close/open travel, +a shoe impulse, disabled-table gravity control and 600 simulated seconds of +continuous native holding. Each tracking attempt has a four-second deadline and +requires both 5 mm position and 3° orientation tolerances. Every attempt and raw +control-window duration remains in the output, including failures. Native timing +excludes browser rendering and network. This evaluates target tracking and +contact diagnostics; it does not score an autonomous shoe-organizing skill. + +Browser acceptance and native/WASM parity are separate: + +```sh +PYTHONPATH=src python scripts/workstation-parity-fixture.py --scene ./live-workstation --output ./native-parity.json +node tests/browser/workstation_parity.mjs ./live-workstation ./native-parity.json ./wasm-parity.json +``` + +The actual-browser tests use the same exported folder served over HTTP: + +```sh +npm ci --prefix viewer +viewer/node_modules/.bin/playwright install chromium +node tests/browser/workstation_ui.cjs http://localhost:8000/ ./ui-evidence +DVIDIA_BENCH_SECONDS=600 DVIDIA_BENCH_RENDERER=device DVIDIA_BROWSER_CHANNEL=chromium node tests/browser/workstation_live.cjs http://localhost:8000/ ./browser-evidence +``` + +The device renderer is requested, then identified in the receipt. The live benchmark defaults to +SwiftShader software rendering. Neither render-call counts nor worker state +updates measure GPU presentation completion or hardware actuator latency. + +The parity runner requires `npm ci --prefix viewer`. It retains numerical, +loaded-contact and strict raw contact-count comparisons separately. A strict +contact-count mismatch exits nonzero even when state tolerances agree; inspect +all result fields. Floating-point differences around zero-load contacts must not +be presented as exact contact parity. + +## Hardware and licensing + +Physics runs on a CPU. Browser rendering requires WebGL2; JavaScript, +WebAssembly and DecompressionStream must be available. No CUDA training GPU or +large model download is required. Minimum RAM and CPU specifications have not +been established across devices. Published measurements name their browser, +rendering backend and timing scope; software-rendered browser results are not +hardware GPU measurements. + +DVIDIA code, original shoe shapes and procedural visual details are MIT. PiPER +assets retain their pinned upstream MIT notices. Three.js is MIT. MuJoCo is +Apache-2.0 with dependency notices retained in `workstation.third-party.txt`. +The header uses DVIDIA's existing mark and wordmark. The embedded IBM Plex Sans +wordmark font retains its SIL Open Font License 1.1 notice in the HTML; the +software license does not grant rights to DVIDIA trademarks. +Visual shoelaces and surface details are cosmetic; they do not simulate cloth or +change collision geometry. Shoe mass, friction and contact parameters remain +authored assumptions. Retained shoe lifting and real-world transfer are open. + +To rebuild the browser runtime with pinned dependencies: + +```sh +npm ci --prefix viewer +npm run --prefix viewer build:workstation +``` diff --git a/publishing/huggingface/prepare_workstation.py b/publishing/huggingface/prepare_workstation.py new file mode 100644 index 0000000..160d242 --- /dev/null +++ b/publishing/huggingface/prepare_workstation.py @@ -0,0 +1,257 @@ +"""Stage the live workstation and separate public evidence beside prior artifacts.""" +from __future__ import annotations +import argparse +from hashlib import sha256 +import json +from pathlib import Path +import re +import shutil +import struct +import sys +import tempfile +import zlib + +import publish_robot_sim as publisher + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT/'src')) +NAMESPACE = 'workstation/v01' +EVIDENCE_NAMESPACE = 'workstation-evidence/v01' +EVIDENCE_SCHEMA = 'dvidia.live-workstation-evidence/v1' +MAX_EVIDENCE_FILES = 128 +MAX_EVIDENCE_BYTES = 128*1024*1024 +EVIDENCE_SEAL = 'evidence-integrity.json' +PRIVATE_PATTERN = re.compile( + rb'(?:/(?:Users|home)/|/private/tmp/|/var/folders/|[A-Za-z]:\\Users\\|' + rb'hf_[A-Za-z0-9]{30,}|gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{30,}|' + rb'sk-[A-Za-z0-9_-]{30,}|-----BEGIN [A-Z ]*PRIVATE KEY-----)') + + +def encoded(value): + return (json.dumps(value, indent=2, allow_nan=False)+'\n').encode() + + +def record(raw): + return {'bytes': len(raw), 'sha256': sha256(raw).hexdigest()} + + +def _private(raw): + publisher._no_private_bytes(raw) + if PRIVATE_PATTERN.search(raw): + raise ValueError('Possible credential or private path in workstation evidence') + + +def _png(raw): + """Bound screenshot structure; reject text/EXIF metadata and trailing data.""" + if raw[:8] != b'\x89PNG\r\n\x1a\n': + raise ValueError('Evidence PNG signature mismatch') + offset, chunks, data_seen = 8, [], False + allowed = {b'IHDR', b'PLTE', b'IDAT', b'IEND', b'tRNS', b'sRGB', b'gAMA', b'cHRM', b'pHYs'} + while offset < len(raw): + if offset+12 > len(raw): + raise ValueError('Evidence PNG is truncated') + length = struct.unpack_from('>I', raw, offset)[0] + kind, end = raw[offset+4:offset+8], offset+12+length + if kind not in allowed or end > len(raw): + raise ValueError('Evidence PNG has unsupported metadata or chunk size') + content = raw[offset+8:offset+8+length] + if zlib.crc32(kind+content)&0xffffffff != struct.unpack_from('>I', raw, end-4)[0]: + raise ValueError('Evidence PNG checksum mismatch') + if kind == b'IHDR': + if chunks or length != 13: + raise ValueError('Evidence PNG header mismatch') + width, height = struct.unpack_from('>II', content) + if not 1 <= width <= 16384 or not 1 <= height <= 16384 or width*height > 32*1024*1024: + raise ValueError('Evidence PNG dimensions exceed bounds') + if kind == b'IDAT': + data_seen = True + chunks.append(kind) + offset = end + if len(chunks) > 4096: + raise ValueError('Evidence PNG chunk count exceeds bounds') + if kind == b'IEND': + if length or offset != len(raw) or not data_seen: + raise ValueError('Evidence PNG terminator mismatch') + break + if not chunks or chunks[0] != b'IHDR' or chunks[-1] != b'IEND': + raise ValueError('Evidence PNG lacks its image framing') + + +def read_evidence(directory): + """Freeze bounded data/screenshots and check decoded JSON strings for privacy.""" + from dvidia_training.reference_replay import _decode + root = Path(directory).absolute() + publisher._plain(root) + if not root.is_dir(): + raise ValueError('Evidence requires a plain directory') + files, total, entries = {}, 0, 0 + for path in root.rglob('*'): + entries += 1 + if entries > 2*MAX_EVIDENCE_FILES: + raise ValueError('Evidence directory entry count exceeds bounds') + publisher._plain(path) + name = path.relative_to(root).as_posix() + if (len(name) > 240 or len(path.relative_to(root).parts) > 8 + or re.fullmatch(r'[A-Za-z0-9_-][A-Za-z0-9_.-]*(?:/[A-Za-z0-9_-][A-Za-z0-9_.-]*)*', name) is None): + raise ValueError('Evidence path must be a bounded safe relative name') + if path.is_dir(): + continue + publisher._artifact_name(EVIDENCE_NAMESPACE+'/'+name) + if not path.is_file() or path.suffix not in {'.json', '.md', '.png'}: + raise ValueError('Evidence accepts only plain JSON, Markdown and PNG files') + if name == EVIDENCE_SEAL: + raise ValueError('Evidence seal name is reserved for the generated inventory') + raw = publisher._bytes(path, publisher.MAX_FILE_BYTES) + _private(raw) + if path.suffix == '.json': + value = _decode(raw) + stack = [(value, 0)] + while stack: + item, depth = stack.pop() + if depth > 64: + raise ValueError('Evidence JSON nesting exceeds bounds') + if type(item) is dict: + for key, child in item.items(): + _private(key.encode('utf-8')) + stack.append((child, depth+1)) + elif type(item) is list: + stack.extend((child, depth+1) for child in item) + elif type(item) is str: + _private(item.encode('utf-8')) + elif path.suffix == '.md': + try: + raw.decode('utf-8') + except UnicodeError as exc: + raise ValueError('Evidence Markdown must be UTF-8') from exc + if b'\0' in raw: + raise ValueError('Evidence Markdown contains binary content') + else: + _png(raw) + files[name] = raw + total += len(raw) + if len(files) > MAX_EVIDENCE_FILES or total > MAX_EVIDENCE_BYTES: + raise ValueError('Evidence exceeds its bounded publication budget') + if 'README.md' not in files or not files['README.md'].strip(): + raise ValueError('Evidence requires a nonempty README.md') + return files + + +def stage(base_plan, workstation, output, source_commit, expected_remote_commit, *, evidence): + """Freeze a complete additive release against an explicit remote parent.""" + if any(type(value) is not str or re.fullmatch(r'[a-f0-9]{40}', value) is None for value in + (source_commit, expected_remote_commit)): + raise ValueError('Exact source and remote parent commits are required') + base_plan = Path(base_plan).absolute() + base = publisher.checked_plan(base_plan) + root = Path(workstation).absolute() + publisher._plain(root) + evidence_root = Path(evidence).absolute() + if root == evidence_root or root in evidence_root.parents or evidence_root in root.parents: + raise ValueError('Workstation and evidence inputs require separate directory trees') + evidence_files = read_evidence(evidence_root) + from dvidia_training.workstation import inspect_export + inspect_export(root) + payload = {} + for item in base['repository']['files']: + raw = publisher._bytes(base_plan.parent/'space'/item['path'], publisher.MAX_FILE_BYTES) + if record(raw) != {'bytes':item['bytes'], 'sha256':item['sha256']}: + raise ValueError('Prior artifact changed while freezing the additive publication') + payload[item['path']] = raw + if any(name.startswith(namespace+'/') for name in payload for namespace in (NAMESPACE, EVIDENCE_NAMESPACE)): + raise ValueError('First workstation release must not replace an existing workstation or evidence namespace') + added = {} + for path in sorted(root.rglob('*')): + publisher._plain(path) + if not path.is_file(): + continue + name = NAMESPACE+'/'+path.relative_to(root).as_posix() + publisher._artifact_name(name) + raw = publisher._bytes(path, publisher.MAX_FILE_BYTES) + publisher._no_private_artifact_bytes(name, raw) + added[name] = raw + if not 8 <= len(added) <= 128 or sum(map(len, added.values())) > 96*1024*1024: + raise ValueError('Workstation exceeds its release budget') + seal = {'schema': EVIDENCE_SCHEMA, 'source_commit': source_commit, + 'scope': 'Complete public evidence inventory; hashes establish consistency, not authentication or physical qualification', + 'workstation_path': NAMESPACE, + 'workstation_integrity': record(added[NAMESPACE+'/workstation-integrity.json']), + 'files': {name: record(raw) for name, raw in sorted(evidence_files.items())}} + evidence_files[EVIDENCE_SEAL] = encoded(seal) + added_evidence = {EVIDENCE_NAMESPACE+'/'+name: raw for name, raw in evidence_files.items()} + payload.update(added) + payload.update(added_evidence) + index = payload['index.html'].decode() + marker = '
' + if index.count(marker) != 1: + raise ValueError('Existing asset-library entry point has changed') + card = ('

A live PiPER shoe workstation.

' + '

Drag the gripper target, open and close the jaws, and push a free rigid shoe. ' + 'MuJoCo physics runs locally in your browser. Explore contacts and download a session receipt.

' + '

Authored control and synthetic shoe properties; no learned policy or hardware qualification.

' + 'Enter the live workstation →
') + payload['index.html'] = index.replace(marker, card+marker).encode() + payload['README.md'] += ('\n\n## Live PiPER shoe workstation v0.1\n\n' + '[Open the live workstation](workstation/v01/index.html). MuJoCo 3.15.0 WASM runs in a browser worker. ' + 'Drag targets, bounded joint commands, native gripper actuation and free-object contact are live. ' + 'The shoe is a rigid synthetic proxy with uncalibrated properties. No learned skill or physical robot qualification. ' + '[Complete evidence and failures](workstation-evidence/v01/README.md), ' + '[evidence file hashes](workstation-evidence/v01/evidence-integrity.json), and ' + '[research report](https://research.dvidia.org/papers/live-piper-shoe-workstation-v01/). ' + 'DVIDIA code and shoes: MIT; PiPER assets: MIT; Three.js: MIT; MuJoCo: Apache-2.0 with retained dependency notices.\n').encode() + provenance = json.loads(payload['provenance.json']) + provenance['live_workstation'] = {'path': NAMESPACE, 'source_commit': source_commit, + 'mujoco': '3.15.0', 'physical_robot_ready': False, 'learned_policy': False, + 'files': {n[len(NAMESPACE)+1:]: record(b) for n, b in added.items()}, + 'evidence': {'path': EVIDENCE_NAMESPACE, 'source_commit': source_commit, + 'integrity': record(evidence_files[EVIDENCE_SEAL]), + 'files': {name: record(raw) for name, raw in sorted(evidence_files.items())}}} + payload['provenance.json'] = encoded(provenance) + destination = Path(output).absolute() + publisher._plain(destination) + if destination.exists(): + raise ValueError('Workstation publication output must be fresh') + if any(parent == directory for parent in destination.parents for directory in (root, evidence_root, base_plan.parent)): + raise ValueError('Publication output must be outside input trees') + if len(payload) > publisher.MAX_FILES or sum(map(len, payload.values())) > publisher.MAX_TOTAL_BYTES: + raise ValueError('Complete publication exceeds its file or byte budget') + plan = {**base, 'source_commit': source_commit, 'expected_remote_commit': expected_remote_commit, + 'remove_files': [], 'repository': {**base['repository'], + 'files': [{'path': n, **record(b)} for n, b in sorted(payload.items())]}, + 'total_bytes': sum(map(len, payload.values()))} + destination.parent.mkdir(parents=True, exist_ok=True) + staging = Path(tempfile.mkdtemp(prefix='.workstation-publication-', dir=destination.parent)) + try: + for name, raw in payload.items(): + path = staging/'space'/name + path.parent.mkdir(parents=True, exist_ok=True) + with path.open('xb') as stream: + stream.write(raw) + (staging/'publication-plan.json').write_bytes(encoded(plan)) + # Reinspect copied simulation bytes. Evidence is outside this strict tree. + inspect_export(staging/'space'/NAMESPACE) + publisher.checked_plan(staging/'publication-plan.json') + if destination.exists() or destination.is_symlink(): + raise ValueError('Publication output must remain fresh') + staging.rename(destination) + finally: + if staging.exists(): + shutil.rmtree(staging) + return {'plan': str(destination/'publication-plan.json'), 'files': len(payload), + 'added_files': len(added), 'evidence_files': len(added_evidence), 'total_bytes': plan['total_bytes']} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--base-plan', required=True) + parser.add_argument('--workstation', required=True) + parser.add_argument('--evidence', required=True) + parser.add_argument('--output', required=True) + parser.add_argument('--source-commit', required=True) + parser.add_argument('--expected-remote-commit', required=True) + args = parser.parse_args() + print(json.dumps(stage(args.base_plan, args.workstation, args.output, + args.source_commit, args.expected_remote_commit, evidence=args.evidence))) + + +if __name__ == '__main__': + main() diff --git a/publishing/huggingface/prepare_workstation_delivery.py b/publishing/huggingface/prepare_workstation_delivery.py new file mode 100644 index 0000000..c8439d5 --- /dev/null +++ b/publishing/huggingface/prepare_workstation_delivery.py @@ -0,0 +1,116 @@ +"""Stage workstation delivery/branding fixes while retaining original evidence.""" +from __future__ import annotations + +import argparse +import json +from pathlib import Path +import re +import shutil +import tempfile + +import prepare_workstation as original +import publish_robot_sim as publisher + +NAMESPACE = original.NAMESPACE +EVIDENCE_NAMESPACE = 'workstation-delivery/v01' +MUTABLE = {'index.html', 'workstation.json', 'workstation-integrity.json', 'workstation_worker.bundle.js', + 'workstation.bundle.js', 'README.md'} +ADDED = {'native-assets.bin.gz'} + + +def stage(base_plan, workstation, evidence, output, source_commit, expected_remote_commit): + from dvidia_training.workstation import inspect_export + for value in (source_commit, expected_remote_commit): + if type(value) is not str or re.fullmatch('[a-f0-9]{40}', value) is None: + raise ValueError('Exact source and remote parent commits are required') + base_plan, root, destination = map(lambda p: Path(p).absolute(), (base_plan, workstation, output)) + publisher._plain(root) + publisher._plain(destination) + if destination.exists() or root == destination or root in destination.parents or base_plan.parent in destination.parents: + raise ValueError('Delivery publication output must be fresh and outside inputs') + base = publisher.checked_plan(base_plan) + inspect_export(root) + proof = original.read_evidence(evidence) + payload = {} + for entry in base['repository']['files']: + raw = publisher._bytes(base_plan.parent/'space'/entry['path'], publisher.MAX_FILE_BYTES) + if original.record(raw) != {key: entry[key] for key in ('bytes', 'sha256')}: + raise ValueError('Prior artifact changed during staging') + payload[entry['path']] = raw + old = {name[len(NAMESPACE)+1:]: raw for name, raw in payload.items() if name.startswith(NAMESPACE+'/')} + if not old or any(name.startswith(EVIDENCE_NAMESPACE+'/') for name in payload): + raise ValueError('Requires the first published workstation and a fresh delivery evidence namespace') + inspect_export(base_plan.parent/'space'/NAMESPACE) + updated = {p.relative_to(root).as_posix(): publisher._bytes(p, publisher.MAX_FILE_BYTES) + for p in root.rglob('*') if p.is_file()} + if not set(old) <= set(updated) or set(updated)-set(old) != ADDED: + raise ValueError('Delivery update must retain the original inventory and add only its transport bundle') + changed = {name for name in old if old[name] != updated[name]} + if changed-MUTABLE: + raise ValueError('Delivery update changed physics, renderer geometry, native engine, meshes or notices') + before, after = (json.loads(data['workstation.json']) for data in (old, updated)) + if 'native_asset_bundle' in before or 'native_asset_bundle' not in after: + raise ValueError('Delivery update must introduce its compressed transport descriptor') + if before != {key: value for key, value in after.items() if key != 'native_asset_bundle'}: + raise ValueError('Delivery update changed native metadata or controller configuration') + for name, raw in updated.items(): + publisher._artifact_name(NAMESPACE+'/'+name) + publisher._no_private_artifact_bytes(NAMESPACE+'/'+name, raw) + payload[NAMESPACE+'/'+name] = raw + seal = {'schema': 'dvidia.workstation-delivery-evidence/v1', 'source_commit': source_commit, + 'prior_publication_commit': expected_remote_commit, + 'old_workstation_integrity': original.record(old['workstation-integrity.json']), + 'workstation_integrity': original.record(updated['workstation-integrity.json']), + 'changed_files': sorted(changed), 'added_files': sorted(ADDED), + 'native_metadata_unchanged': True, + 'files': {name: original.record(raw) for name, raw in sorted(proof.items())}} + proof[original.EVIDENCE_SEAL] = original.encoded(seal) + payload.update({EVIDENCE_NAMESPACE+'/'+name: raw for name, raw in proof.items()}) + provenance = json.loads(payload['provenance.json']) + live = provenance['live_workstation'] + if live['files'] != {name: original.record(raw) for name, raw in old.items()}: + raise ValueError('Prior workstation provenance differs from its published inventory') + live['original_source_commit'] = live['source_commit'] + live['source_commit'] = source_commit + live['files'] = {name: original.record(raw) for name, raw in updated.items()} + live['delivery'] = {'path': EVIDENCE_NAMESPACE, 'source_commit': source_commit, + 'integrity': original.record(proof[original.EVIDENCE_SEAL])} + provenance['publication_byte_bounds'] = { + 'stored_payload_bytes': publisher.MAX_TOTAL_BYTES, + 'per_file_bytes': publisher.MAX_FILE_BYTES, + 'scope': '768 MiB complete stored Space cap; prior evidence retained; original per-file and attempt decoding bounds unchanged'} + payload['provenance.json'] = original.encoded(provenance) + payload['README.md'] += (f'\n\nThe live workstation now loads one compressed native mesh bundle. ' + f'Original meshes, physics parameters and original benchmark evidence are retained. ' + f'[Delivery validation]({EVIDENCE_NAMESPACE}/README.md).\n').encode() + plan = {**base, 'source_commit': source_commit, 'expected_remote_commit': expected_remote_commit, + 'remove_files': [], 'total_bytes': sum(map(len, payload.values())), + 'repository': {**base['repository'], 'files': [ + {'path': name, **original.record(raw)} for name, raw in sorted(payload.items())]}} + if len(payload) > publisher.MAX_FILES or plan['total_bytes'] > publisher.MAX_TOTAL_BYTES: + raise ValueError('Delivery publication exceeds its file or byte budget') + destination.parent.mkdir(parents=True, exist_ok=True) + staging = Path(tempfile.mkdtemp(prefix='.workstation-delivery-', dir=destination.parent)) + try: + for name, raw in payload.items(): + path = staging/'space'/name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(raw) + (staging/'publication-plan.json').write_bytes(original.encoded(plan)) + inspect_export(staging/'space'/NAMESPACE) + publisher.checked_plan(staging/'publication-plan.json') + if destination.exists() or destination.is_symlink(): + raise ValueError('Delivery output must remain fresh') + staging.rename(destination) + finally: + if staging.exists(): + shutil.rmtree(staging) + return {'plan': str(destination/'publication-plan.json'), 'files': len(payload), + 'total_bytes': plan['total_bytes'], 'changed_workstation_files': sorted(changed)} + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + for name in ('base-plan', 'workstation', 'evidence', 'output', 'source-commit', 'expected-remote-commit'): + parser.add_argument('--'+name, required=True) + print(json.dumps(stage(**vars(parser.parse_args())), indent=2)) diff --git a/publishing/huggingface/prepare_workstation_editorial.py b/publishing/huggingface/prepare_workstation_editorial.py new file mode 100644 index 0000000..4eed8d6 --- /dev/null +++ b/publishing/huggingface/prepare_workstation_editorial.py @@ -0,0 +1,200 @@ +"""Stage an HTML-only workstation refresh, retaining the published mirror runtime. + +Defaults reconstruct the last complete mirror release plus its additive public +acceptance receipt. Staging is offline; publishing uses publish_robot_sim.py. +""" +from __future__ import annotations + +import argparse +from html.parser import HTMLParser +import json +from pathlib import Path +import re +import shutil +import tempfile + +import prepare_workstation as original +import publish_robot_sim as publisher + +NAMESPACE = original.NAMESPACE +EVIDENCE_NAMESPACE = 'workstation-editorial/v01' +MUTABLE = {'index.html', 'workstation-integrity.json'} +APPEND_NAMESPACE = 'workstation-mirror/v01/public/' +APPEND_NAMES = {APPEND_NAMESPACE+name for name in ('README.md', 'acceptance.json', 'test-provenance.json')} +DEFAULT_BASE = original.ROOT/'runs/robot-simulation-lab-publication-mirror-v01/publication-plan.json' +DEFAULT_APPEND = original.ROOT/'runs/hf-download-fix/public-evidence-publication' + + +class _ExecutableHTML(HTMLParser): + """Record executable HTML so editorial changes cannot silently add scripts.""" + def __init__(self, raw): + super().__init__(convert_charrefs=True) + self.scripts, self.active = [], False + self.feed(raw.decode('utf-8')) + self.close() + + def handle_starttag(self, tag, attrs): + if any(key.lower().startswith('on') or (value or '').lstrip().lower().startswith('javascript:') + for key, value in attrs): + raise ValueError('Editorial HTML may not contain event handlers or javascript URLs') + if tag == 'script': + self.scripts.append([sorted(attrs), '']) + self.active = True + + def handle_endtag(self, tag): + if tag == 'script': + self.active = False + + def handle_data(self, data): + if self.active: + self.scripts[-1][1] += data + + +def _json(path): + return json.loads(publisher._bytes(path, 1024*1024)) + + +def _reconstruct(base_path, append_root, expected_remote_commit): + base = publisher.checked_plan(base_path) + base_raw = publisher._bytes(base_path, 1024*1024) + receipt = _json(base_path.parent/'publication-receipt.json') + addition_raw = publisher._bytes(append_root/'plan.json', 1024*1024) + addition, published = json.loads(addition_raw), _json(append_root/'publication-receipt.json') + if (receipt.get('repo_id') != publisher.REPO_ID or receipt.get('repo_type') != 'space' + or receipt.get('plan_sha256') != original.record(base_raw)['sha256'] + or receipt.get('verified_files') != len(base['repository']['files']) + or addition.get('kind') != 'dvidia.mirror-public-acceptance-append/v1' + or addition.get('repo_id') != publisher.REPO_ID + or addition.get('source_publication_plan_sha256') != receipt['plan_sha256'] + or addition.get('parent_commit') != receipt.get('commit') + or addition.get('source_commit') != base.get('source_commit') + or published.get('repo_id') != publisher.REPO_ID or published.get('repo_type') != 'space' + or published.get('parent_commit') != receipt.get('commit') + or published.get('commit') != expected_remote_commit + or published.get('plan_sha256') != original.record(addition_raw)['sha256'] + or published.get('runtime_and_sealed_evidence_unchanged') is not True): + raise ValueError('Baseline and acceptance receipts must bind the exact reviewed remote parent') + entries = addition.get('files') + if (type(entries) is not dict or set(entries) != APPEND_NAMES + or published.get('added_files') != [{'path': name, **record} for name, record in entries.items()] + or published.get('unchanged_existing_files') != len(base['repository']['files'])+1): + raise ValueError('Acceptance append must retain the complete prior inventory and add its three known files') + payload = {} + for entry in base['repository']['files']: + raw = publisher._bytes(base_path.parent/'space'/entry['path'], publisher.MAX_FILE_BYTES) + if original.record(raw) != {key: entry[key] for key in ('bytes', 'sha256')}: + raise ValueError('Prior artifact changed during reconstruction') + payload[entry['path']] = raw + append_payload = append_root/'payload' + actual = set() + for path in append_payload.rglob('*'): + publisher._plain(path) + if path.is_file(): + actual.add(path.relative_to(append_payload).as_posix()) + if actual != APPEND_NAMES or set(payload)&APPEND_NAMES: + raise ValueError('Acceptance append payload must match its exact additive inventory') + for name, expected in entries.items(): + raw = publisher._bytes(append_payload/name, publisher.MAX_FILE_BYTES) + if original.record(raw) != expected: + raise ValueError('Acceptance append differs from the published receipt') + publisher._no_private_artifact_bytes(name, raw) + payload[name] = raw + return base, payload + + +def stage(workstation, evidence, output, source_commit, expected_remote_commit, + *, base_plan=DEFAULT_BASE, append_publication=DEFAULT_APPEND): + from dvidia_training.workstation import inspect_export + if any(type(value) is not str or re.fullmatch('[a-f0-9]{40}', value) is None + for value in (source_commit, expected_remote_commit)): + raise ValueError('Exact source and remote parent commits are required') + root, evidence_root, destination, base_path, append_root = map(lambda p: Path(p).absolute(), + (workstation, evidence, output, base_plan, append_publication)) + for path in (root, evidence_root, destination, base_path, append_root): + publisher._plain(path) + if root == evidence_root or root in evidence_root.parents or evidence_root in root.parents: + raise ValueError('Workstation and evidence require separate directory trees') + if destination.exists() or any(destination == p or p in destination.parents for p in + (root, evidence_root, base_path.parent, append_root)): + raise ValueError('Editorial output must be fresh and outside input trees') + base, payload = _reconstruct(base_path, append_root, expected_remote_commit) + inspect_export(root) + inspect_export(base_path.parent/'space'/NAMESPACE) + old = {name[len(NAMESPACE)+1:]: raw for name, raw in payload.items() if name.startswith(NAMESPACE+'/')} + updated = {} + for path in root.rglob('*'): + publisher._plain(path) + if path.is_file(): + updated[path.relative_to(root).as_posix()] = publisher._bytes(path, publisher.MAX_FILE_BYTES) + if not old or set(old) != set(updated): + raise ValueError('Editorial update must retain the exact prior runtime inventory') + changed = {name for name in old if old[name] != updated[name]} + if changed != MUTABLE: + raise ValueError('Editorial update must change only HTML and its integrity seal') + if _ExecutableHTML(old['index.html']).scripts != _ExecutableHTML(updated['index.html']).scripts: + raise ValueError('Editorial update must preserve executable scripts exactly') + before, after = [json.loads(data['workstation-integrity.json']) for data in (old, updated)] + expected = json.loads(original.encoded(before)) + expected['files']['index.html'] = original.record(updated['index.html']) + if after != expected: + raise ValueError('Editorial integrity seal may update only the HTML record') + if any(name.startswith(EVIDENCE_NAMESPACE+'/') for name in payload): + raise ValueError('Editorial evidence requires a fresh namespace') + proof = original.read_evidence(evidence_root) + for name in MUTABLE: + publisher._no_private_artifact_bytes(NAMESPACE+'/'+name, updated[name]) + payload[NAMESPACE+'/'+name] = updated[name] + seal = {'schema': 'dvidia.workstation-editorial-evidence/v1', 'source_commit': source_commit, + 'prior_publication_commit': expected_remote_commit, + 'scope': 'HTML layout and copy only; no new physics or performance benchmark', + 'prior_workstation_integrity': original.record(old['workstation-integrity.json']), + 'workstation_integrity': original.record(updated['workstation-integrity.json']), + 'changed_workstation_files': sorted(changed), 'runtime_and_assets_unchanged': True, + 'files': {name: original.record(raw) for name, raw in sorted(proof.items())}} + proof[original.EVIDENCE_SEAL] = original.encoded(seal) + payload.update({EVIDENCE_NAMESPACE+'/'+name: raw for name, raw in proof.items()}) + provenance = json.loads(payload['provenance.json']) + live = provenance['live_workstation'] + if live['files'] != {name: original.record(raw) for name, raw in old.items()} or 'editorial' in live: + raise ValueError('Prior workstation provenance must match and retain its historical entries') + live['editorial'] = {'path': EVIDENCE_NAMESPACE, 'source_commit': source_commit, + 'prior_source_commit': live['source_commit'], 'prior_publication_commit': expected_remote_commit, + 'integrity': original.record(proof[original.EVIDENCE_SEAL])} + live['source_commit'] = source_commit + live['files'] = {name: original.record(raw) for name, raw in updated.items()} + payload['provenance.json'] = original.encoded(provenance) + plan = {**base, 'source_commit': source_commit, 'expected_remote_commit': expected_remote_commit, + 'remove_files': [], 'total_bytes': sum(map(len, payload.values())), + 'repository': {**base['repository'], 'files': [ + {'path': name, **original.record(raw)} for name, raw in sorted(payload.items())]}} + if len(payload) > publisher.MAX_FILES or plan['total_bytes'] > publisher.MAX_TOTAL_BYTES: + raise ValueError('Editorial publication exceeds its bounded budget') + destination.parent.mkdir(parents=True, exist_ok=True) + staging = Path(tempfile.mkdtemp(prefix='.workstation-editorial-', dir=destination.parent)) + try: + for name, raw in payload.items(): + path = staging/'space'/name + path.parent.mkdir(parents=True, exist_ok=True) + with path.open('xb') as stream: + stream.write(raw) + (staging/'publication-plan.json').write_bytes(original.encoded(plan)) + inspect_export(staging/'space'/NAMESPACE) + publisher.checked_plan(staging/'publication-plan.json') + if destination.exists() or destination.is_symlink(): + raise ValueError('Editorial output must remain fresh') + staging.rename(destination) + finally: + if staging.exists(): + shutil.rmtree(staging) + return {'plan': str(destination/'publication-plan.json'), 'files': len(payload), + 'evidence_files': len(proof), 'total_bytes': plan['total_bytes'], + 'changed_workstation_files': sorted(changed), 'prior_files_retained': len(payload)-len(proof)} + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + for name in ('workstation', 'evidence', 'output', 'source-commit', 'expected-remote-commit'): + parser.add_argument('--'+name, required=True) + parser.add_argument('--base-plan', default=DEFAULT_BASE) + parser.add_argument('--append-publication', default=DEFAULT_APPEND) + print(json.dumps(stage(**vars(parser.parse_args())), indent=2)) diff --git a/publishing/huggingface/prepare_workstation_mirror.py b/publishing/huggingface/prepare_workstation_mirror.py new file mode 100644 index 0000000..d22fafb --- /dev/null +++ b/publishing/huggingface/prepare_workstation_mirror.py @@ -0,0 +1,142 @@ +"""Stage a verified workstation asset mirror while preserving prior evidence.""" +from __future__ import annotations + +import argparse +import json +from pathlib import Path +import re +import shutil +import tempfile + +import prepare_workstation as original +import publish_robot_sim as publisher + +NAMESPACE = original.NAMESPACE +EVIDENCE_NAMESPACE = 'workstation-mirror/v01' +MUTABLE = {'workstation.bundle.js', 'workstation_worker.bundle.js', 'model.json', + 'workstation-integrity.json', 'README.md'} + + +def _check_metadata(old, updated): + before, after = (json.loads(data['model.json']) for data in (old, updated)) + if type(before) is not dict or type(after) is not dict: + raise ValueError('Mirror update requires model dictionaries') + old_geometry, new_geometry = before.get('geometry_binary'), after.get('geometry_binary') + if type(old_geometry) is not dict or type(new_geometry) is not dict: + raise ValueError('Mirror update requires geometry descriptors') + checksum = original.record(old['geometry.bin.gz'])['sha256'] + if ('compressed_sha256' in old_geometry and old_geometry['compressed_sha256'] != checksum): + raise ValueError('Prior compressed geometry checksum does not match unchanged bytes') + if new_geometry.get('compressed_sha256') != checksum: + raise ValueError('Mirror compressed geometry checksum must match unchanged bytes') + before = {**before, 'geometry_binary': {key: value for key, value in old_geometry.items() + if key != 'compressed_sha256'}} + after = {**after, 'geometry_binary': {key: value for key, value in new_geometry.items() + if key != 'compressed_sha256'}} + if json.dumps(before, sort_keys=True, allow_nan=False) != json.dumps(after, sort_keys=True, allow_nan=False): + raise ValueError('Mirror update may add only the compressed geometry checksum to model metadata') + + +def stage(base_plan, workstation, evidence, output, source_commit, expected_remote_commit): + from dvidia_training.workstation import inspect_export + if any(type(value) is not str or re.fullmatch('[a-f0-9]{40}', value) is None + for value in (source_commit, expected_remote_commit)): + raise ValueError('Exact source and remote parent commits are required') + base_plan, root, evidence_root, destination = map(lambda p: Path(p).absolute(), + (base_plan, workstation, evidence, output)) + for path in (root, evidence_root, destination): + publisher._plain(path) + if root == evidence_root or root in evidence_root.parents or evidence_root in root.parents: + raise ValueError('Workstation and evidence inputs require separate directory trees') + inputs = (root, evidence_root, base_plan.parent) + if destination.exists() or any(destination == p or p in destination.parents for p in inputs): + raise ValueError('Mirror update output must be fresh and outside input trees') + base = publisher.checked_plan(base_plan) + inspect_export(root) + proof = original.read_evidence(evidence_root) + payload = {} + for entry in base['repository']['files']: + raw = publisher._bytes(base_plan.parent/'space'/entry['path'], publisher.MAX_FILE_BYTES) + if original.record(raw) != {key: entry[key] for key in ('bytes', 'sha256')}: + raise ValueError('Prior artifact changed during staging') + payload[entry['path']] = raw + old = {name[len(NAMESPACE)+1:]: raw for name, raw in payload.items() if name.startswith(NAMESPACE+'/')} + if not old or any(name.startswith(EVIDENCE_NAMESPACE+'/') for name in payload): + raise ValueError('Requires a published workstation and a fresh mirror evidence namespace') + inspect_export(base_plan.parent/'space'/NAMESPACE) + updated = {} + for path in root.rglob('*'): + publisher._plain(path) + if path.is_file(): + updated[path.relative_to(root).as_posix()] = publisher._bytes(path, publisher.MAX_FILE_BYTES) + if set(old) != set(updated): + raise ValueError('Mirror update must retain the exact prior runtime inventory') + changed = {name for name in old if old[name] != updated[name]} + if changed-MUTABLE: + raise ValueError('Mirror update changed physics, renderer geometry, native engine, meshes or notices') + _check_metadata(old, updated) + for name, raw in updated.items(): + publisher._artifact_name(NAMESPACE+'/'+name) + publisher._no_private_artifact_bytes(NAMESPACE+'/'+name, raw) + payload[NAMESPACE+'/'+name] = raw + seal = {'schema': 'dvidia.workstation-mirror-evidence/v1', 'source_commit': source_commit, + 'prior_publication_commit': expected_remote_commit, + 'scope': 'SHA-256-verified DVIDIA research mirror delivery; original binary, physics and evidence bytes retained', + 'old_workstation_integrity': original.record(old['workstation-integrity.json']), + 'workstation_integrity': original.record(updated['workstation-integrity.json']), + 'changed_files': sorted(changed), 'added_files': [], + 'native_engine_bytes_unchanged': True, 'prior_native_metadata_unchanged': True, + 'compressed_resources_unchanged': True, + 'files': {name: original.record(raw) for name, raw in sorted(proof.items())}} + proof[original.EVIDENCE_SEAL] = original.encoded(seal) + payload.update({EVIDENCE_NAMESPACE+'/'+name: raw for name, raw in proof.items()}) + provenance = json.loads(payload['provenance.json']) + live = provenance['live_workstation'] + if live['files'] != {name: original.record(raw) for name, raw in old.items()}: + raise ValueError('Prior workstation provenance differs from its published inventory') + if 'mirror' in live: + raise ValueError('Prior mirror provenance must not be replaced') + live['mirror'] = {'path': EVIDENCE_NAMESPACE, 'source_commit': source_commit, + 'prior_source_commit': live['source_commit'], + 'prior_publication_commit': expected_remote_commit, + 'integrity': original.record(proof[original.EVIDENCE_SEAL])} + live['source_commit'] = source_commit + live['files'] = {name: original.record(raw) for name, raw in updated.items()} + payload['provenance.json'] = original.encoded(provenance) + payload['README.md'] += (f'\n\nThe Hugging Face workstation can load its three compressed simulator resources from ' + f'DVIDIA’s research mirror, with exact byte bounds and SHA-256 verification. ' + f'Original engine, mesh, geometry and benchmark bytes are retained. ' + f'[Mirror validation]({EVIDENCE_NAMESPACE}/README.md).\n').encode() + plan = {**base, 'source_commit': source_commit, 'expected_remote_commit': expected_remote_commit, + 'remove_files': [], 'total_bytes': sum(map(len, payload.values())), + 'repository': {**base['repository'], 'files': [ + {'path': name, **original.record(raw)} for name, raw in sorted(payload.items())]}} + if len(payload) > publisher.MAX_FILES or plan['total_bytes'] > publisher.MAX_TOTAL_BYTES: + raise ValueError('Mirror publication exceeds its file or byte budget') + destination.parent.mkdir(parents=True, exist_ok=True) + staging = Path(tempfile.mkdtemp(prefix='.workstation-mirror-', dir=destination.parent)) + try: + for name, raw in payload.items(): + path = staging/'space'/name + path.parent.mkdir(parents=True, exist_ok=True) + with path.open('xb') as stream: + stream.write(raw) + (staging/'publication-plan.json').write_bytes(original.encoded(plan)) + inspect_export(staging/'space'/NAMESPACE) + publisher.checked_plan(staging/'publication-plan.json') + if destination.exists() or destination.is_symlink(): + raise ValueError('Mirror output must remain fresh') + staging.rename(destination) + finally: + if staging.exists(): + shutil.rmtree(staging) + return {'plan': str(destination/'publication-plan.json'), 'files': len(payload), + 'evidence_files': len(proof), 'total_bytes': plan['total_bytes'], + 'changed_workstation_files': sorted(changed), 'added_workstation_files': []} + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + for name in ('base-plan', 'workstation', 'evidence', 'output', 'source-commit', 'expected-remote-commit'): + parser.add_argument('--'+name, required=True) + print(json.dumps(stage(**vars(parser.parse_args())), indent=2)) diff --git a/publishing/huggingface/prepare_workstation_patch.py b/publishing/huggingface/prepare_workstation_patch.py new file mode 100644 index 0000000..dafffd2 --- /dev/null +++ b/publishing/huggingface/prepare_workstation_patch.py @@ -0,0 +1,144 @@ +"""Stage a bounded workstation download fix without rewriting published evidence.""" +from __future__ import annotations + +import argparse +import json +from pathlib import Path +import re +import shutil +import tempfile +import zlib + +import prepare_workstation as original +import publish_robot_sim as publisher + +NAMESPACE = original.NAMESPACE +EVIDENCE_NAMESPACE = 'workstation-download-fix/v01' +MUTABLE = {'index.html', 'workstation.bundle.js', 'workstation_worker.bundle.js', + 'workstation.json', 'workstation-integrity.json', 'README.md'} +ADDED = {'mujoco.wasm.gz'} + + +def _check_metadata(old, updated): + before, after = (json.loads(data['workstation.json']) for data in (old, updated)) + descriptors = {'native_wasm', 'wasm_bundle'} + if (type(before) is not dict or type(after) is not dict or descriptors & before.keys() + or not descriptors <= after.keys() + or before != {key: value for key, value in after.items() if key not in descriptors}): + raise ValueError('Download fix must preserve all prior metadata and add only native WASM descriptors') + native, compressed = old['mujoco.wasm'], updated['mujoco.wasm.gz'] + if after['native_wasm'] != {'path': 'mujoco.wasm', **original.record(native)}: + raise ValueError('Native WASM descriptor must match unchanged published engine bytes') + if after['wasm_bundle'] != {'path': 'mujoco.wasm.gz', 'compression': 'gzip', + **original.record(compressed), 'uncompressed_bytes': len(native)}: + raise ValueError('WASM bundle descriptor must match compressed and native byte bounds') + decoder = zlib.decompressobj(16+zlib.MAX_WBITS) + try: + decoded = decoder.decompress(compressed, len(native)+1) + except zlib.error as exc: + raise ValueError('WASM bundle is not valid bounded gzip') from exc + if (decoded != native or not decoder.eof or decoder.unconsumed_tail or decoder.unused_data): + raise ValueError('WASM bundle must decode exactly to the unchanged engine with no trailing data') + + +def stage(base_plan, workstation, evidence, output, source_commit, expected_remote_commit): + from dvidia_training.workstation import inspect_export + if any(type(value) is not str or re.fullmatch('[a-f0-9]{40}', value) is None + for value in (source_commit, expected_remote_commit)): + raise ValueError('Exact source and remote parent commits are required') + base_plan, root, evidence_root, destination = map(lambda p: Path(p).absolute(), + (base_plan, workstation, evidence, output)) + for path in (root, evidence_root, destination): + publisher._plain(path) + if root == evidence_root or root in evidence_root.parents or evidence_root in root.parents: + raise ValueError('Workstation and evidence inputs require separate directory trees') + inputs = (root, evidence_root, base_plan.parent) + if destination.exists() or any(destination == p or p in destination.parents for p in inputs): + raise ValueError('Download fix output must be fresh and outside input trees') + base = publisher.checked_plan(base_plan) + inspect_export(root) + proof = original.read_evidence(evidence_root) + payload = {} + for entry in base['repository']['files']: + raw = publisher._bytes(base_plan.parent/'space'/entry['path'], publisher.MAX_FILE_BYTES) + if original.record(raw) != {key: entry[key] for key in ('bytes', 'sha256')}: + raise ValueError('Prior artifact changed during staging') + payload[entry['path']] = raw + old = {name[len(NAMESPACE)+1:]: raw for name, raw in payload.items() if name.startswith(NAMESPACE+'/')} + if not old or any(name.startswith(EVIDENCE_NAMESPACE+'/') for name in payload): + raise ValueError('Requires a published workstation and a fresh download-fix evidence namespace') + inspect_export(base_plan.parent/'space'/NAMESPACE) + updated = {} + for path in root.rglob('*'): + publisher._plain(path) + if path.is_file(): + updated[path.relative_to(root).as_posix()] = publisher._bytes(path, publisher.MAX_FILE_BYTES) + if not set(old) <= set(updated) or set(updated)-set(old) != ADDED: + raise ValueError('Download fix must retain the prior inventory and add only mujoco.wasm.gz') + changed = {name for name in old if old[name] != updated[name]} + if changed-MUTABLE: + raise ValueError('Download fix changed physics, renderer geometry, native engine, meshes or notices') + _check_metadata(old, updated) + for name, raw in updated.items(): + publisher._artifact_name(NAMESPACE+'/'+name) + publisher._no_private_artifact_bytes(NAMESPACE+'/'+name, raw) + payload[NAMESPACE+'/'+name] = raw + seal = {'schema': 'dvidia.workstation-download-fix-evidence/v1', 'source_commit': source_commit, + 'prior_publication_commit': expected_remote_commit, + 'scope': 'Download transport and browser validation; original physics and evidence retained', + 'old_workstation_integrity': original.record(old['workstation-integrity.json']), + 'workstation_integrity': original.record(updated['workstation-integrity.json']), + 'changed_files': sorted(changed), 'added_files': sorted(ADDED), + 'native_engine_bytes_unchanged': True, 'prior_native_metadata_unchanged': True, + 'files': {name: original.record(raw) for name, raw in sorted(proof.items())}} + proof[original.EVIDENCE_SEAL] = original.encoded(seal) + payload.update({EVIDENCE_NAMESPACE+'/'+name: raw for name, raw in proof.items()}) + provenance = json.loads(payload['provenance.json']) + live = provenance['live_workstation'] + if live['files'] != {name: original.record(raw) for name, raw in old.items()}: + raise ValueError('Prior workstation provenance differs from its published inventory') + if 'download_fix' in live: + raise ValueError('Prior download-fix provenance must not be replaced') + live['download_fix'] = {'path': EVIDENCE_NAMESPACE, 'source_commit': source_commit, + 'prior_source_commit': live['source_commit'], + 'prior_publication_commit': expected_remote_commit, + 'integrity': original.record(proof[original.EVIDENCE_SEAL])} + live['source_commit'] = source_commit + live['files'] = {name: original.record(raw) for name, raw in updated.items()} + payload['provenance.json'] = original.encoded(provenance) + payload['README.md'] += (f'\n\nThe workstation download fix adds compressed WASM transport and ' + f'bounded download recovery. Original engine, mesh and benchmark bytes are retained. ' + f'[Download-fix validation]({EVIDENCE_NAMESPACE}/README.md).\n').encode() + plan = {**base, 'source_commit': source_commit, 'expected_remote_commit': expected_remote_commit, + 'remove_files': [], 'total_bytes': sum(map(len, payload.values())), + 'repository': {**base['repository'], 'files': [ + {'path': name, **original.record(raw)} for name, raw in sorted(payload.items())]}} + if len(payload) > publisher.MAX_FILES or plan['total_bytes'] > publisher.MAX_TOTAL_BYTES: + raise ValueError('Download-fix publication exceeds its file or byte budget') + destination.parent.mkdir(parents=True, exist_ok=True) + staging = Path(tempfile.mkdtemp(prefix='.workstation-download-fix-', dir=destination.parent)) + try: + for name, raw in payload.items(): + path = staging/'space'/name + path.parent.mkdir(parents=True, exist_ok=True) + with path.open('xb') as stream: + stream.write(raw) + (staging/'publication-plan.json').write_bytes(original.encoded(plan)) + inspect_export(staging/'space'/NAMESPACE) + publisher.checked_plan(staging/'publication-plan.json') + if destination.exists() or destination.is_symlink(): + raise ValueError('Download-fix output must remain fresh') + staging.rename(destination) + finally: + if staging.exists(): + shutil.rmtree(staging) + return {'plan': str(destination/'publication-plan.json'), 'files': len(payload), + 'evidence_files': len(proof), 'total_bytes': plan['total_bytes'], + 'changed_workstation_files': sorted(changed), 'added_workstation_files': sorted(ADDED)} + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + for name in ('base-plan', 'workstation', 'evidence', 'output', 'source-commit', 'expected-remote-commit'): + parser.add_argument('--'+name, required=True) + print(json.dumps(stage(**vars(parser.parse_args())), indent=2)) diff --git a/publishing/huggingface/publish_robot_sim.py b/publishing/huggingface/publish_robot_sim.py index c46fe96..3d6a401 100644 --- a/publishing/huggingface/publish_robot_sim.py +++ b/publishing/huggingface/publish_robot_sim.py @@ -19,10 +19,10 @@ REPO_ID = 'Dvidia/robot-simulation-lab' KIND = 'dvidia.robot-simulation-lab-publication' MAX_FILE_BYTES = 32*1024*1024 -# v0.5 retains every prior receipt and adds at most three complete cohorts. -# Only the stored payload cap increases; decoded/per-file bounds stay fixed. -MAX_TOTAL_BYTES = 512*1024*1024 -MAX_FILES = 700 # Prior receipts plus the bounded three-arm shoe asset library. +# Retain the existing 627-file lab, then add the bounded live export and evidence. +# Per-file and decoded-data bounds stay fixed; this only raises complete storage. +MAX_TOTAL_BYTES = 768*1024*1024 +MAX_FILES = 900 # Prior evidence plus up to128 export and128 evidence files. MAX_RELIABILITY_COHORTS = 3 ALLOWED_SUFFIXES = {'.md', '.html', '.js', '.json', '.txt', '.png', '.bin', '.gz'} SHA = re.compile(r'(?:[a-f0-9]{40}|[a-f0-9]{64})') @@ -33,6 +33,7 @@ RELIABILITY_COHORT_PATH = re.compile(r'(?:development|confirmation)-(?:0|[1-9][0-9]{0,5})') RELIABILITY_ATTEMPT_PATH = re.compile(r'tasks/piper-reliability-v05/(?:development|confirmation)-(?:0|[1-9][0-9]{0,5})/attempts/[a-z0-9][a-z0-9_.-]{0,159}\.json\.gz') +WORKSTATION_NATIVE_PATH = re.compile(r'workstation/v01/(?:mujoco\.wasm|scene\.xml|assets/[A-Za-z0-9_.-]+\.(?:stl|obj|msh))') def _compressed_attempt(name): return GRIP_ATTEMPT_PATH.fullmatch(name) or CONTACT_ATTEMPT_PATH.fullmatch(name) or RELIABILITY_ATTEMPT_PATH.fullmatch(name) @@ -64,10 +65,13 @@ def _artifact_name(name): or int(relative.parts[2].rsplit('-',1)[1])>999988): raise PublicationError('Reliability evidence requires a bounded cohort and seed namespace.') if (any(p.startswith('.') for p in relative.parts) - or (relative.suffix not in ALLOWED_SUFFIXES and relative.name != 'LICENSE')): + or (relative.suffix not in ALLOWED_SUFFIXES and relative.name != 'LICENSE' + and WORKSTATION_NATIVE_PATH.fullmatch(relative.as_posix()) is None)): raise PublicationError('Unexpected Robot Simulation Lab artifact type.') if relative.suffix in ('.bin', '.gz') and relative.name not in ( 'geometry.bin', 'motion.bin', 'geometry.bin.gz', 'motion.bin.gz'): + if relative.as_posix() in ('workstation/v01/native-assets.bin.gz', 'workstation/v01/mujoco.wasm.gz'): + return relative if _compressed_attempt(relative.as_posix()) is None: raise PublicationError('Only native geometry, recorded motion and scoped PiPER attempt JSON may be published.') return relative @@ -294,7 +298,9 @@ def publish_robot_sim(path): verified_downloads(row,revision,False) result = {'repo_id':REPO_ID,'repo_type':'space','commit':revision, 'url':'https://huggingface.co/spaces/'+REPO_ID,'verified_files':len(row['files']), - 'scope':'Recorded native simulation evidence; no live physics, learned policy or physical robot qualification', + 'scope':('Native simulation evidence and a live browser workstation; no learned policy or physical robot qualification' + if 'workstation/v01/workstation.json' in payload else + 'Recorded native simulation evidence; no live physics, learned policy or physical robot qualification'), 'plan_sha256':plan_digest,'removed_files':removals} _plain(target) target.write_text(json.dumps(result,indent=2)+'\n') diff --git a/publishing/huggingface/robot-simulation-lab/test_prepare.py b/publishing/huggingface/robot-simulation-lab/test_prepare.py index b01db75..8137073 100644 --- a/publishing/huggingface/robot-simulation-lab/test_prepare.py +++ b/publishing/huggingface/robot-simulation-lab/test_prepare.py @@ -412,7 +412,7 @@ def test_v05_three_cohorts_keep_every_original_byte_and_separate_denominators(se entries=[v for k,v in provenance['contact_task_benchmarks'].items() if k.startswith('piper-reliability-v05/')] self.assertEqual(len(entries),3) self.assertTrue(all(r['attempted']==12*len(reliability.VARIANTS) for r in entries)) - self.assertEqual(provenance['publication_byte_bounds']['stored_payload_bytes'],512*1024*1024) + self.assertEqual(provenance['publication_byte_bounds']['stored_payload_bytes'],768*1024*1024) self.assertEqual(provenance['publication_byte_bounds']['per_file_bytes'],32*1024*1024) self.assertIn('PiPER reliability v0.5',(self.output/'space/README.md').read_text()) @@ -813,7 +813,7 @@ def test_v03_retains_all_eighty_four_attempts_and_exact_prior_evidence(self): self.assertEqual(compared['source_integrity'],record(payload['integrity.json'])) self.assertGreater(compared['decoded_bytes'],compared['stored_bytes']) self.assertFalse(compared['learned_policy']) - self.assertEqual(provenance['publication_byte_bounds']['stored_payload_bytes'],512*1024*1024) + self.assertEqual(provenance['publication_byte_bounds']['stored_payload_bytes'],768*1024*1024) self.assertEqual(provenance['publication_byte_bounds']['per_file_bytes'],32*1024*1024) readme=(self.output/'space/README.md').read_text() self.assertIn(comparison,readme) @@ -917,7 +917,7 @@ def test_v04_retains_all_eighty_four_attempts_and_exact_prior_evidence(self): self.assertEqual(compared['source_integrity'],record(payload['integrity.json'])) self.assertGreater(compared['decoded_bytes'],compared['stored_bytes']) self.assertFalse(compared['learned_policy']) - self.assertEqual(provenance['publication_byte_bounds']['stored_payload_bytes'],512*1024*1024) + self.assertEqual(provenance['publication_byte_bounds']['stored_payload_bytes'],768*1024*1024) self.assertEqual(provenance['publication_byte_bounds']['per_file_bytes'],32*1024*1024) readme=(self.output/'space/README.md').read_text() self.assertIn(comparison,readme) diff --git a/publishing/huggingface/test_prepare_asset_library.py b/publishing/huggingface/test_prepare_asset_library.py index b770088..5d4fb31 100644 --- a/publishing/huggingface/test_prepare_asset_library.py +++ b/publishing/huggingface/test_prepare_asset_library.py @@ -73,7 +73,7 @@ def test_reader_rejects_hidden_files_private_paths_and_symlinks(self): with self.assertRaises(publisher.PublicationError):prepare.read_payload(self.library) def test_reader_and_publisher_enforce_file_and_byte_budgets(self): - self.assertEqual(publisher.MAX_FILES,700) + self.assertEqual(publisher.MAX_FILES,900) with patch.object(prepare,'MAX_LIBRARY_FILES',1),self.assertRaises(ValueError):prepare.read_payload(self.library) with patch.object(prepare,'MAX_LIBRARY_BYTES',1),self.assertRaises(ValueError):prepare.read_payload(self.library) with patch.object(publisher,'MAX_FILES',5),self.assertRaises(publisher.PublicationError):publisher.checked_plan(self.plan) diff --git a/publishing/huggingface/test_prepare_workstation.py b/publishing/huggingface/test_prepare_workstation.py new file mode 100644 index 0000000..939eb4b --- /dev/null +++ b/publishing/huggingface/test_prepare_workstation.py @@ -0,0 +1,217 @@ +"""Data-only workstation evidence staging, with no credentials or native engine.""" +import json +from pathlib import Path +import struct +import tempfile +import unittest +from unittest.mock import patch +import zlib + +import prepare_workstation as prepare +import publish_robot_sim as publisher + + +def png(metadata=False): + def chunk(kind, raw): + return struct.pack('>I', len(raw))+kind+raw+struct.pack('>I', zlib.crc32(kind+raw)&0xffffffff) + return (b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR', struct.pack('>IIBBBBB', 1, 1, 8, 2, 0, 0, 0)) + +(chunk(b'tEXt', b'Comment\0metadata') if metadata else b'') + +chunk(b'IDAT', zlib.compress(b'\0\x10\x20\x30'))+chunk(b'IEND', b'')) + + +class WorkstationPublicationTests(unittest.TestCase): + def setUp(self): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.root = Path(temporary.name).resolve() + self.space = self.root/'base/space' + self.space.mkdir(parents=True) + self.original = { + 'README.md': b'---\nsdk: static\napp_file: index.html\nlicense: mit\n---\nPrior card\n', + 'index.html': b'
Prior assets
', + 'LICENSE': b'MIT', 'provenance.json': b'{"prior":"preserved"}', + 'tasks/prior/report.json': b'{"all_failures_retained":true}', + 'asset-library/v01/README.md': b'Original shoe library\n', + 'replay/geometry.bin': b'Original native geometry'} + for name, raw in self.original.items(): + path = self.space/name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(raw) + self.plan = self.root/'base/publication-plan.json' + self.refresh_base() + self.workstation = self.root/'native' + self.workstation.mkdir() + self.native_files = { + 'index.html': b'Live simulator', 'scene.xml': b'', + 'mujoco.wasm': b'\0asm\1\0\0\0', 'model.json': b'{}', + 'workstation.json': b'{}', 'workstation-integrity.json': b'{}', + 'geometry.bin.gz': b'fixture geometry', 'LICENSE': b'MIT', 'README.md': b'Native scene guide'} + for name, raw in self.native_files.items(): + (self.workstation/name).write_bytes(raw) + self.evidence = self.root/'evidence' + self.evidence.mkdir() + self.evidence_files = {'README.md': b'Complete attempts and failures.\n', + 'confirmation/report.json': b'{"passed":false,"attempts":20}', + 'browser/desktop.png': png()} + for name, raw in self.evidence_files.items(): + path = self.evidence/name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(raw) + guard = patch.object(publisher, 'client', side_effect=AssertionError('Credentials forbidden')) + guard.start() + self.addCleanup(guard.stop) + + def refresh_base(self): + self.plan.write_bytes(prepare.encoded({ + 'kind': publisher.KIND, 'schema_version': 1, 'namespace': 'Dvidia', 'private': False, + 'source_commit': 'a'*40, 'expected_remote_commit': 'b'*40, 'remove_files': [], + 'repository': {'repo_id': publisher.REPO_ID, 'repo_type': 'space', 'space_sdk': 'static', + 'directory': 'space', 'files': [{'path': name, **prepare.record(raw)} for name, raw in self.original.items()]}, + 'total_bytes': sum(map(len, self.original.values()))})) + + def inspect_native(self, directory): + root = Path(directory) + actual = {p.relative_to(root).as_posix():p.read_bytes() for p in root.rglob('*') if p.is_file()} + if actual != self.native_files: + raise ValueError('Strict native export received different bytes or extra evidence') + return {'file_count':len(actual)} + + def stage(self, name='output', **kwargs): + with patch('dvidia_training.workstation.inspect_export', side_effect=self.inspect_native): + return prepare.stage(self.plan, self.workstation, self.root/name, 'c'*40, 'd'*40, + evidence=kwargs.get('evidence', self.evidence)) + + def test_preserves_prior_results_and_strict_native_namespace(self): + result = self.stage() + output = self.root/'output/space' + for name, raw in self.original.items(): + if name not in {'README.md', 'index.html', 'provenance.json'}: + self.assertEqual((output/name).read_bytes(), raw) + self.inspect_native(output/prepare.NAMESPACE) + for name, raw in self.evidence_files.items(): + self.assertEqual((output/prepare.EVIDENCE_NAMESPACE/name).read_bytes(), raw) + if name in self.native_files: + self.assertEqual((output/prepare.NAMESPACE/name).read_bytes(), self.native_files[name]) + else: + self.assertFalse((output/prepare.NAMESPACE/name).exists()) + provenance = json.loads((output/'provenance.json').read_bytes()) + self.assertEqual(provenance['prior'], 'preserved') + evidence = provenance['live_workstation']['evidence'] + self.assertEqual(evidence['path'], prepare.EVIDENCE_NAMESPACE) + self.assertEqual(evidence['source_commit'], 'c'*40) + seal_bytes = (output/prepare.EVIDENCE_NAMESPACE/prepare.EVIDENCE_SEAL).read_bytes() + self.assertEqual(evidence['integrity'], prepare.record(seal_bytes)) + seal = json.loads(seal_bytes) + self.assertEqual(seal['source_commit'], 'c'*40) + self.assertEqual(seal['workstation_integrity'], prepare.record(self.native_files['workstation-integrity.json'])) + self.assertEqual(seal['files'], {name:prepare.record(raw) for name, raw in self.evidence_files.items()}) + self.assertIn(b'workstation-evidence/v01/README.md', (output/'README.md').read_bytes()) + plan = publisher.checked_plan(self.root/'output/publication-plan.json') + self.assertEqual(plan['expected_remote_commit'], 'd'*40) + self.assertEqual(plan['remove_files'], []) + self.assertEqual(result['added_files'], len(self.native_files)) + self.assertEqual(result['evidence_files'], len(self.evidence_files)+1) + + def test_rejects_tampered_prior_data_and_existing_output_before_overwrite(self): + (self.space/'tasks/prior/report.json').write_bytes(b'changed') + with self.assertRaises(publisher.PublicationError): + self.stage() + self.assertFalse((self.root/'output').exists()) + (self.space/'tasks/prior/report.json').write_bytes(self.original['tasks/prior/report.json']) + (self.root/'output').mkdir() + (self.root/'output/keep.md').write_text('keep') + with self.assertRaises(ValueError): + self.stage() + self.assertEqual((self.root/'output/keep.md').read_text(), 'keep') + + def test_prior_artifact_mutation_during_staging_is_rejected(self): + def inspect_and_mutate(directory): + result = self.inspect_native(directory) + (self.space/'tasks/prior/report.json').write_bytes(b'changed after prior verification') + return result + with patch('dvidia_training.workstation.inspect_export', side_effect=inspect_and_mutate): + with self.assertRaisesRegex(ValueError, 'Prior artifact changed'): + prepare.stage(self.plan, self.workstation, self.root/'output', 'c'*40, 'd'*40, evidence=self.evidence) + self.assertFalse((self.root/'output').exists()) + + def test_rejects_replacement_of_either_prior_release_namespace(self): + for prefix in (prepare.NAMESPACE, prepare.EVIDENCE_NAMESPACE): + name = prefix+'/prior.json' + self.original[name] = b'{}' + path = self.space/name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b'{}') + self.refresh_base() + with self.subTest(prefix=prefix), self.assertRaisesRegex(ValueError, 'replace'): + self.stage() + self.assertFalse((self.root/'output').exists()) + del self.original[name] + path.unlink() + self.refresh_base() + + def test_evidence_requires_separate_input_tree_and_readme(self): + for folder in (self.workstation, self.workstation/'evidence', self.root): + with self.subTest(folder=folder), self.assertRaisesRegex(ValueError, 'separate'): + self.stage(evidence=folder) + (self.evidence/'README.md').unlink() + with self.assertRaisesRegex(ValueError, 'README'): + self.stage() + self.assertFalse((self.root/'output').exists()) + + def test_only_safe_data_paths_and_extensions_are_allowed(self): + for name in ('extra.js', 'extra.html', 'extra.xml', 'model.wasm', '.hidden.json', + 'space name.json', 'a:b.json', prepare.EVIDENCE_SEAL): + path = self.evidence/name + path.write_bytes(b'{}') + with self.subTest(name=name), self.assertRaises((ValueError, publisher.PublicationError)): + prepare.read_evidence(self.evidence) + path.unlink() + alias = self.evidence/'alias.json' + alias.symlink_to(self.evidence/'confirmation/report.json') + with self.assertRaises(publisher.PublicationError): + prepare.read_evidence(self.evidence) + + def test_private_paths_and_tokens_are_checked_after_json_unescaping(self): + values = [b'{"path":"\\u002fUsers\\u002fsomeone\\u002fprivate"}', + b'{"path":"C:\\\\Users\\\\someone\\\\private"}', + prepare.encoded({'token':'github_pat_'+'x'*40}), + prepare.encoded({'token':'hf_'+'x'*40}), + b'{"path":"/private/tmp/receipt.json"}'] + for raw in values: + (self.evidence/'private.json').write_bytes(raw) + with self.subTest(raw=raw), self.assertRaises((ValueError, publisher.PublicationError)): + prepare.read_evidence(self.evidence) + self.assertFalse((self.root/'output').exists()) + + def test_json_rejects_nonfinite_duplicates_and_excessive_depth(self): + for raw in (b'{"x":NaN}', b'{"x":1,"x":2}', b'['*65+b'0'+b']'*65, b'\xff'): + (self.evidence/'invalid.json').write_bytes(raw) + with self.subTest(raw=raw[:40]), self.assertRaises(ValueError): + prepare.read_evidence(self.evidence) + + def test_png_rejects_text_metadata_bogus_images_and_trailing_payload(self): + for raw in (b'not png', png(metadata=True), png()+b'private trailing payload', png()[:-5]): + (self.evidence/'browser/desktop.png').write_bytes(raw) + with self.subTest(raw=raw[:30]), self.assertRaises(ValueError): + prepare.read_evidence(self.evidence) + + def test_evidence_and_total_budgets_apply_before_output_creation(self): + for constant, value in [('MAX_EVIDENCE_FILES', 1), ('MAX_EVIDENCE_BYTES', 2)]: + with patch.object(prepare, constant, value), self.assertRaises(ValueError): + self.stage() + self.assertFalse((self.root/'output').exists()) + with patch.object(publisher, 'MAX_TOTAL_BYTES', sum(map(len, self.original.values()))), self.assertRaises(ValueError): + self.stage() + self.assertFalse((self.root/'output').exists()) + + def test_final_inspection_failure_cleans_staging_and_preserves_inputs(self): + with patch('dvidia_training.workstation.inspect_export', side_effect=[{}, ValueError('changed bytes')]): + with self.assertRaisesRegex(ValueError, 'changed bytes'): + prepare.stage(self.plan, self.workstation, self.root/'output', 'c'*40, 'd'*40, evidence=self.evidence) + self.assertFalse((self.root/'output').exists()) + self.assertFalse(list(self.root.glob('.workstation-publication-*'))) + self.inspect_native(self.workstation) + + +if __name__ == '__main__': + unittest.main() diff --git a/publishing/huggingface/test_prepare_workstation_delivery.py b/publishing/huggingface/test_prepare_workstation_delivery.py new file mode 100644 index 0000000..9551359 --- /dev/null +++ b/publishing/huggingface/test_prepare_workstation_delivery.py @@ -0,0 +1,82 @@ +"""Delivery revisions preserve physics and every original public evidence byte.""" +import json +import unittest +from unittest.mock import patch + +import prepare_workstation as original +import prepare_workstation_delivery as delivery +import publish_robot_sim as publisher +import test_prepare_workstation as fixtures + + +class DeliveryTests(unittest.TestCase): + refresh_base = fixtures.WorkstationPublicationTests.refresh_base + inspect_native = fixtures.WorkstationPublicationTests.inspect_native + + def setUp(self): + fixtures.WorkstationPublicationTests.setUp(self) + with patch('dvidia_training.workstation.inspect_export', side_effect=self.inspect_native): + original.stage(self.plan, self.workstation, self.root/'first', 'c'*40, 'd'*40, evidence=self.evidence) + self.base = self.root/'first/publication-plan.json' + self.updated = {**self.native_files, + 'index.html': b'Live simulator with the official DVIDIA wordmark', + 'workstation.json': original.encoded({'native_asset_bundle': {'path':'native-assets.bin.gz'}}), + 'workstation-integrity.json': b'{"updated":true}', + 'native-assets.bin.gz': b'bounded gzip fixture'} + self.new = self.root/'new' + self.new.mkdir() + for name, raw in self.updated.items(): + (self.new/name).write_bytes(raw) + + def stage(self): + with patch('dvidia_training.workstation.inspect_export', return_value={}): + return delivery.stage(self.base, self.new, self.evidence, self.root/'delivery', 'e'*40, 'f'*40) + + def test_preserves_original_receipts_and_native_bytes_and_binds_new_transport(self): + self.stage() + old, new = self.root/'first/space', self.root/'delivery/space' + for path in old.rglob('*'): + if not path.is_file(): + continue + name = path.relative_to(old).as_posix() + if name in {'provenance.json', 'README.md'} or name in { + original.NAMESPACE+'/'+value for value in delivery.MUTABLE}: + continue + self.assertEqual(path.read_bytes(), (new/name).read_bytes()) + before = json.loads((old/'provenance.json').read_bytes())['live_workstation'] + after = json.loads((new/'provenance.json').read_bytes())['live_workstation'] + self.assertEqual(before['evidence'], after['evidence']) + self.assertEqual(after['original_source_commit'], 'c'*40) + self.assertEqual(after['source_commit'], 'e'*40) + plan = publisher.checked_plan(self.root/'delivery/publication-plan.json') + self.assertEqual(plan['expected_remote_commit'], 'f'*40) + self.assertEqual(plan['remove_files'], []) + + def test_refuses_physics_changes_or_asset_removal(self): + (self.new/'scene.xml').write_bytes(b'') + with self.assertRaisesRegex(ValueError, 'changed physics'): + self.stage() + (self.new/'scene.xml').write_bytes(self.native_files['scene.xml']) + (self.new/'mujoco.wasm').unlink() + with self.assertRaisesRegex(ValueError, 'retain'): + self.stage() + self.assertFalse((self.root/'delivery').exists()) + + def test_refuses_changed_controller_metadata_and_unknown_extra_files(self): + (self.new/'workstation.json').write_bytes(original.encoded({'controller':'changed', 'native_asset_bundle':{}})) + with self.assertRaisesRegex(ValueError, 'controller'): + self.stage() + (self.new/'workstation.json').write_bytes(self.updated['workstation.json']) + (self.new/'extra.json').write_bytes(b'{}') + with self.assertRaisesRegex(ValueError, 'only its transport bundle'): + self.stage() + + def test_native_bundle_allowlist_is_scoped(self): + publisher._artifact_name('workstation/v01/native-assets.bin.gz') + for name in ('other/native-assets.bin.gz', 'workstation/v02/native-assets.bin.gz'): + with self.assertRaises(publisher.PublicationError): + publisher._artifact_name(name) + + +if __name__ == '__main__': + unittest.main() diff --git a/publishing/huggingface/test_prepare_workstation_editorial.py b/publishing/huggingface/test_prepare_workstation_editorial.py new file mode 100644 index 0000000..dd9ce97 --- /dev/null +++ b/publishing/huggingface/test_prepare_workstation_editorial.py @@ -0,0 +1,196 @@ +"""Editorial releases preserve the fixed runtime and every earlier public receipt.""" +import json +import unittest +from unittest.mock import patch + +import prepare_workstation as original +import prepare_workstation_editorial as prepare +import publish_robot_sim as publisher +import test_prepare_workstation as fixtures + + +class EditorialTests(unittest.TestCase): + refresh_base = fixtures.WorkstationPublicationTests.refresh_base + + def setUp(self): + fixtures.WorkstationPublicationTests.setUp(self) + self.native_files.update({'index.html': b'

Before

', + 'workstation.bundle.js': b'verified mirror loader', 'workstation_worker.bundle.js': b'unchanged physics worker', + 'native-assets.bin.gz': b'unchanged native meshes', 'mujoco.wasm.gz': b'unchanged engine bundle'}) + self.native_files['workstation-integrity.json'] = original.encoded({'schema': 'fixture', + 'scope': 'consistency', 'files': {name: original.record(raw) for name, raw in self.native_files.items() + if name != 'workstation-integrity.json'}}) + self.original.update({original.NAMESPACE+'/'+name: raw for name, raw in self.native_files.items()}) + self.original['provenance.json'] = original.encoded({'prior': 'retained', 'live_workstation': { + 'source_commit': 'a'*40, 'files': {name: original.record(raw) for name, raw in self.native_files.items()}, + 'mirror': {'retained': True}, 'download_fix': {'retained': True}, 'evidence': {'retained': True}}}) + for name, raw in self.original.items(): + path = self.space/name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(raw) + self.refresh_base() + self.append = self.root/'append' + self.append.mkdir() + self.append_files = {name: b'{}' if name.endswith('.json') else b'Prior public acceptance' + for name in sorted(prepare.APPEND_NAMES)} + for name, raw in self.append_files.items(): + path = self.append/'payload'/name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(raw) + self.refresh_receipts() + self.updated = {**self.native_files, 'index.html': + b'

After

Clearer copy.

'} + seal = json.loads(self.native_files['workstation-integrity.json']) + seal['files']['index.html'] = original.record(self.updated['index.html']) + self.updated['workstation-integrity.json'] = original.encoded(seal) + for name, raw in self.updated.items(): + (self.workstation/name).write_bytes(raw) + + def refresh_receipts(self): + digest = original.record(self.plan.read_bytes())['sha256'] + (self.plan.parent/'publication-receipt.json').write_bytes(original.encoded({ + 'repo_id': publisher.REPO_ID, 'repo_type': 'space', 'commit': 'b'*40, + 'plan_sha256': digest, 'verified_files': len(self.original)})) + addition = {'kind': 'dvidia.mirror-public-acceptance-append/v1', 'repo_id': publisher.REPO_ID, + 'parent_commit': 'b'*40, 'source_commit': 'a'*40, 'source_publication_plan_sha256': digest, + 'files': {name: original.record(raw) for name, raw in self.append_files.items()}} + raw = original.encoded(addition) + (self.append/'plan.json').write_bytes(raw) + (self.append/'publication-receipt.json').write_bytes(original.encoded({ + 'repo_id': publisher.REPO_ID, 'repo_type': 'space', 'commit': 'c'*40, 'parent_commit': 'b'*40, + 'plan_sha256': original.record(raw)['sha256'], 'runtime_and_sealed_evidence_unchanged': True, + 'unchanged_existing_files': len(self.original)+1, + 'added_files': [{'path': name, **record} for name, record in addition['files'].items()]})) + + def stage(self, **overrides): + args = dict(workstation=self.workstation, evidence=self.evidence, output=self.root/'output', + source_commit='d'*40, expected_remote_commit='c'*40, + base_plan=self.plan, append_publication=self.append) + args.update(overrides) + with patch('dvidia_training.workstation.inspect_export', return_value={}): + return prepare.stage(**args) + + def test_reconstructs_complete_parent_and_changes_only_html_seal_provenance(self): + result = self.stage() + after = self.root/'output/space' + permitted = {'provenance.json'} | {original.NAMESPACE+'/'+name for name in prepare.MUTABLE} + for name, raw in {**self.original, **self.append_files}.items(): + if name not in permitted: + self.assertEqual((after/name).read_bytes(), raw, name) + live = json.loads((after/'provenance.json').read_bytes())['live_workstation'] + prior = json.loads(self.original['provenance.json'])['live_workstation'] + for name in ('mirror', 'download_fix', 'evidence'): + self.assertEqual(live[name], prior[name]) + self.assertEqual(live['files'], {name: original.record(raw) for name, raw in self.updated.items()}) + self.assertEqual(live['editorial']['prior_source_commit'], 'a'*40) + seal_raw = (after/prepare.EVIDENCE_NAMESPACE/original.EVIDENCE_SEAL).read_bytes() + self.assertEqual(live['editorial']['integrity'], original.record(seal_raw)) + seal = json.loads(seal_raw) + self.assertTrue(seal['runtime_and_assets_unchanged']) + self.assertEqual(seal['files'], {name: original.record(raw) for name, raw in self.evidence_files.items()}) + plan = publisher.checked_plan(self.root/'output/publication-plan.json') + self.assertEqual(plan['expected_remote_commit'], 'c'*40) + self.assertEqual(plan['source_commit'], 'd'*40) + self.assertEqual(plan['remove_files'], []) + self.assertEqual(result['prior_files_retained'], len(self.original)+3) + + def test_refuses_any_non_html_runtime_change_or_inventory_change(self): + for name in set(self.native_files)-prepare.MUTABLE: + (self.workstation/name).write_bytes(b'changed') + with self.subTest(name=name), self.assertRaisesRegex(ValueError, 'only HTML'): + self.stage() + (self.workstation/name).write_bytes(self.updated[name]) + extra = self.workstation/'extra.json' + extra.write_bytes(b'{}') + with self.assertRaisesRegex(ValueError, 'exact prior runtime inventory'): + self.stage() + extra.unlink() + (self.workstation/'scene.xml').unlink() + with self.assertRaisesRegex(ValueError, 'exact prior runtime inventory'): + self.stage() + + def test_refuses_script_and_inline_execution_changes(self): + for html in (b'', b'', + b'Go', b''): + (self.workstation/'index.html').write_bytes(html) + with self.subTest(html=html), self.assertRaisesRegex(ValueError, 'scripts|handlers'): + self.stage() + + def test_seal_can_update_only_exact_html_record(self): + valid = json.loads(self.updated['workstation-integrity.json']) + for field, value in (('scope', 'changed'), ('schema', 'changed'), ('files', {})): + (self.workstation/'workstation-integrity.json').write_bytes(original.encoded({**valid, field: value})) + with self.subTest(field=field), self.assertRaisesRegex(ValueError, 'only the HTML record'): + self.stage() + + def test_rejects_wrong_remote_parent_and_broken_receipt_chain(self): + with self.assertRaisesRegex(ValueError, 'reviewed remote parent'): + self.stage(expected_remote_commit='e'*40) + for path in (self.plan.parent/'publication-receipt.json', self.append/'plan.json', + self.append/'publication-receipt.json'): + old = path.read_bytes() + path.write_bytes(b'{}') + with self.subTest(path=path), self.assertRaisesRegex(ValueError, 'reviewed remote parent'): + self.stage() + path.write_bytes(old) + + def test_rejects_tampered_or_unlisted_acceptance_and_prior_bytes(self): + name = next(iter(self.append_files)) + path = self.append/'payload'/name + path.write_bytes(b'changed') + with self.assertRaisesRegex(ValueError, 'published receipt'): + self.stage() + path.write_bytes(self.append_files[name]) + extra = self.append/'payload/extra.md' + extra.write_bytes(b'unlisted') + with self.assertRaisesRegex(ValueError, 'exact additive inventory'): + self.stage() + extra.unlink() + (self.space/'tasks/prior/report.json').write_bytes(b'changed') + with self.assertRaises(publisher.PublicationError): + self.stage() + + def test_refuses_overwriting_historical_editorial_namespace_or_provenance(self): + for mode in ('namespace', 'provenance'): + if mode == 'namespace': + self.original[prepare.EVIDENCE_NAMESPACE+'/README.md'] = b'old evidence' + else: + del self.original[prepare.EVIDENCE_NAMESPACE+'/README.md'] + (self.space/prepare.EVIDENCE_NAMESPACE/'README.md').unlink() + value = json.loads(self.original['provenance.json']) + value['live_workstation']['editorial'] = {'preserve': True} + self.original['provenance.json'] = original.encoded(value) + for name, raw in self.original.items(): + path = self.space/name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(raw) + self.refresh_base() + self.refresh_receipts() + with self.subTest(mode=mode), self.assertRaisesRegex(ValueError, 'fresh namespace|historical entries'): + self.stage() + + def test_rejects_invalid_commits_nested_output_and_private_evidence(self): + for field in ('source_commit', 'expected_remote_commit'): + with self.subTest(field=field), self.assertRaisesRegex(ValueError, 'Exact source'): + self.stage(**{field: 'main'}) + with self.assertRaisesRegex(ValueError, 'separate'): + self.stage(evidence=self.workstation) + for root in (self.workstation, self.evidence, self.plan.parent, self.append): + with self.subTest(root=root), self.assertRaisesRegex(ValueError, 'fresh and outside'): + self.stage(output=root/'output') + (self.evidence/'private.json').write_bytes(b'{"path":"/Users/private/item"}') + with self.assertRaisesRegex(ValueError, 'private path'): + self.stage() + self.assertFalse((self.root/'output').exists()) + + def test_failed_final_native_inspection_leaves_no_partial_output(self): + with patch('dvidia_training.workstation.inspect_export', side_effect=[{}, {}, ValueError('native mismatch')]): + with self.assertRaisesRegex(ValueError, 'native mismatch'): + prepare.stage(self.workstation, self.evidence, self.root/'output', 'd'*40, 'c'*40, + base_plan=self.plan, append_publication=self.append) + self.assertFalse((self.root/'output').exists()) + self.assertFalse(list(self.root.glob('.workstation-editorial-*'))) + + +if __name__ == '__main__': + unittest.main() diff --git a/publishing/huggingface/test_prepare_workstation_mirror.py b/publishing/huggingface/test_prepare_workstation_mirror.py new file mode 100644 index 0000000..0a36ce4 --- /dev/null +++ b/publishing/huggingface/test_prepare_workstation_mirror.py @@ -0,0 +1,202 @@ +"""Mirror staging cannot alter physics, binaries or earlier public evidence.""" +import gzip +import json +import unittest +from unittest.mock import patch + +import prepare_workstation as original +import prepare_workstation_mirror as prepare +import publish_robot_sim as publisher +import test_prepare_workstation as fixtures + + +class MirrorTests(unittest.TestCase): + refresh_base = fixtures.WorkstationPublicationTests.refresh_base + inspect_native = fixtures.WorkstationPublicationTests.inspect_native + + def setUp(self): + fixtures.WorkstationPublicationTests.setUp(self) + self.model = {'schema': 'model-fixture', 'bodies': ['fixed'], 'geometry_binary': { + 'href': 'geometry.bin.gz', 'compression': 'gzip', 'bytes': 16, + 'compressed_bytes': len(self.native_files['geometry.bin.gz']), 'sha256': 'a'*64}} + self.native_files.update({ + 'model.json': original.encoded(self.model), + 'workstation.bundle.js': b'prior renderer', + 'workstation_worker.bundle.js': b'prior worker', + 'native-assets.bin.gz': b'unchanged native bundle', + 'mujoco.wasm.gz': gzip.compress(self.native_files['mujoco.wasm'], mtime=0)}) + for name, raw in self.native_files.items(): + (self.workstation/name).write_bytes(raw) + with patch('dvidia_training.workstation.inspect_export', side_effect=self.inspect_native): + original.stage(self.plan, self.workstation, self.root/'prior', 'c'*40, 'd'*40, + evidence=self.evidence) + self.base = self.root/'prior/publication-plan.json' + self.prior = self.root/'prior/space' + self.provenance = self.prior/'provenance.json' + value = json.loads(self.provenance.read_bytes()) + value['live_workstation']['delivery'] = {'retained': True} + value['live_workstation']['download_fix'] = {'source_commit': 'c'*40, 'retained': True} + self.provenance.write_bytes(original.encoded(value)) + self.refresh_prior_plan() + self.new = self.root/'mirror-export' + self.new.mkdir() + self.updated = {**self.native_files, 'workstation.bundle.js': b'verified mirror renderer', + 'workstation_worker.bundle.js': b'verified mirror worker', + 'workstation-integrity.json': b'{"mirror":true}', + 'README.md': b'Verified DVIDIA mirror delivery'} + self.new_model = {**self.model, 'geometry_binary': {**self.model['geometry_binary'], + 'compressed_sha256': original.record(self.native_files['geometry.bin.gz'])['sha256']}} + self.updated['model.json'] = original.encoded(self.new_model) + for name, raw in self.updated.items(): + (self.new/name).write_bytes(raw) + + def refresh_prior_plan(self): + plan = json.loads(self.base.read_bytes()) + plan['repository']['files'] = [ + {'path': path.relative_to(self.prior).as_posix(), **original.record(path.read_bytes())} + for path in sorted(self.prior.rglob('*')) if path.is_file()] + plan['total_bytes'] = sum(entry['bytes'] for entry in plan['repository']['files']) + self.base.write_bytes(original.encoded(plan)) + + def stage(self, **overrides): + args = {'base_plan': self.base, 'workstation': self.new, 'evidence': self.evidence, + 'output': self.root/'mirror', 'source_commit': '1'*40, 'expected_remote_commit': '2'*40} + args.update(overrides) + with patch('dvidia_training.workstation.inspect_export', return_value={}): + return prepare.stage(**args) + + def test_preserves_all_prior_binaries_evidence_and_provenance(self): + result = self.stage() + after = self.root/'mirror/space' + allowed = {'README.md', 'provenance.json'} | {original.NAMESPACE+'/'+name for name in prepare.MUTABLE} + for path in self.prior.rglob('*'): + if path.is_file() and path.relative_to(self.prior).as_posix() not in allowed: + self.assertEqual(path.read_bytes(), (after/path.relative_to(self.prior)).read_bytes()) + before = json.loads(self.provenance.read_bytes())['live_workstation'] + live = json.loads((after/'provenance.json').read_bytes())['live_workstation'] + for key in ('evidence', 'delivery', 'download_fix'): + self.assertEqual(live[key], before[key]) + self.assertEqual(live['mirror']['prior_source_commit'], 'c'*40) + self.assertEqual(live['mirror']['prior_publication_commit'], '2'*40) + self.assertEqual(live['source_commit'], '1'*40) + self.assertEqual(live['files'], {name: original.record(raw) for name, raw in self.updated.items()}) + seal_raw = (after/prepare.EVIDENCE_NAMESPACE/original.EVIDENCE_SEAL).read_bytes() + self.assertEqual(live['mirror']['integrity'], original.record(seal_raw)) + seal = json.loads(seal_raw) + self.assertEqual(seal['added_files'], []) + self.assertTrue(seal['compressed_resources_unchanged']) + self.assertEqual(seal['files'], {name: original.record(raw) for name, raw in self.evidence_files.items()}) + for name, raw in self.evidence_files.items(): + self.assertEqual((after/prepare.EVIDENCE_NAMESPACE/name).read_bytes(), raw) + plan = publisher.checked_plan(self.root/'mirror/publication-plan.json') + self.assertEqual(plan['source_commit'], '1'*40) + self.assertEqual(plan['expected_remote_commit'], '2'*40) + self.assertEqual(plan['remove_files'], []) + self.assertEqual(result['added_workstation_files'], []) + self.assertIn(b'SHA-256 verification', (after/'README.md').read_bytes()) + + def test_protects_every_binary_scene_manifest_branding_and_notice(self): + for name in ('scene.xml', 'mujoco.wasm', 'mujoco.wasm.gz', 'geometry.bin.gz', + 'native-assets.bin.gz', 'workstation.json', 'index.html', 'LICENSE'): + (self.new/name).write_bytes(b'changed') + with self.subTest(name=name), self.assertRaisesRegex(ValueError, 'changed physics'): + self.stage() + (self.new/name).write_bytes(self.updated[name]) + self.assertFalse((self.root/'mirror').exists()) + + def test_rejects_any_removed_or_added_runtime_file(self): + (self.new/'mujoco.wasm').unlink() + with self.assertRaisesRegex(ValueError, 'exact prior runtime inventory'): + self.stage() + (self.new/'mujoco.wasm').write_bytes(self.updated['mujoco.wasm']) + (self.new/'extra.json').write_bytes(b'{}') + with self.assertRaisesRegex(ValueError, 'exact prior runtime inventory'): + self.stage() + + def test_model_change_is_only_exact_compressed_digest(self): + invalid = [] + for field, value in (('sha256', '0'*64), ('bytes', 9), ('extra', True), ('compressed_sha256', 'f'*64)): + model = json.loads(original.encoded(self.new_model)) + model['geometry_binary'][field] = value + invalid.append(model) + model = json.loads(original.encoded(self.new_model)) + del model['geometry_binary']['compressed_sha256'] + invalid.append(model) + model = json.loads(original.encoded(self.new_model)) + model['bodies'] = ['changed'] + invalid.append(model) + invalid.extend(([], {'geometry_binary': []}, {})) + for model in invalid: + (self.new/'model.json').write_bytes(original.encoded(model)) + with self.subTest(model=model), self.assertRaises(ValueError): + self.stage() + self.assertFalse((self.root/'mirror').exists()) + + def test_accepts_preexisting_matching_digest_but_rejects_bad_prior_digest(self): + old_model = self.prior/original.NAMESPACE/'model.json' + for checksum in ('0'*64, self.new_model['geometry_binary']['compressed_sha256']): + model = {**self.model, 'geometry_binary': {**self.model['geometry_binary'], 'compressed_sha256': checksum}} + old_model.write_bytes(original.encoded(model)) + value = json.loads(self.provenance.read_bytes()) + value['live_workstation']['files']['model.json'] = original.record(old_model.read_bytes()) + self.provenance.write_bytes(original.encoded(value)) + self.refresh_prior_plan() + if checksum == '0'*64: + with self.assertRaisesRegex(ValueError, 'Prior compressed geometry checksum'): + self.stage() + else: + self.stage() + + def test_refuses_replacing_old_mirror_provenance_or_evidence(self): + prior = self.provenance.read_bytes() + for mode in ('inventory', 'mirror'): + value = json.loads(prior) + if mode == 'inventory': + value['live_workstation']['files']['mujoco.wasm']['sha256'] = '0'*64 + else: + value['live_workstation']['mirror'] = {'must_remain': True} + self.provenance.write_bytes(original.encoded(value)) + self.refresh_prior_plan() + with self.subTest(mode=mode), self.assertRaisesRegex(ValueError, 'provenance'): + self.stage() + self.provenance.write_bytes(prior) + path = self.prior/prepare.EVIDENCE_NAMESPACE/'README.md' + path.parent.mkdir(parents=True) + path.write_bytes(b'Prior mirror evidence') + self.refresh_prior_plan() + with self.assertRaisesRegex(ValueError, 'fresh mirror evidence'): + self.stage() + + def test_commit_and_input_bounds(self): + for field in ('source_commit', 'expected_remote_commit'): + for value in ('main', 'a'*39, 'A'*40, None): + with self.subTest(field=field, value=value), self.assertRaisesRegex(ValueError, 'Exact source'): + self.stage(**{field: value}) + for folder in (self.new, self.new/'proof', self.root): + with self.subTest(folder=folder), self.assertRaisesRegex(ValueError, 'separate'): + self.stage(evidence=folder) + for folder in (self.new/'output', self.evidence/'output', self.base.parent/'output'): + with self.subTest(folder=folder), self.assertRaisesRegex(ValueError, 'outside input'): + self.stage(output=folder) + (self.root/'mirror').mkdir() + (self.root/'mirror/keep.md').write_bytes(b'keep') + with self.assertRaisesRegex(ValueError, 'fresh'): + self.stage() + self.assertEqual((self.root/'mirror/keep.md').read_bytes(), b'keep') + + def test_prior_tampering_and_failed_final_inspection_leave_no_output(self): + old = self.prior/'tasks/prior/report.json' + raw = old.read_bytes() + old.write_bytes(b'changed') + with self.assertRaises(publisher.PublicationError): + self.stage() + old.write_bytes(raw) + with patch('dvidia_training.workstation.inspect_export', side_effect=[{}, {}, ValueError('final mismatch')]): + with self.assertRaisesRegex(ValueError, 'final mismatch'): + prepare.stage(self.base, self.new, self.evidence, self.root/'mirror', '1'*40, '2'*40) + self.assertFalse((self.root/'mirror').exists()) + self.assertFalse(list(self.root.glob('.workstation-mirror-*'))) + + +if __name__ == '__main__': + unittest.main() diff --git a/publishing/huggingface/test_prepare_workstation_patch.py b/publishing/huggingface/test_prepare_workstation_patch.py new file mode 100644 index 0000000..961000f --- /dev/null +++ b/publishing/huggingface/test_prepare_workstation_patch.py @@ -0,0 +1,214 @@ +"""Download fixes retain physics, prior evidence and bounded publication inputs.""" +import gzip +import json +import unittest +from unittest.mock import patch + +import prepare_workstation as original +import prepare_workstation_delivery as delivery +import prepare_workstation_patch as prepare +import publish_robot_sim as publisher +import test_prepare_workstation as fixtures + + +class DownloadFixTests(unittest.TestCase): + refresh_base = fixtures.WorkstationPublicationTests.refresh_base + inspect_native = fixtures.WorkstationPublicationTests.inspect_native + + def setUp(self): + fixtures.WorkstationPublicationTests.setUp(self) + for name in ('workstation.bundle.js', 'workstation_worker.bundle.js'): + self.native_files[name] = b'original runtime' + (self.workstation/name).write_bytes(self.native_files[name]) + with patch('dvidia_training.workstation.inspect_export', side_effect=self.inspect_native): + original.stage(self.plan, self.workstation, self.root/'first', 'c'*40, 'd'*40, + evidence=self.evidence) + self.prior = self.root/'prior-export' + self.prior.mkdir() + self.prior_files = {**self.native_files, + 'workstation.json': original.encoded({'native_asset_bundle': {'path': 'native-assets.bin.gz'}}), + 'native-assets.bin.gz': b'prior transport fixture'} + for name, raw in self.prior_files.items(): + (self.prior/name).write_bytes(raw) + with patch('dvidia_training.workstation.inspect_export', return_value={}): + delivery.stage(self.root/'first/publication-plan.json', self.prior, self.evidence, + self.root/'delivery', 'e'*40, 'f'*40) + self.base = self.root/'delivery/publication-plan.json' + self.new = self.root/'new-export' + self.new.mkdir() + self.updated = {**self.prior_files, + 'index.html': b'Official DVIDIA workstation with bounded download recovery', + 'workstation_worker.bundle.js': b'new loader', + 'workstation.bundle.js': b'new download status', + 'workstation-integrity.json': b'{"new":true}', + 'mujoco.wasm.gz': gzip.compress(self.native_files['mujoco.wasm'], mtime=0)} + for name, raw in self.updated.items(): + (self.new/name).write_bytes(raw) + self.refresh_metadata() + + def refresh_metadata(self, compressed=None, native=None): + native = self.prior_files['mujoco.wasm'] if native is None else native + compressed = self.updated['mujoco.wasm.gz'] if compressed is None else compressed + metadata = json.loads(self.prior_files['workstation.json']) + metadata.update(native_wasm={'path': 'mujoco.wasm', **original.record(native)}, + wasm_bundle={'path': 'mujoco.wasm.gz', 'compression': 'gzip', + **original.record(compressed), 'uncompressed_bytes': len(native)}) + (self.new/'workstation.json').write_bytes(original.encoded(metadata)) + + def stage(self, **overrides): + args = {'base_plan': self.base, 'workstation': self.new, 'evidence': self.evidence, + 'output': self.root/'fixed', 'source_commit': '1'*40, 'expected_remote_commit': '2'*40} + args.update(overrides) + with patch('dvidia_training.workstation.inspect_export', return_value={}): + return prepare.stage(**args) + + def test_preserves_every_old_receipt_and_native_byte_and_appends_provenance(self): + result = self.stage() + before, after = self.root/'delivery/space', self.root/'fixed/space' + allowed = {'README.md', 'provenance.json'} | {original.NAMESPACE+'/'+name for name in prepare.MUTABLE} + for path in before.rglob('*'): + if path.is_file() and path.relative_to(before).as_posix() not in allowed: + self.assertEqual(path.read_bytes(), (after/path.relative_to(before)).read_bytes()) + old_live = json.loads((before/'provenance.json').read_bytes())['live_workstation'] + new_live = json.loads((after/'provenance.json').read_bytes())['live_workstation'] + for key in ('evidence', 'delivery', 'original_source_commit'): + self.assertEqual(new_live[key], old_live[key]) + self.assertEqual(new_live['source_commit'], '1'*40) + self.assertEqual(new_live['download_fix']['prior_source_commit'], 'e'*40) + self.assertEqual(new_live['download_fix']['prior_publication_commit'], '2'*40) + seal_raw = (after/prepare.EVIDENCE_NAMESPACE/original.EVIDENCE_SEAL).read_bytes() + self.assertEqual(new_live['download_fix']['integrity'], original.record(seal_raw)) + seal = json.loads(seal_raw) + self.assertEqual(seal['files'], {name: original.record(raw) for name, raw in self.evidence_files.items()}) + self.assertEqual(seal['added_files'], ['mujoco.wasm.gz']) + for name, raw in self.evidence_files.items(): + self.assertEqual((after/prepare.EVIDENCE_NAMESPACE/name).read_bytes(), raw) + plan = publisher.checked_plan(self.root/'fixed/publication-plan.json') + self.assertEqual(plan['expected_remote_commit'], '2'*40) + self.assertEqual(plan['source_commit'], '1'*40) + self.assertEqual(plan['remove_files'], []) + self.assertEqual(result['added_workstation_files'], ['mujoco.wasm.gz']) + + def test_refuses_physics_engine_notice_or_native_bundle_changes(self): + for name in ('scene.xml', 'mujoco.wasm', 'geometry.bin.gz', 'native-assets.bin.gz', 'LICENSE'): + (self.new/name).write_bytes(b'changed') + with self.subTest(name=name), self.assertRaisesRegex(ValueError, 'changed physics'): + self.stage() + (self.new/name).write_bytes(self.updated[name]) + self.assertFalse((self.root/'fixed').exists()) + + def test_refuses_missing_or_unexpected_inventory(self): + for name in ('mujoco.wasm', 'mujoco.wasm.gz'): + raw = (self.new/name).read_bytes() + (self.new/name).unlink() + with self.subTest(name=name), self.assertRaisesRegex(ValueError, 'retain the prior inventory'): + self.stage() + (self.new/name).write_bytes(raw) + (self.new/'extra.json').write_bytes(b'{}') + with self.assertRaisesRegex(ValueError, 'add only mujoco.wasm.gz'): + self.stage() + + def test_only_exact_new_descriptors_are_allowed(self): + valid = json.loads((self.new/'workstation.json').read_bytes()) + invalid = [] + for key in ('native_wasm', 'wasm_bundle'): + data = json.loads(original.encoded(valid)) + del data[key] + invalid.append(data) + data = json.loads(original.encoded(valid)) + data['native_asset_bundle'] = {'path': 'different'} + invalid.append(data) + for key in ('native_wasm', 'wasm_bundle'): + for field, value in (('path', 'other.wasm'), ('sha256', '0'*64), ('bytes', 1), ('extra', True)): + data = json.loads(original.encoded(valid)) + data[key][field] = value + invalid.append(data) + for data in invalid: + (self.new/'workstation.json').write_bytes(original.encoded(data)) + with self.subTest(data=data), self.assertRaises(ValueError): + self.stage() + + def test_gzip_must_decode_exact_engine_without_trailing_or_extra_members(self): + valid = self.updated['mujoco.wasm.gz'] + invalid = (b'not gzip', valid[:-2], valid+b'trailing', valid+valid, + gzip.compress(b'x'*1024*1024, mtime=0), gzip.compress(b'different', mtime=0)) + for compressed in invalid: + (self.new/'mujoco.wasm.gz').write_bytes(compressed) + self.refresh_metadata(compressed=compressed) + with self.subTest(size=len(compressed)), self.assertRaisesRegex(ValueError, 'WASM bundle'): + self.stage() + self.assertFalse((self.root/'fixed').exists()) + + def test_requires_exact_commit_names_fresh_output_and_separate_inputs(self): + for field in ('source_commit', 'expected_remote_commit'): + for value in ('main', 'a'*39, 'A'*40, None): + with self.subTest(field=field, value=value), self.assertRaisesRegex(ValueError, 'Exact source'): + self.stage(**{field: value}) + for folder in (self.new, self.new/'evidence', self.root): + with self.subTest(folder=folder), self.assertRaisesRegex(ValueError, 'separate'): + self.stage(evidence=folder) + for folder in (self.new/'output', self.evidence/'output', self.base.parent/'output'): + with self.subTest(folder=folder), self.assertRaisesRegex(ValueError, 'outside input'): + self.stage(output=folder) + (self.root/'fixed').mkdir() + (self.root/'fixed/keep.md').write_bytes(b'keep') + with self.assertRaisesRegex(ValueError, 'fresh'): + self.stage() + self.assertEqual((self.root/'fixed/keep.md').read_bytes(), b'keep') + + def test_rejects_changed_prior_artifacts(self): + old = self.root/'delivery/space/tasks/prior/report.json' + old.write_bytes(b'changed') + with self.assertRaises(publisher.PublicationError): + self.stage() + self.assertFalse((self.root/'fixed').exists()) + + def test_refuses_replacing_prior_provenance_or_download_evidence(self): + path = self.root/'delivery/space/provenance.json' + prior = json.loads(path.read_bytes()) + plan = json.loads(self.base.read_bytes()) + for mutation in ('inventory', 'download_fix'): + value = json.loads(original.encoded(prior)) + live = value['live_workstation'] + if mutation == 'inventory': + live['files']['mujoco.wasm']['sha256'] = '0'*64 + else: + live['download_fix'] = {'prior': 'must remain intact'} + raw = original.encoded(value) + path.write_bytes(raw) + for entry in plan['repository']['files']: + if entry['path'] == 'provenance.json': + entry.update(original.record(raw)) + plan['total_bytes'] = sum(entry['bytes'] for entry in plan['repository']['files']) + self.base.write_bytes(original.encoded(plan)) + with self.subTest(mutation=mutation), self.assertRaisesRegex(ValueError, 'provenance'): + self.stage() + self.assertFalse((self.root/'fixed').exists()) + + def test_rejects_prior_mutation_during_inspection(self): + def mutate(_): + (self.root/'delivery/space/tasks/prior/report.json').write_bytes(b'changed') + with patch('dvidia_training.workstation.inspect_export', side_effect=mutate): + with self.assertRaisesRegex(ValueError, 'Prior artifact changed'): + prepare.stage(self.base, self.new, self.evidence, self.root/'fixed', '1'*40, '2'*40) + + def test_budgets_and_final_inspection_failure_leave_no_output(self): + for constant, value in (('MAX_FILES', 1), ('MAX_TOTAL_BYTES', 1)): + with patch.object(publisher, constant, value), self.assertRaises((ValueError, publisher.PublicationError)): + self.stage() + with patch('dvidia_training.workstation.inspect_export', side_effect=[{}, {}, ValueError('final mismatch')]): + with self.assertRaisesRegex(ValueError, 'final mismatch'): + prepare.stage(self.base, self.new, self.evidence, self.root/'fixed', '1'*40, '2'*40) + self.assertFalse((self.root/'fixed').exists()) + self.assertFalse(list(self.root.glob('.workstation-download-fix-*'))) + + def test_native_wasm_bundle_allowlist_is_scoped(self): + publisher._artifact_name('workstation/v01/mujoco.wasm.gz') + for name in ('other/mujoco.wasm.gz', 'workstation/v02/mujoco.wasm.gz', + 'workstation/v01/other.wasm.gz', 'workstation/v01/assets/mujoco.wasm.gz'): + with self.subTest(name=name), self.assertRaises(publisher.PublicationError): + publisher._artifact_name(name) + + +if __name__ == '__main__': + unittest.main() diff --git a/publishing/huggingface/test_publish_robot_sim.py b/publishing/huggingface/test_publish_robot_sim.py index d853820..7acf2f7 100644 --- a/publishing/huggingface/test_publish_robot_sim.py +++ b/publishing/huggingface/test_publish_robot_sim.py @@ -57,6 +57,15 @@ def api(self,existing=()): def test_accepts_complete_named_static_space_and_native_binaries(self): self.assertEqual(publisher.checked_plan(self.path),self.plan) + def test_live_workstation_native_files_are_scoped(self): + for name in ['workstation/v01/mujoco.wasm', 'workstation/v01/scene.xml', + 'workstation/v01/assets/link1.stl', 'workstation/v01/assets/link2.obj']: + self.assertEqual(publisher._artifact_name(name).as_posix(), name) + for name in ['mujoco.wasm', 'workstation/v02/mujoco.wasm', 'workstation/v01/plugin.wasm', + 'workstation/v01/assets/../../secret.xml', 'workstation/v01/assets/model.xml']: + with self.subTest(name=name), self.assertRaises(PublicationError): + publisher._artifact_name(name) + def test_rejects_unrelated_destination_private_sdk_and_path_escape(self): for field,value in [('repo_id','Dvidia/observation-lab'),('repo_type','model'), ('space_sdk','docker'),('directory','../outside')]: @@ -108,7 +117,7 @@ def test_frontmatter_cannot_be_spoofed_by_body_or_duplicate_keys(self): with self.subTest(card=card),self.assertRaises(PublicationError): publisher.checked_plan(self.path) def test_byte_bounds_are_checked_without_credential_access(self): - self.assertEqual(publisher.MAX_TOTAL_BYTES,512*1024*1024) + self.assertEqual(publisher.MAX_TOTAL_BYTES,768*1024*1024) self.assertEqual(publisher.MAX_FILE_BYTES,32*1024*1024) with patch.object(publisher,'MAX_TOTAL_BYTES',self.plan['total_bytes']): self.assertEqual(publisher.checked_plan(self.path),self.plan) diff --git a/pyproject.toml b/pyproject.toml index fcb360b..3628b2a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -8,7 +8,7 @@ version = "0.1.0" description = "Local CPU training from Skillspace footage, with optional simulation movement candidates" readme = "README.md" license = "MIT AND Apache-2.0" -license-files = ["LICENSE", "third_party/observation-models/*LICENSE.txt"] +license-files = ["LICENSE", "third_party/observation-models/*LICENSE.txt", "third_party/mujoco/*.txt"] requires-python = ">=3.12" dependencies = ["numpy==2.5.3"] classifiers = [ @@ -49,9 +49,11 @@ dvidia-piper-contact = "dvidia_training.piper_contact_benchmark:main" dvidia-piper-recovery = "dvidia_training.piper_recovery_benchmark:main" dvidia-piper-reliability = "dvidia_training.piper_reliability_benchmark:main" dvidia-assets = "dvidia_training.asset_cli:main" +dvidia-workstation = "dvidia_training.workstation:main" +dvidia-workstation-benchmark = "dvidia_training.workstation_benchmark:main" [tool.setuptools.packages.find] where = ["src"] [tool.setuptools.package-data] -dvidia_training = ["*.html", "*.json", "*.js", "*.txt", "LICENSE", "requirements.lock.txt"] +dvidia_training = ["*.html", "*.json", "*.js", "*.txt", "*.wasm", "LICENSE", "requirements.lock.txt"] diff --git a/scripts/workstation-parity-fixture.py b/scripts/workstation-parity-fixture.py new file mode 100644 index 0000000..3a4d030 --- /dev/null +++ b/scripts/workstation-parity-fixture.py @@ -0,0 +1,110 @@ +"""Generate an auditable 30-second native trace for the browser controller parity test.""" +from __future__ import annotations + +import argparse +from hashlib import sha256 +import json +from pathlib import Path +import platform +import time + +import mujoco +import numpy as np + +from dvidia_training import workstation + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--scene', type=Path, required=True) + parser.add_argument('--output', type=Path, required=True) + args = parser.parse_args() + manifest = json.loads((args.scene / 'workstation.json').read_text()) + model = mujoco.MjModel.from_xml_path(str(args.scene / 'scene.xml')) + data = mujoco.MjData(model) + data.qpos[:] = manifest['home_qpos'] + data.ctrl[:] = manifest['home_ctrl'] + mujoco.mj_forward(model, data) + dt = manifest['timestep'] + stride = round(manifest['control_dt'] / dt) + total_steps = round(30 / dt) + commands = [ + {'step': 0, 'type': 'target', 'position': [.38, 0., .25]}, + {'step': 1500, 'type': 'target', 'position': [.32, -.12, .20]}, + {'step': 3003, 'type': 'gripper', 'jaw': .015}, + {'step': 4500, 'type': 'gripper', 'jaw': .035}, + {'step': 5000, 'type': 'target', 'position': [.40, .10, .28]}, + {'step': 7000, 'type': 'target', 'position': [.30, .04, .23]}, + {'step': 9000, 'type': 'target', 'position': manifest['initial_target_xyz']}, + {'step': 10000, 'type': 'gripper', 'jaw': 0.}, + {'step': 11000, 'type': 'push', 'body': manifest['shoe_body_names'][0], + 'impulse': [0., .12, 0.]}, + {'step': 12000, 'type': 'gripper', 'jaw': .035}, + {'step': 13000, 'type': 'target', 'position': [.35, -.03, .24]}, + ] + schedule = {} + for command in commands: + schedule.setdefault(command['step'], []).append(command) + target = manifest['initial_target_xyz'] + jaw = manifest['home_ctrl'][6] + shoe = mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_BODY, manifest['shoe_body_names'][0]) + tcp = mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_SITE, manifest['tcp_site_name']) + trace, step_ms, control_ms = [], [], [] + started = time.perf_counter() + error = None + completed = 0 + for index in range(total_steps): + force = None + for command in schedule.get(index, []): + if command['type'] == 'target': target = command['position'] + elif command['type'] == 'gripper': jaw = command['jaw'] + else: force = np.asarray(command['impulse']) / dt + tick = time.perf_counter() + if index % stride == 0: + control_started = time.perf_counter() + desired = workstation.controller_action(model, data, target, jaw) + control_ms.append((time.perf_counter() - control_started) * 1000) + data.ctrl[:6] += np.clip(desired[:6] - data.ctrl[:6], -manifest['controller']['joint_rate_rad_s'] * dt, + manifest['controller']['joint_rate_rad_s'] * dt) + data.ctrl[6] += float(np.clip(desired[6] - data.ctrl[6], -manifest['controller']['gripper_rate_m_s'] * dt, + manifest['controller']['gripper_rate_m_s'] * dt)) + data.xfrc_applied[:] = 0 + if force is not None: data.xfrc_applied[shoe, :3] = force + mujoco.mj_step(model, data) + data.xfrc_applied[:] = 0 + mujoco.mj_forward(model, data) + completed += 1 + step_ms.append((time.perf_counter() - tick) * 1000) + if not all(np.isfinite(value).all() for value in (data.qpos, data.qvel, data.qacc)): + error = 'nonfinite_native_state'; break + if any(warning.number for warning in data.warning): + error = 'native_solver_warning'; break + if (index + 1) % stride == 0: + forces = [] + for contact in range(data.ncon): + force_vector = np.empty(6) + mujoco.mj_contactForce(model, data, contact, force_vector) + forces.append(max(0., float(force_vector[0]))) + trace.append({'completed_steps': index + 1, 'qpos': data.qpos.tolist(), 'qvel': data.qvel.tolist(), + 'ctrl': data.ctrl.tolist(), 'tcp_position': data.site_xpos[tcp].tolist(), + 'shoe_position': data.xpos[shoe].tolist(), 'contacts': int(data.ncon), + 'contact_normal_forces_n': forces, 'active_contacts': sum(force > .001 for force in forces), + 'tracking_error_m': float(np.linalg.norm(data.site_xpos[tcp] - target))}) + wall_seconds = time.perf_counter() - started + result = {'schema': 'dvidia.workstation-native-parity/v1', 'engine': mujoco.__version__, + 'platform': platform.platform(), 'native_scene_sha256': sha256((args.scene / 'scene.xml').read_bytes()).hexdigest(), + 'manifest_sha256': sha256((args.scene / 'workstation.json').read_bytes()).hexdigest(), + 'physics_steps': total_steps, 'completed_steps': completed, 'timestep': dt, 'control_stride': stride, + 'commands': commands, 'trace': trace, 'valid': error is None, 'error': error, + 'warnings': [int(warning.number) for warning in data.warning], + 'wall_seconds': wall_seconds, 'real_time_factor': completed * dt / wall_seconds, + 'step_ms_p50': float(np.percentile(step_ms, 50)), 'step_ms_p95': float(np.percentile(step_ms, 95)), + 'control_ms_p95': float(np.percentile(control_ms, 95))} + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(result, indent=2, allow_nan=False) + '\n') + print(json.dumps({key: value for key, value in result.items() if key not in ('commands', 'trace')}, indent=2)) + if error: raise SystemExit(1) + + +if __name__ == '__main__': + main() diff --git a/src/dvidia_training/mujoco.wasm b/src/dvidia_training/mujoco.wasm new file mode 100755 index 0000000..badbf65 Binary files /dev/null and b/src/dvidia_training/mujoco.wasm differ diff --git a/src/dvidia_training/workstation.bundle.js b/src/dvidia_training/workstation.bundle.js new file mode 100644 index 0000000..892878e --- /dev/null +++ b/src/dvidia_training/workstation.bundle.js @@ -0,0 +1,3834 @@ +/* DVIDIA live workstation. MIT. Three.js r180 MIT. See workstation.third-party.txt. */ +var gi={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},_i={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},Rh=0,Ol=1,Ch=2;var Bl=1,Vo=2,Dn=3,qn=0,Ve=1,Ge=2,Kn=0,Pi=1,zl=2,kl=3,Hl=4,Ph=5,ci=100,Ih=101,Dh=102,Lh=103,Uh=104,Nh=200,Fh=201,Oh=202,Bh=203,fo=204,po=205,zh=206,kh=207,Hh=208,Vh=209,Gh=210,Wh=211,Xh=212,qh=213,Yh=214,Go=0,Wo=1,Xo=2,Ii=3,qo=4,Yo=5,Zo=6,Jo=7,Vl=0,Zh=1,Jh=2,jn=0,$h=1,Kh=2,jh=3,$o=4,Qh=5,tu=6,eu=7;var Gl=300,Fi=301,Oi=302,Ko=303,jo=304,wr=306,hs=1e3,li=1001,mo=1002,un=1003,nu=1004;var Er=1005;var Mn=1006,Qo=1007;var xi=1008;var En=1009,Wl=1010,Xl=1011,ws=1012,ta=1013,yi=1014,Ln=1015,Es=1016,ea=1017,na=1018,Ts=1020,ql=35902,Yl=35899,Zl=1021,Jl=1022,dn=1023,us=1026,As=1027,$l=1028,ia=1029,Kl=1030,sa=1031;var ra=1033,Tr=33776,Ar=33777,Rr=33778,Cr=33779,oa=35840,aa=35841,la=35842,ca=35843,ha=36196,ua=37492,da=37496,fa=37808,pa=37809,ma=37810,ga=37811,_a=37812,xa=37813,ya=37814,va=37815,Ma=37816,Sa=37817,ba=37818,wa=37819,Ea=37820,Ta=37821,Aa=36492,Ra=36494,Ca=36495,Pa=36283,Ia=36284,Da=36285,La=36286;var qs=2300,go=2301,uo=2302,El=2400,Tl=2401,Al=2402;var iu=3200,su=3201;var jl=0,ru=1,Qn="",De="srgb",Yn="srgb-linear",Ys="linear",ne="srgb";var Ri=7680;var Rl=519,ou=512,au=513,lu=514,Ql=515,cu=516,hu=517,uu=518,du=519,Cl=35044;var tc="300 es",yn=2e3,Zs=2001;var Rn=class{addEventListener(t,e){this._listeners===void 0&&(this._listeners={});let n=this._listeners;n[t]===void 0&&(n[t]=[]),n[t].indexOf(e)===-1&&n[t].push(e)}hasEventListener(t,e){let n=this._listeners;return n===void 0?!1:n[t]!==void 0&&n[t].indexOf(e)!==-1}removeEventListener(t,e){let n=this._listeners;if(n===void 0)return;let s=n[t];if(s!==void 0){let r=s.indexOf(e);r!==-1&&s.splice(r,1)}}dispatchEvent(t){let e=this._listeners;if(e===void 0)return;let n=e[t.type];if(n!==void 0){t.target=this;let s=n.slice(0);for(let r=0,o=s.length;r>8&255]+Le[i>>16&255]+Le[i>>24&255]+"-"+Le[t&255]+Le[t>>8&255]+"-"+Le[t>>16&15|64]+Le[t>>24&255]+"-"+Le[e&63|128]+Le[e>>8&255]+"-"+Le[e>>16&255]+Le[e>>24&255]+Le[n&255]+Le[n>>8&255]+Le[n>>16&255]+Le[n>>24&255]).toLowerCase()}function Zt(i,t,e){return Math.max(t,Math.min(e,i))}function ec(i,t){return(i%t+t)%t}function Od(i,t,e,n,s){return n+(i-t)*(s-n)/(e-t)}function Bd(i,t,e){return i!==t?(e-i)/(t-i):0}function Gs(i,t,e){return(1-e)*i+e*t}function zd(i,t,e,n){return Gs(i,t,1-Math.exp(-e*n))}function kd(i,t=1){return t-Math.abs(ec(i,t*2)-t)}function Hd(i,t,e){return i<=t?0:i>=e?1:(i=(i-t)/(e-t),i*i*(3-2*i))}function Vd(i,t,e){return i<=t?0:i>=e?1:(i=(i-t)/(e-t),i*i*i*(i*(i*6-15)+10))}function Gd(i,t){return i+Math.floor(Math.random()*(t-i+1))}function Wd(i,t){return i+Math.random()*(t-i)}function Xd(i){return i*(.5-Math.random())}function qd(i){i!==void 0&&(jc=i);let t=jc+=1831565813;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}function Yd(i){return i*Vs}function Zd(i){return i*ds}function Jd(i){return(i&i-1)===0&&i!==0}function $d(i){return Math.pow(2,Math.ceil(Math.log(i)/Math.LN2))}function Kd(i){return Math.pow(2,Math.floor(Math.log(i)/Math.LN2))}function jd(i,t,e,n,s){let r=Math.cos,o=Math.sin,a=r(e/2),l=o(e/2),c=r((t+n)/2),h=o((t+n)/2),u=r((t-n)/2),d=o((t-n)/2),p=r((n-t)/2),g=o((n-t)/2);switch(s){case"XYX":i.set(a*h,l*u,l*d,a*c);break;case"YZY":i.set(l*d,a*h,l*u,a*c);break;case"ZXZ":i.set(l*u,l*d,a*h,a*c);break;case"XZX":i.set(a*h,l*g,l*p,a*c);break;case"YXY":i.set(l*p,a*h,l*g,a*c);break;case"ZYZ":i.set(l*g,l*p,a*h,a*c);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+s)}}function ls(i,t){switch(t.constructor){case Float32Array:return i;case Uint32Array:return i/4294967295;case Uint16Array:return i/65535;case Uint8Array:return i/255;case Int32Array:return Math.max(i/2147483647,-1);case Int16Array:return Math.max(i/32767,-1);case Int8Array:return Math.max(i/127,-1);default:throw new Error("Invalid component type.")}}function He(i,t){switch(t.constructor){case Float32Array:return i;case Uint32Array:return Math.round(i*4294967295);case Uint16Array:return Math.round(i*65535);case Uint8Array:return Math.round(i*255);case Int32Array:return Math.round(i*2147483647);case Int16Array:return Math.round(i*32767);case Int8Array:return Math.round(i*127);default:throw new Error("Invalid component type.")}}var nc={DEG2RAD:Vs,RAD2DEG:ds,generateUUID:Bi,clamp:Zt,euclideanModulo:ec,mapLinear:Od,inverseLerp:Bd,lerp:Gs,damp:zd,pingpong:kd,smoothstep:Hd,smootherstep:Vd,randInt:Gd,randFloat:Wd,randFloatSpread:Xd,seededRandom:qd,degToRad:Yd,radToDeg:Zd,isPowerOfTwo:Jd,ceilPowerOfTwo:$d,floorPowerOfTwo:Kd,setQuaternionFromProperEuler:jd,normalize:He,denormalize:ls},ht=class i{constructor(t=0,e=0){i.prototype.isVector2=!0,this.x=t,this.y=e}get width(){return this.x}set width(t){this.x=t}get height(){return this.y}set height(t){this.y=t}set(t,e){return this.x=t,this.y=e,this}setScalar(t){return this.x=t,this.y=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y)}copy(t){return this.x=t.x,this.y=t.y,this}add(t){return this.x+=t.x,this.y+=t.y,this}addScalar(t){return this.x+=t,this.y+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this}subScalar(t){return this.x-=t,this.y-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this}multiply(t){return this.x*=t.x,this.y*=t.y,this}multiplyScalar(t){return this.x*=t,this.y*=t,this}divide(t){return this.x/=t.x,this.y/=t.y,this}divideScalar(t){return this.multiplyScalar(1/t)}applyMatrix3(t){let e=this.x,n=this.y,s=t.elements;return this.x=s[0]*e+s[3]*n+s[6],this.y=s[1]*e+s[4]*n+s[7],this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this}clamp(t,e){return this.x=Zt(this.x,t.x,e.x),this.y=Zt(this.y,t.y,e.y),this}clampScalar(t,e){return this.x=Zt(this.x,t,e),this.y=Zt(this.y,t,e),this}clampLength(t,e){let n=this.length();return this.divideScalar(n||1).multiplyScalar(Zt(n,t,e))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(t){return this.x*t.x+this.y*t.y}cross(t){return this.x*t.y-this.y*t.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(t){let e=Math.sqrt(this.lengthSq()*t.lengthSq());if(e===0)return Math.PI/2;let n=this.dot(t)/e;return Math.acos(Zt(n,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){let e=this.x-t.x,n=this.y-t.y;return e*e+n*n}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this}lerpVectors(t,e,n){return this.x=t.x+(e.x-t.x)*n,this.y=t.y+(e.y-t.y)*n,this}equals(t){return t.x===this.x&&t.y===this.y}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this}rotateAround(t,e){let n=Math.cos(e),s=Math.sin(e),r=this.x-t.x,o=this.y-t.y;return this.x=r*n-o*s+t.x,this.y=r*s+o*n+t.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}},ye=class{constructor(t=0,e=0,n=0,s=1){this.isQuaternion=!0,this._x=t,this._y=e,this._z=n,this._w=s}static slerpFlat(t,e,n,s,r,o,a){let l=n[s+0],c=n[s+1],h=n[s+2],u=n[s+3],d=r[o+0],p=r[o+1],g=r[o+2],_=r[o+3];if(a===0){t[e+0]=l,t[e+1]=c,t[e+2]=h,t[e+3]=u;return}if(a===1){t[e+0]=d,t[e+1]=p,t[e+2]=g,t[e+3]=_;return}if(u!==_||l!==d||c!==p||h!==g){let m=1-a,f=l*d+c*p+h*g+u*_,w=f>=0?1:-1,M=1-f*f;if(M>Number.EPSILON){let R=Math.sqrt(M),T=Math.atan2(R,f*w);m=Math.sin(m*T)/R,a=Math.sin(a*T)/R}let x=a*w;if(l=l*m+d*x,c=c*m+p*x,h=h*m+g*x,u=u*m+_*x,m===1-a){let R=1/Math.sqrt(l*l+c*c+h*h+u*u);l*=R,c*=R,h*=R,u*=R}}t[e]=l,t[e+1]=c,t[e+2]=h,t[e+3]=u}static multiplyQuaternionsFlat(t,e,n,s,r,o){let a=n[s],l=n[s+1],c=n[s+2],h=n[s+3],u=r[o],d=r[o+1],p=r[o+2],g=r[o+3];return t[e]=a*g+h*u+l*p-c*d,t[e+1]=l*g+h*d+c*u-a*p,t[e+2]=c*g+h*p+a*d-l*u,t[e+3]=h*g-a*u-l*d-c*p,t}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get w(){return this._w}set w(t){this._w=t,this._onChangeCallback()}set(t,e,n,s){return this._x=t,this._y=e,this._z=n,this._w=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(t){return this._x=t.x,this._y=t.y,this._z=t.z,this._w=t.w,this._onChangeCallback(),this}setFromEuler(t,e=!0){let n=t._x,s=t._y,r=t._z,o=t._order,a=Math.cos,l=Math.sin,c=a(n/2),h=a(s/2),u=a(r/2),d=l(n/2),p=l(s/2),g=l(r/2);switch(o){case"XYZ":this._x=d*h*u+c*p*g,this._y=c*p*u-d*h*g,this._z=c*h*g+d*p*u,this._w=c*h*u-d*p*g;break;case"YXZ":this._x=d*h*u+c*p*g,this._y=c*p*u-d*h*g,this._z=c*h*g-d*p*u,this._w=c*h*u+d*p*g;break;case"ZXY":this._x=d*h*u-c*p*g,this._y=c*p*u+d*h*g,this._z=c*h*g+d*p*u,this._w=c*h*u-d*p*g;break;case"ZYX":this._x=d*h*u-c*p*g,this._y=c*p*u+d*h*g,this._z=c*h*g-d*p*u,this._w=c*h*u+d*p*g;break;case"YZX":this._x=d*h*u+c*p*g,this._y=c*p*u+d*h*g,this._z=c*h*g-d*p*u,this._w=c*h*u-d*p*g;break;case"XZY":this._x=d*h*u-c*p*g,this._y=c*p*u-d*h*g,this._z=c*h*g+d*p*u,this._w=c*h*u+d*p*g;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+o)}return e===!0&&this._onChangeCallback(),this}setFromAxisAngle(t,e){let n=e/2,s=Math.sin(n);return this._x=t.x*s,this._y=t.y*s,this._z=t.z*s,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(t){let e=t.elements,n=e[0],s=e[4],r=e[8],o=e[1],a=e[5],l=e[9],c=e[2],h=e[6],u=e[10],d=n+a+u;if(d>0){let p=.5/Math.sqrt(d+1);this._w=.25/p,this._x=(h-l)*p,this._y=(r-c)*p,this._z=(o-s)*p}else if(n>a&&n>u){let p=2*Math.sqrt(1+n-a-u);this._w=(h-l)/p,this._x=.25*p,this._y=(s+o)/p,this._z=(r+c)/p}else if(a>u){let p=2*Math.sqrt(1+a-n-u);this._w=(r-c)/p,this._x=(s+o)/p,this._y=.25*p,this._z=(l+h)/p}else{let p=2*Math.sqrt(1+u-n-a);this._w=(o-s)/p,this._x=(r+c)/p,this._y=(l+h)/p,this._z=.25*p}return this._onChangeCallback(),this}setFromUnitVectors(t,e){let n=t.dot(e)+1;return n<1e-8?(n=0,Math.abs(t.x)>Math.abs(t.z)?(this._x=-t.y,this._y=t.x,this._z=0,this._w=n):(this._x=0,this._y=-t.z,this._z=t.y,this._w=n)):(this._x=t.y*e.z-t.z*e.y,this._y=t.z*e.x-t.x*e.z,this._z=t.x*e.y-t.y*e.x,this._w=n),this.normalize()}angleTo(t){return 2*Math.acos(Math.abs(Zt(this.dot(t),-1,1)))}rotateTowards(t,e){let n=this.angleTo(t);if(n===0)return this;let s=Math.min(1,e/n);return this.slerp(t,s),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(t){return this._x*t._x+this._y*t._y+this._z*t._z+this._w*t._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let t=this.length();return t===0?(this._x=0,this._y=0,this._z=0,this._w=1):(t=1/t,this._x=this._x*t,this._y=this._y*t,this._z=this._z*t,this._w=this._w*t),this._onChangeCallback(),this}multiply(t){return this.multiplyQuaternions(this,t)}premultiply(t){return this.multiplyQuaternions(t,this)}multiplyQuaternions(t,e){let n=t._x,s=t._y,r=t._z,o=t._w,a=e._x,l=e._y,c=e._z,h=e._w;return this._x=n*h+o*a+s*c-r*l,this._y=s*h+o*l+r*a-n*c,this._z=r*h+o*c+n*l-s*a,this._w=o*h-n*a-s*l-r*c,this._onChangeCallback(),this}slerp(t,e){if(e===0)return this;if(e===1)return this.copy(t);let n=this._x,s=this._y,r=this._z,o=this._w,a=o*t._w+n*t._x+s*t._y+r*t._z;if(a<0?(this._w=-t._w,this._x=-t._x,this._y=-t._y,this._z=-t._z,a=-a):this.copy(t),a>=1)return this._w=o,this._x=n,this._y=s,this._z=r,this;let l=1-a*a;if(l<=Number.EPSILON){let p=1-e;return this._w=p*o+e*this._w,this._x=p*n+e*this._x,this._y=p*s+e*this._y,this._z=p*r+e*this._z,this.normalize(),this}let c=Math.sqrt(l),h=Math.atan2(c,a),u=Math.sin((1-e)*h)/c,d=Math.sin(e*h)/c;return this._w=o*u+this._w*d,this._x=n*u+this._x*d,this._y=s*u+this._y*d,this._z=r*u+this._z*d,this._onChangeCallback(),this}slerpQuaternions(t,e,n){return this.copy(t).slerp(e,n)}random(){let t=2*Math.PI*Math.random(),e=2*Math.PI*Math.random(),n=Math.random(),s=Math.sqrt(1-n),r=Math.sqrt(n);return this.set(s*Math.sin(t),s*Math.cos(t),r*Math.sin(e),r*Math.cos(e))}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._w===this._w}fromArray(t,e=0){return this._x=t[e],this._y=t[e+1],this._z=t[e+2],this._w=t[e+3],this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._w,t}fromBufferAttribute(t,e){return this._x=t.getX(e),this._y=t.getY(e),this._z=t.getZ(e),this._w=t.getW(e),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}},A=class i{constructor(t=0,e=0,n=0){i.prototype.isVector3=!0,this.x=t,this.y=e,this.z=n}set(t,e,n){return n===void 0&&(n=this.z),this.x=t,this.y=e,this.z=n,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this}multiplyVectors(t,e){return this.x=t.x*e.x,this.y=t.y*e.y,this.z=t.z*e.z,this}applyEuler(t){return this.applyQuaternion(Qc.setFromEuler(t))}applyAxisAngle(t,e){return this.applyQuaternion(Qc.setFromAxisAngle(t,e))}applyMatrix3(t){let e=this.x,n=this.y,s=this.z,r=t.elements;return this.x=r[0]*e+r[3]*n+r[6]*s,this.y=r[1]*e+r[4]*n+r[7]*s,this.z=r[2]*e+r[5]*n+r[8]*s,this}applyNormalMatrix(t){return this.applyMatrix3(t).normalize()}applyMatrix4(t){let e=this.x,n=this.y,s=this.z,r=t.elements,o=1/(r[3]*e+r[7]*n+r[11]*s+r[15]);return this.x=(r[0]*e+r[4]*n+r[8]*s+r[12])*o,this.y=(r[1]*e+r[5]*n+r[9]*s+r[13])*o,this.z=(r[2]*e+r[6]*n+r[10]*s+r[14])*o,this}applyQuaternion(t){let e=this.x,n=this.y,s=this.z,r=t.x,o=t.y,a=t.z,l=t.w,c=2*(o*s-a*n),h=2*(a*e-r*s),u=2*(r*n-o*e);return this.x=e+l*c+o*u-a*h,this.y=n+l*h+a*c-r*u,this.z=s+l*u+r*h-o*c,this}project(t){return this.applyMatrix4(t.matrixWorldInverse).applyMatrix4(t.projectionMatrix)}unproject(t){return this.applyMatrix4(t.projectionMatrixInverse).applyMatrix4(t.matrixWorld)}transformDirection(t){let e=this.x,n=this.y,s=this.z,r=t.elements;return this.x=r[0]*e+r[4]*n+r[8]*s,this.y=r[1]*e+r[5]*n+r[9]*s,this.z=r[2]*e+r[6]*n+r[10]*s,this.normalize()}divide(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this}divideScalar(t){return this.multiplyScalar(1/t)}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this}clamp(t,e){return this.x=Zt(this.x,t.x,e.x),this.y=Zt(this.y,t.y,e.y),this.z=Zt(this.z,t.z,e.z),this}clampScalar(t,e){return this.x=Zt(this.x,t,e),this.y=Zt(this.y,t,e),this.z=Zt(this.z,t,e),this}clampLength(t,e){let n=this.length();return this.divideScalar(n||1).multiplyScalar(Zt(n,t,e))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this}lerpVectors(t,e,n){return this.x=t.x+(e.x-t.x)*n,this.y=t.y+(e.y-t.y)*n,this.z=t.z+(e.z-t.z)*n,this}cross(t){return this.crossVectors(this,t)}crossVectors(t,e){let n=t.x,s=t.y,r=t.z,o=e.x,a=e.y,l=e.z;return this.x=s*l-r*a,this.y=r*o-n*l,this.z=n*a-s*o,this}projectOnVector(t){let e=t.lengthSq();if(e===0)return this.set(0,0,0);let n=t.dot(this)/e;return this.copy(t).multiplyScalar(n)}projectOnPlane(t){return Qa.copy(this).projectOnVector(t),this.sub(Qa)}reflect(t){return this.sub(Qa.copy(t).multiplyScalar(2*this.dot(t)))}angleTo(t){let e=Math.sqrt(this.lengthSq()*t.lengthSq());if(e===0)return Math.PI/2;let n=this.dot(t)/e;return Math.acos(Zt(n,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){let e=this.x-t.x,n=this.y-t.y,s=this.z-t.z;return e*e+n*n+s*s}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)+Math.abs(this.z-t.z)}setFromSpherical(t){return this.setFromSphericalCoords(t.radius,t.phi,t.theta)}setFromSphericalCoords(t,e,n){let s=Math.sin(e)*t;return this.x=s*Math.sin(n),this.y=Math.cos(e)*t,this.z=s*Math.cos(n),this}setFromCylindrical(t){return this.setFromCylindricalCoords(t.radius,t.theta,t.y)}setFromCylindricalCoords(t,e,n){return this.x=t*Math.sin(e),this.y=n,this.z=t*Math.cos(e),this}setFromMatrixPosition(t){let e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this}setFromMatrixScale(t){let e=this.setFromMatrixColumn(t,0).length(),n=this.setFromMatrixColumn(t,1).length(),s=this.setFromMatrixColumn(t,2).length();return this.x=e,this.y=n,this.z=s,this}setFromMatrixColumn(t,e){return this.fromArray(t.elements,e*4)}setFromMatrix3Column(t,e){return this.fromArray(t.elements,e*3)}setFromEuler(t){return this.x=t._x,this.y=t._y,this.z=t._z,this}setFromColor(t){return this.x=t.r,this.y=t.g,this.z=t.b,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this.z=t.getZ(e),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){let t=Math.random()*Math.PI*2,e=Math.random()*2-1,n=Math.sqrt(1-e*e);return this.x=n*Math.cos(t),this.y=e,this.z=n*Math.sin(t),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}},Qa=new A,Qc=new ye,Wt=class i{constructor(t,e,n,s,r,o,a,l,c){i.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],t!==void 0&&this.set(t,e,n,s,r,o,a,l,c)}set(t,e,n,s,r,o,a,l,c){let h=this.elements;return h[0]=t,h[1]=s,h[2]=a,h[3]=e,h[4]=r,h[5]=l,h[6]=n,h[7]=o,h[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(t){let e=this.elements,n=t.elements;return e[0]=n[0],e[1]=n[1],e[2]=n[2],e[3]=n[3],e[4]=n[4],e[5]=n[5],e[6]=n[6],e[7]=n[7],e[8]=n[8],this}extractBasis(t,e,n){return t.setFromMatrix3Column(this,0),e.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(t){let e=t.elements;return this.set(e[0],e[4],e[8],e[1],e[5],e[9],e[2],e[6],e[10]),this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){let n=t.elements,s=e.elements,r=this.elements,o=n[0],a=n[3],l=n[6],c=n[1],h=n[4],u=n[7],d=n[2],p=n[5],g=n[8],_=s[0],m=s[3],f=s[6],w=s[1],M=s[4],x=s[7],R=s[2],T=s[5],P=s[8];return r[0]=o*_+a*w+l*R,r[3]=o*m+a*M+l*T,r[6]=o*f+a*x+l*P,r[1]=c*_+h*w+u*R,r[4]=c*m+h*M+u*T,r[7]=c*f+h*x+u*P,r[2]=d*_+p*w+g*R,r[5]=d*m+p*M+g*T,r[8]=d*f+p*x+g*P,this}multiplyScalar(t){let e=this.elements;return e[0]*=t,e[3]*=t,e[6]*=t,e[1]*=t,e[4]*=t,e[7]*=t,e[2]*=t,e[5]*=t,e[8]*=t,this}determinant(){let t=this.elements,e=t[0],n=t[1],s=t[2],r=t[3],o=t[4],a=t[5],l=t[6],c=t[7],h=t[8];return e*o*h-e*a*c-n*r*h+n*a*l+s*r*c-s*o*l}invert(){let t=this.elements,e=t[0],n=t[1],s=t[2],r=t[3],o=t[4],a=t[5],l=t[6],c=t[7],h=t[8],u=h*o-a*c,d=a*l-h*r,p=c*r-o*l,g=e*u+n*d+s*p;if(g===0)return this.set(0,0,0,0,0,0,0,0,0);let _=1/g;return t[0]=u*_,t[1]=(s*c-h*n)*_,t[2]=(a*n-s*o)*_,t[3]=d*_,t[4]=(h*e-s*l)*_,t[5]=(s*r-a*e)*_,t[6]=p*_,t[7]=(n*l-c*e)*_,t[8]=(o*e-n*r)*_,this}transpose(){let t,e=this.elements;return t=e[1],e[1]=e[3],e[3]=t,t=e[2],e[2]=e[6],e[6]=t,t=e[5],e[5]=e[7],e[7]=t,this}getNormalMatrix(t){return this.setFromMatrix4(t).invert().transpose()}transposeIntoArray(t){let e=this.elements;return t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8],this}setUvTransform(t,e,n,s,r,o,a){let l=Math.cos(r),c=Math.sin(r);return this.set(n*l,n*c,-n*(l*o+c*a)+o+t,-s*c,s*l,-s*(-c*o+l*a)+a+e,0,0,1),this}scale(t,e){return this.premultiply(tl.makeScale(t,e)),this}rotate(t){return this.premultiply(tl.makeRotation(-t)),this}translate(t,e){return this.premultiply(tl.makeTranslation(t,e)),this}makeTranslation(t,e){return t.isVector2?this.set(1,0,t.x,0,1,t.y,0,0,1):this.set(1,0,t,0,1,e,0,0,1),this}makeRotation(t){let e=Math.cos(t),n=Math.sin(t);return this.set(e,-n,0,n,e,0,0,0,1),this}makeScale(t,e){return this.set(t,0,0,0,e,0,0,0,1),this}equals(t){let e=this.elements,n=t.elements;for(let s=0;s<9;s++)if(e[s]!==n[s])return!1;return!0}fromArray(t,e=0){for(let n=0;n<9;n++)this.elements[n]=t[n+e];return this}toArray(t=[],e=0){let n=this.elements;return t[e]=n[0],t[e+1]=n[1],t[e+2]=n[2],t[e+3]=n[3],t[e+4]=n[4],t[e+5]=n[5],t[e+6]=n[6],t[e+7]=n[7],t[e+8]=n[8],t}clone(){return new this.constructor().fromArray(this.elements)}},tl=new Wt;function ic(i){for(let t=i.length-1;t>=0;--t)if(i[t]>=65535)return!0;return!1}function Js(i){return document.createElementNS("http://www.w3.org/1999/xhtml",i)}function fu(){let i=Js("canvas");return i.style.display="block",i}var th={};function fs(i){i in th||(th[i]=!0,console.warn(i))}function pu(i,t,e){return new Promise(function(n,s){function r(){switch(i.clientWaitSync(t,i.SYNC_FLUSH_COMMANDS_BIT,0)){case i.WAIT_FAILED:s();break;case i.TIMEOUT_EXPIRED:setTimeout(r,e);break;default:n()}}setTimeout(r,e)})}var eh=new Wt().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),nh=new Wt().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function Qd(){let i={enabled:!0,workingColorSpace:Yn,spaces:{},convert:function(s,r,o){return this.enabled===!1||r===o||!r||!o||(this.spaces[r].transfer===ne&&(s.r=Xn(s.r),s.g=Xn(s.g),s.b=Xn(s.b)),this.spaces[r].primaries!==this.spaces[o].primaries&&(s.applyMatrix3(this.spaces[r].toXYZ),s.applyMatrix3(this.spaces[o].fromXYZ)),this.spaces[o].transfer===ne&&(s.r=cs(s.r),s.g=cs(s.g),s.b=cs(s.b))),s},workingToColorSpace:function(s,r){return this.convert(s,this.workingColorSpace,r)},colorSpaceToWorking:function(s,r){return this.convert(s,r,this.workingColorSpace)},getPrimaries:function(s){return this.spaces[s].primaries},getTransfer:function(s){return s===Qn?Ys:this.spaces[s].transfer},getToneMappingMode:function(s){return this.spaces[s].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(s,r=this.workingColorSpace){return s.fromArray(this.spaces[r].luminanceCoefficients)},define:function(s){Object.assign(this.spaces,s)},_getMatrix:function(s,r,o){return s.copy(this.spaces[r].toXYZ).multiply(this.spaces[o].fromXYZ)},_getDrawingBufferColorSpace:function(s){return this.spaces[s].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(s=this.workingColorSpace){return this.spaces[s].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(s,r){return fs("THREE.ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),i.workingToColorSpace(s,r)},toWorkingColorSpace:function(s,r){return fs("THREE.ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),i.colorSpaceToWorking(s,r)}},t=[.64,.33,.3,.6,.15,.06],e=[.2126,.7152,.0722],n=[.3127,.329];return i.define({[Yn]:{primaries:t,whitePoint:n,transfer:Ys,toXYZ:eh,fromXYZ:nh,luminanceCoefficients:e,workingColorSpaceConfig:{unpackColorSpace:De},outputColorSpaceConfig:{drawingBufferColorSpace:De}},[De]:{primaries:t,whitePoint:n,transfer:ne,toXYZ:eh,fromXYZ:nh,luminanceCoefficients:e,outputColorSpaceConfig:{drawingBufferColorSpace:De}}}),i}var Qt=Qd();function Xn(i){return i<.04045?i*.0773993808:Math.pow(i*.9478672986+.0521327014,2.4)}function cs(i){return i<.0031308?i*12.92:1.055*Math.pow(i,.41666)-.055}var $i,_o=class{static getDataURL(t,e="image/png"){if(/^data:/i.test(t.src)||typeof HTMLCanvasElement>"u")return t.src;let n;if(t instanceof HTMLCanvasElement)n=t;else{$i===void 0&&($i=Js("canvas")),$i.width=t.width,$i.height=t.height;let s=$i.getContext("2d");t instanceof ImageData?s.putImageData(t,0,0):s.drawImage(t,0,0,t.width,t.height),n=$i}return n.toDataURL(e)}static sRGBToLinear(t){if(typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&t instanceof ImageBitmap){let e=Js("canvas");e.width=t.width,e.height=t.height;let n=e.getContext("2d");n.drawImage(t,0,0,t.width,t.height);let s=n.getImageData(0,0,t.width,t.height),r=s.data;for(let o=0;o1),this.pmremVersion=0}get width(){return this.source.getSize(nl).x}get height(){return this.source.getSize(nl).y}get depth(){return this.source.getSize(nl).z}get image(){return this.source.data}set image(t=null){this.source.data=t}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(t,e){this.updateRanges.push({start:t,count:e})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(t){return this.name=t.name,this.source=t.source,this.mipmaps=t.mipmaps.slice(0),this.mapping=t.mapping,this.channel=t.channel,this.wrapS=t.wrapS,this.wrapT=t.wrapT,this.magFilter=t.magFilter,this.minFilter=t.minFilter,this.anisotropy=t.anisotropy,this.format=t.format,this.internalFormat=t.internalFormat,this.type=t.type,this.offset.copy(t.offset),this.repeat.copy(t.repeat),this.center.copy(t.center),this.rotation=t.rotation,this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrix.copy(t.matrix),this.generateMipmaps=t.generateMipmaps,this.premultiplyAlpha=t.premultiplyAlpha,this.flipY=t.flipY,this.unpackAlignment=t.unpackAlignment,this.colorSpace=t.colorSpace,this.renderTarget=t.renderTarget,this.isRenderTargetTexture=t.isRenderTargetTexture,this.isArrayTexture=t.isArrayTexture,this.userData=JSON.parse(JSON.stringify(t.userData)),this.needsUpdate=!0,this}setValues(t){for(let e in t){let n=t[e];if(n===void 0){console.warn(`THREE.Texture.setValues(): parameter '${e}' has value of undefined.`);continue}let s=this[e];if(s===void 0){console.warn(`THREE.Texture.setValues(): property '${e}' does not exist.`);continue}s&&n&&s.isVector2&&n.isVector2||s&&n&&s.isVector3&&n.isVector3||s&&n&&s.isMatrix3&&n.isMatrix3?s.copy(n):this[e]=n}}toJSON(t){let e=t===void 0||typeof t=="string";if(!e&&t.textures[this.uuid]!==void 0)return t.textures[this.uuid];let n={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(t).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(n.userData=this.userData),e||(t.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(t){if(this.mapping!==Gl)return t;if(t.applyMatrix3(this.matrix),t.x<0||t.x>1)switch(this.wrapS){case hs:t.x=t.x-Math.floor(t.x);break;case li:t.x=t.x<0?0:1;break;case mo:Math.abs(Math.floor(t.x)%2)===1?t.x=Math.ceil(t.x)-t.x:t.x=t.x-Math.floor(t.x);break}if(t.y<0||t.y>1)switch(this.wrapT){case hs:t.y=t.y-Math.floor(t.y);break;case li:t.y=t.y<0?0:1;break;case mo:Math.abs(Math.floor(t.y)%2)===1?t.y=Math.ceil(t.y)-t.y:t.y=t.y-Math.floor(t.y);break}return this.flipY&&(t.y=1-t.y),t}set needsUpdate(t){t===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(t){t===!0&&this.pmremVersion++}};Ye.DEFAULT_IMAGE=null;Ye.DEFAULT_MAPPING=Gl;Ye.DEFAULT_ANISOTROPY=1;var ve=class i{constructor(t=0,e=0,n=0,s=1){i.prototype.isVector4=!0,this.x=t,this.y=e,this.z=n,this.w=s}get width(){return this.z}set width(t){this.z=t}get height(){return this.w}set height(t){this.w=t}set(t,e,n,s){return this.x=t,this.y=e,this.z=n,this.w=s,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this.w=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setW(t){return this.w=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;case 3:this.w=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w!==void 0?t.w:1,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this.w+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this.w=t.w+e.w,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this.w+=t.w*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this.w-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this.w=t.w-e.w,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this}applyMatrix4(t){let e=this.x,n=this.y,s=this.z,r=this.w,o=t.elements;return this.x=o[0]*e+o[4]*n+o[8]*s+o[12]*r,this.y=o[1]*e+o[5]*n+o[9]*s+o[13]*r,this.z=o[2]*e+o[6]*n+o[10]*s+o[14]*r,this.w=o[3]*e+o[7]*n+o[11]*s+o[15]*r,this}divide(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this.w/=t.w,this}divideScalar(t){return this.multiplyScalar(1/t)}setAxisAngleFromQuaternion(t){this.w=2*Math.acos(t.w);let e=Math.sqrt(1-t.w*t.w);return e<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=t.x/e,this.y=t.y/e,this.z=t.z/e),this}setAxisAngleFromRotationMatrix(t){let e,n,s,r,l=t.elements,c=l[0],h=l[4],u=l[8],d=l[1],p=l[5],g=l[9],_=l[2],m=l[6],f=l[10];if(Math.abs(h-d)<.01&&Math.abs(u-_)<.01&&Math.abs(g-m)<.01){if(Math.abs(h+d)<.1&&Math.abs(u+_)<.1&&Math.abs(g+m)<.1&&Math.abs(c+p+f-3)<.1)return this.set(1,0,0,0),this;e=Math.PI;let M=(c+1)/2,x=(p+1)/2,R=(f+1)/2,T=(h+d)/4,P=(u+_)/4,D=(g+m)/4;return M>x&&M>R?M<.01?(n=0,s=.707106781,r=.707106781):(n=Math.sqrt(M),s=T/n,r=P/n):x>R?x<.01?(n=.707106781,s=0,r=.707106781):(s=Math.sqrt(x),n=T/s,r=D/s):R<.01?(n=.707106781,s=.707106781,r=0):(r=Math.sqrt(R),n=P/r,s=D/r),this.set(n,s,r,e),this}let w=Math.sqrt((m-g)*(m-g)+(u-_)*(u-_)+(d-h)*(d-h));return Math.abs(w)<.001&&(w=1),this.x=(m-g)/w,this.y=(u-_)/w,this.z=(d-h)/w,this.w=Math.acos((c+p+f-1)/2),this}setFromMatrixPosition(t){let e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this.w=e[15],this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this.w=Math.min(this.w,t.w),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this.w=Math.max(this.w,t.w),this}clamp(t,e){return this.x=Zt(this.x,t.x,e.x),this.y=Zt(this.y,t.y,e.y),this.z=Zt(this.z,t.z,e.z),this.w=Zt(this.w,t.w,e.w),this}clampScalar(t,e){return this.x=Zt(this.x,t,e),this.y=Zt(this.y,t,e),this.z=Zt(this.z,t,e),this.w=Zt(this.w,t,e),this}clampLength(t,e){let n=this.length();return this.divideScalar(n||1).multiplyScalar(Zt(n,t,e))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z+this.w*t.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this.w+=(t.w-this.w)*e,this}lerpVectors(t,e,n){return this.x=t.x+(e.x-t.x)*n,this.y=t.y+(e.y-t.y)*n,this.z=t.z+(e.z-t.z)*n,this.w=t.w+(e.w-t.w)*n,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z&&t.w===this.w}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this.w=t[e+3],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t[e+3]=this.w,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this.z=t.getZ(e),this.w=t.getW(e),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}},xo=class extends Rn{constructor(t=1,e=1,n={}){super(),n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Mn,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},n),this.isRenderTarget=!0,this.width=t,this.height=e,this.depth=n.depth,this.scissor=new ve(0,0,t,e),this.scissorTest=!1,this.viewport=new ve(0,0,t,e);let s={width:t,height:e,depth:n.depth},r=new Ye(s);this.textures=[];let o=n.count;for(let a=0;a1;this.dispose()}this.viewport.set(0,0,t,e),this.scissor.set(0,0,t,e)}clone(){return new this.constructor().copy(this)}copy(t){this.width=t.width,this.height=t.height,this.depth=t.depth,this.scissor.copy(t.scissor),this.scissorTest=t.scissorTest,this.viewport.copy(t.viewport),this.textures.length=0;for(let e=0,n=t.textures.length;e=this.min.x&&t.x<=this.max.x&&t.y>=this.min.y&&t.y<=this.max.y&&t.z>=this.min.z&&t.z<=this.max.z}containsBox(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y&&this.min.z<=t.min.z&&t.max.z<=this.max.z}getParameter(t,e){return e.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y),(t.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(t){return t.max.x>=this.min.x&&t.min.x<=this.max.x&&t.max.y>=this.min.y&&t.min.y<=this.max.y&&t.max.z>=this.min.z&&t.min.z<=this.max.z}intersectsSphere(t){return this.clampPoint(t.center,gn),gn.distanceToSquared(t.center)<=t.radius*t.radius}intersectsPlane(t){let e,n;return t.normal.x>0?(e=t.normal.x*this.min.x,n=t.normal.x*this.max.x):(e=t.normal.x*this.max.x,n=t.normal.x*this.min.x),t.normal.y>0?(e+=t.normal.y*this.min.y,n+=t.normal.y*this.max.y):(e+=t.normal.y*this.max.y,n+=t.normal.y*this.min.y),t.normal.z>0?(e+=t.normal.z*this.min.z,n+=t.normal.z*this.max.z):(e+=t.normal.z*this.max.z,n+=t.normal.z*this.min.z),e<=-t.constant&&n>=-t.constant}intersectsTriangle(t){if(this.isEmpty())return!1;this.getCenter(Fs),Gr.subVectors(this.max,Fs),Ki.subVectors(t.a,Fs),ji.subVectors(t.b,Fs),Qi.subVectors(t.c,Fs),ei.subVectors(ji,Ki),ni.subVectors(Qi,ji),wi.subVectors(Ki,Qi);let e=[0,-ei.z,ei.y,0,-ni.z,ni.y,0,-wi.z,wi.y,ei.z,0,-ei.x,ni.z,0,-ni.x,wi.z,0,-wi.x,-ei.y,ei.x,0,-ni.y,ni.x,0,-wi.y,wi.x,0];return!il(e,Ki,ji,Qi,Gr)||(e=[1,0,0,0,1,0,0,0,1],!il(e,Ki,ji,Qi,Gr))?!1:(Wr.crossVectors(ei,ni),e=[Wr.x,Wr.y,Wr.z],il(e,Ki,ji,Qi,Gr))}clampPoint(t,e){return e.copy(t).clamp(this.min,this.max)}distanceToPoint(t){return this.clampPoint(t,gn).distanceTo(t)}getBoundingSphere(t){return this.isEmpty()?t.makeEmpty():(this.getCenter(t.center),t.radius=this.getSize(gn).length()*.5),t}intersect(t){return this.min.max(t.min),this.max.min(t.max),this.isEmpty()&&this.makeEmpty(),this}union(t){return this.min.min(t.min),this.max.max(t.max),this}applyMatrix4(t){return this.isEmpty()?this:(kn[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(t),kn[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(t),kn[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(t),kn[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(t),kn[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(t),kn[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(t),kn[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(t),kn[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(t),this.setFromPoints(kn),this)}translate(t){return this.min.add(t),this.max.add(t),this}equals(t){return t.min.equals(this.min)&&t.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(t){return this.min.fromArray(t.min),this.max.fromArray(t.max),this}},kn=[new A,new A,new A,new A,new A,new A,new A,new A],gn=new A,Vr=new hi,Ki=new A,ji=new A,Qi=new A,ei=new A,ni=new A,wi=new A,Fs=new A,Gr=new A,Wr=new A,Ei=new A;function il(i,t,e,n,s){for(let r=0,o=i.length-3;r<=o;r+=3){Ei.fromArray(i,r);let a=s.x*Math.abs(Ei.x)+s.y*Math.abs(Ei.y)+s.z*Math.abs(Ei.z),l=t.dot(Ei),c=e.dot(Ei),h=n.dot(Ei);if(Math.max(-Math.max(l,c,h),Math.min(l,c,h))>a)return!1}return!0}var nf=new hi,Os=new A,sl=new A,Di=class{constructor(t=new A,e=-1){this.isSphere=!0,this.center=t,this.radius=e}set(t,e){return this.center.copy(t),this.radius=e,this}setFromPoints(t,e){let n=this.center;e!==void 0?n.copy(e):nf.setFromPoints(t).getCenter(n);let s=0;for(let r=0,o=t.length;rthis.radius*this.radius&&(e.sub(this.center).normalize(),e.multiplyScalar(this.radius).add(this.center)),e}getBoundingBox(t){return this.isEmpty()?(t.makeEmpty(),t):(t.set(this.center,this.center),t.expandByScalar(this.radius),t)}applyMatrix4(t){return this.center.applyMatrix4(t),this.radius=this.radius*t.getMaxScaleOnAxis(),this}translate(t){return this.center.add(t),this}expandByPoint(t){if(this.isEmpty())return this.center.copy(t),this.radius=0,this;Os.subVectors(t,this.center);let e=Os.lengthSq();if(e>this.radius*this.radius){let n=Math.sqrt(e),s=(n-this.radius)*.5;this.center.addScaledVector(Os,s/n),this.radius+=s}return this}union(t){return t.isEmpty()?this:this.isEmpty()?(this.copy(t),this):(this.center.equals(t.center)===!0?this.radius=Math.max(this.radius,t.radius):(sl.subVectors(t.center,this.center).setLength(t.radius),this.expandByPoint(Os.copy(t.center).add(sl)),this.expandByPoint(Os.copy(t.center).sub(sl))),this)}equals(t){return t.center.equals(this.center)&&t.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(t){return this.radius=t.radius,this.center.fromArray(t.center),this}},Hn=new A,rl=new A,Xr=new A,ii=new A,ol=new A,qr=new A,al=new A,ui=class{constructor(t=new A,e=new A(0,0,-1)){this.origin=t,this.direction=e}set(t,e){return this.origin.copy(t),this.direction.copy(e),this}copy(t){return this.origin.copy(t.origin),this.direction.copy(t.direction),this}at(t,e){return e.copy(this.origin).addScaledVector(this.direction,t)}lookAt(t){return this.direction.copy(t).sub(this.origin).normalize(),this}recast(t){return this.origin.copy(this.at(t,Hn)),this}closestPointToPoint(t,e){e.subVectors(t,this.origin);let n=e.dot(this.direction);return n<0?e.copy(this.origin):e.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(t){return Math.sqrt(this.distanceSqToPoint(t))}distanceSqToPoint(t){let e=Hn.subVectors(t,this.origin).dot(this.direction);return e<0?this.origin.distanceToSquared(t):(Hn.copy(this.origin).addScaledVector(this.direction,e),Hn.distanceToSquared(t))}distanceSqToSegment(t,e,n,s){rl.copy(t).add(e).multiplyScalar(.5),Xr.copy(e).sub(t).normalize(),ii.copy(this.origin).sub(rl);let r=t.distanceTo(e)*.5,o=-this.direction.dot(Xr),a=ii.dot(this.direction),l=-ii.dot(Xr),c=ii.lengthSq(),h=Math.abs(1-o*o),u,d,p,g;if(h>0)if(u=o*l-a,d=o*a-l,g=r*h,u>=0)if(d>=-g)if(d<=g){let _=1/h;u*=_,d*=_,p=u*(u+o*d+2*a)+d*(o*u+d+2*l)+c}else d=r,u=Math.max(0,-(o*d+a)),p=-u*u+d*(d+2*l)+c;else d=-r,u=Math.max(0,-(o*d+a)),p=-u*u+d*(d+2*l)+c;else d<=-g?(u=Math.max(0,-(-o*r+a)),d=u>0?-r:Math.min(Math.max(-r,-l),r),p=-u*u+d*(d+2*l)+c):d<=g?(u=0,d=Math.min(Math.max(-r,-l),r),p=d*(d+2*l)+c):(u=Math.max(0,-(o*r+a)),d=u>0?r:Math.min(Math.max(-r,-l),r),p=-u*u+d*(d+2*l)+c);else d=o>0?-r:r,u=Math.max(0,-(o*d+a)),p=-u*u+d*(d+2*l)+c;return n&&n.copy(this.origin).addScaledVector(this.direction,u),s&&s.copy(rl).addScaledVector(Xr,d),p}intersectSphere(t,e){Hn.subVectors(t.center,this.origin);let n=Hn.dot(this.direction),s=Hn.dot(Hn)-n*n,r=t.radius*t.radius;if(s>r)return null;let o=Math.sqrt(r-s),a=n-o,l=n+o;return l<0?null:a<0?this.at(l,e):this.at(a,e)}intersectsSphere(t){return t.radius<0?!1:this.distanceSqToPoint(t.center)<=t.radius*t.radius}distanceToPlane(t){let e=t.normal.dot(this.direction);if(e===0)return t.distanceToPoint(this.origin)===0?0:null;let n=-(this.origin.dot(t.normal)+t.constant)/e;return n>=0?n:null}intersectPlane(t,e){let n=this.distanceToPlane(t);return n===null?null:this.at(n,e)}intersectsPlane(t){let e=t.distanceToPoint(this.origin);return e===0||t.normal.dot(this.direction)*e<0}intersectBox(t,e){let n,s,r,o,a,l,c=1/this.direction.x,h=1/this.direction.y,u=1/this.direction.z,d=this.origin;return c>=0?(n=(t.min.x-d.x)*c,s=(t.max.x-d.x)*c):(n=(t.max.x-d.x)*c,s=(t.min.x-d.x)*c),h>=0?(r=(t.min.y-d.y)*h,o=(t.max.y-d.y)*h):(r=(t.max.y-d.y)*h,o=(t.min.y-d.y)*h),n>o||r>s||((r>n||isNaN(n))&&(n=r),(o=0?(a=(t.min.z-d.z)*u,l=(t.max.z-d.z)*u):(a=(t.max.z-d.z)*u,l=(t.min.z-d.z)*u),n>l||a>s)||((a>n||n!==n)&&(n=a),(l=0?n:s,e)}intersectsBox(t){return this.intersectBox(t,Hn)!==null}intersectTriangle(t,e,n,s,r){ol.subVectors(e,t),qr.subVectors(n,t),al.crossVectors(ol,qr);let o=this.direction.dot(al),a;if(o>0){if(s)return null;a=1}else if(o<0)a=-1,o=-o;else return null;ii.subVectors(this.origin,t);let l=a*this.direction.dot(qr.crossVectors(ii,qr));if(l<0)return null;let c=a*this.direction.dot(ol.cross(ii));if(c<0||l+c>o)return null;let h=-a*ii.dot(al);return h<0?null:this.at(h/o,r)}applyMatrix4(t){return this.origin.applyMatrix4(t),this.direction.transformDirection(t),this}equals(t){return t.origin.equals(this.origin)&&t.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}},oe=class i{constructor(t,e,n,s,r,o,a,l,c,h,u,d,p,g,_,m){i.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],t!==void 0&&this.set(t,e,n,s,r,o,a,l,c,h,u,d,p,g,_,m)}set(t,e,n,s,r,o,a,l,c,h,u,d,p,g,_,m){let f=this.elements;return f[0]=t,f[4]=e,f[8]=n,f[12]=s,f[1]=r,f[5]=o,f[9]=a,f[13]=l,f[2]=c,f[6]=h,f[10]=u,f[14]=d,f[3]=p,f[7]=g,f[11]=_,f[15]=m,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new i().fromArray(this.elements)}copy(t){let e=this.elements,n=t.elements;return e[0]=n[0],e[1]=n[1],e[2]=n[2],e[3]=n[3],e[4]=n[4],e[5]=n[5],e[6]=n[6],e[7]=n[7],e[8]=n[8],e[9]=n[9],e[10]=n[10],e[11]=n[11],e[12]=n[12],e[13]=n[13],e[14]=n[14],e[15]=n[15],this}copyPosition(t){let e=this.elements,n=t.elements;return e[12]=n[12],e[13]=n[13],e[14]=n[14],this}setFromMatrix3(t){let e=t.elements;return this.set(e[0],e[3],e[6],0,e[1],e[4],e[7],0,e[2],e[5],e[8],0,0,0,0,1),this}extractBasis(t,e,n){return t.setFromMatrixColumn(this,0),e.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this}makeBasis(t,e,n){return this.set(t.x,e.x,n.x,0,t.y,e.y,n.y,0,t.z,e.z,n.z,0,0,0,0,1),this}extractRotation(t){let e=this.elements,n=t.elements,s=1/ts.setFromMatrixColumn(t,0).length(),r=1/ts.setFromMatrixColumn(t,1).length(),o=1/ts.setFromMatrixColumn(t,2).length();return e[0]=n[0]*s,e[1]=n[1]*s,e[2]=n[2]*s,e[3]=0,e[4]=n[4]*r,e[5]=n[5]*r,e[6]=n[6]*r,e[7]=0,e[8]=n[8]*o,e[9]=n[9]*o,e[10]=n[10]*o,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromEuler(t){let e=this.elements,n=t.x,s=t.y,r=t.z,o=Math.cos(n),a=Math.sin(n),l=Math.cos(s),c=Math.sin(s),h=Math.cos(r),u=Math.sin(r);if(t.order==="XYZ"){let d=o*h,p=o*u,g=a*h,_=a*u;e[0]=l*h,e[4]=-l*u,e[8]=c,e[1]=p+g*c,e[5]=d-_*c,e[9]=-a*l,e[2]=_-d*c,e[6]=g+p*c,e[10]=o*l}else if(t.order==="YXZ"){let d=l*h,p=l*u,g=c*h,_=c*u;e[0]=d+_*a,e[4]=g*a-p,e[8]=o*c,e[1]=o*u,e[5]=o*h,e[9]=-a,e[2]=p*a-g,e[6]=_+d*a,e[10]=o*l}else if(t.order==="ZXY"){let d=l*h,p=l*u,g=c*h,_=c*u;e[0]=d-_*a,e[4]=-o*u,e[8]=g+p*a,e[1]=p+g*a,e[5]=o*h,e[9]=_-d*a,e[2]=-o*c,e[6]=a,e[10]=o*l}else if(t.order==="ZYX"){let d=o*h,p=o*u,g=a*h,_=a*u;e[0]=l*h,e[4]=g*c-p,e[8]=d*c+_,e[1]=l*u,e[5]=_*c+d,e[9]=p*c-g,e[2]=-c,e[6]=a*l,e[10]=o*l}else if(t.order==="YZX"){let d=o*l,p=o*c,g=a*l,_=a*c;e[0]=l*h,e[4]=_-d*u,e[8]=g*u+p,e[1]=u,e[5]=o*h,e[9]=-a*h,e[2]=-c*h,e[6]=p*u+g,e[10]=d-_*u}else if(t.order==="XZY"){let d=o*l,p=o*c,g=a*l,_=a*c;e[0]=l*h,e[4]=-u,e[8]=c*h,e[1]=d*u+_,e[5]=o*h,e[9]=p*u-g,e[2]=g*u-p,e[6]=a*h,e[10]=_*u+d}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromQuaternion(t){return this.compose(sf,t,rf)}lookAt(t,e,n){let s=this.elements;return je.subVectors(t,e),je.lengthSq()===0&&(je.z=1),je.normalize(),si.crossVectors(n,je),si.lengthSq()===0&&(Math.abs(n.z)===1?je.x+=1e-4:je.z+=1e-4,je.normalize(),si.crossVectors(n,je)),si.normalize(),Yr.crossVectors(je,si),s[0]=si.x,s[4]=Yr.x,s[8]=je.x,s[1]=si.y,s[5]=Yr.y,s[9]=je.y,s[2]=si.z,s[6]=Yr.z,s[10]=je.z,this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){let n=t.elements,s=e.elements,r=this.elements,o=n[0],a=n[4],l=n[8],c=n[12],h=n[1],u=n[5],d=n[9],p=n[13],g=n[2],_=n[6],m=n[10],f=n[14],w=n[3],M=n[7],x=n[11],R=n[15],T=s[0],P=s[4],D=s[8],S=s[12],v=s[1],I=s[5],F=s[9],z=s[13],k=s[2],V=s[6],G=s[10],tt=s[14],W=s[3],B=s[7],Z=s[11],Q=s[15];return r[0]=o*T+a*v+l*k+c*W,r[4]=o*P+a*I+l*V+c*B,r[8]=o*D+a*F+l*G+c*Z,r[12]=o*S+a*z+l*tt+c*Q,r[1]=h*T+u*v+d*k+p*W,r[5]=h*P+u*I+d*V+p*B,r[9]=h*D+u*F+d*G+p*Z,r[13]=h*S+u*z+d*tt+p*Q,r[2]=g*T+_*v+m*k+f*W,r[6]=g*P+_*I+m*V+f*B,r[10]=g*D+_*F+m*G+f*Z,r[14]=g*S+_*z+m*tt+f*Q,r[3]=w*T+M*v+x*k+R*W,r[7]=w*P+M*I+x*V+R*B,r[11]=w*D+M*F+x*G+R*Z,r[15]=w*S+M*z+x*tt+R*Q,this}multiplyScalar(t){let e=this.elements;return e[0]*=t,e[4]*=t,e[8]*=t,e[12]*=t,e[1]*=t,e[5]*=t,e[9]*=t,e[13]*=t,e[2]*=t,e[6]*=t,e[10]*=t,e[14]*=t,e[3]*=t,e[7]*=t,e[11]*=t,e[15]*=t,this}determinant(){let t=this.elements,e=t[0],n=t[4],s=t[8],r=t[12],o=t[1],a=t[5],l=t[9],c=t[13],h=t[2],u=t[6],d=t[10],p=t[14],g=t[3],_=t[7],m=t[11],f=t[15];return g*(+r*l*u-s*c*u-r*a*d+n*c*d+s*a*p-n*l*p)+_*(+e*l*p-e*c*d+r*o*d-s*o*p+s*c*h-r*l*h)+m*(+e*c*u-e*a*p-r*o*u+n*o*p+r*a*h-n*c*h)+f*(-s*a*h-e*l*u+e*a*d+s*o*u-n*o*d+n*l*h)}transpose(){let t=this.elements,e;return e=t[1],t[1]=t[4],t[4]=e,e=t[2],t[2]=t[8],t[8]=e,e=t[6],t[6]=t[9],t[9]=e,e=t[3],t[3]=t[12],t[12]=e,e=t[7],t[7]=t[13],t[13]=e,e=t[11],t[11]=t[14],t[14]=e,this}setPosition(t,e,n){let s=this.elements;return t.isVector3?(s[12]=t.x,s[13]=t.y,s[14]=t.z):(s[12]=t,s[13]=e,s[14]=n),this}invert(){let t=this.elements,e=t[0],n=t[1],s=t[2],r=t[3],o=t[4],a=t[5],l=t[6],c=t[7],h=t[8],u=t[9],d=t[10],p=t[11],g=t[12],_=t[13],m=t[14],f=t[15],w=u*m*c-_*d*c+_*l*p-a*m*p-u*l*f+a*d*f,M=g*d*c-h*m*c-g*l*p+o*m*p+h*l*f-o*d*f,x=h*_*c-g*u*c+g*a*p-o*_*p-h*a*f+o*u*f,R=g*u*l-h*_*l-g*a*d+o*_*d+h*a*m-o*u*m,T=e*w+n*M+s*x+r*R;if(T===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);let P=1/T;return t[0]=w*P,t[1]=(_*d*r-u*m*r-_*s*p+n*m*p+u*s*f-n*d*f)*P,t[2]=(a*m*r-_*l*r+_*s*c-n*m*c-a*s*f+n*l*f)*P,t[3]=(u*l*r-a*d*r-u*s*c+n*d*c+a*s*p-n*l*p)*P,t[4]=M*P,t[5]=(h*m*r-g*d*r+g*s*p-e*m*p-h*s*f+e*d*f)*P,t[6]=(g*l*r-o*m*r-g*s*c+e*m*c+o*s*f-e*l*f)*P,t[7]=(o*d*r-h*l*r+h*s*c-e*d*c-o*s*p+e*l*p)*P,t[8]=x*P,t[9]=(g*u*r-h*_*r-g*n*p+e*_*p+h*n*f-e*u*f)*P,t[10]=(o*_*r-g*a*r+g*n*c-e*_*c-o*n*f+e*a*f)*P,t[11]=(h*a*r-o*u*r-h*n*c+e*u*c+o*n*p-e*a*p)*P,t[12]=R*P,t[13]=(h*_*s-g*u*s+g*n*d-e*_*d-h*n*m+e*u*m)*P,t[14]=(g*a*s-o*_*s-g*n*l+e*_*l+o*n*m-e*a*m)*P,t[15]=(o*u*s-h*a*s+h*n*l-e*u*l-o*n*d+e*a*d)*P,this}scale(t){let e=this.elements,n=t.x,s=t.y,r=t.z;return e[0]*=n,e[4]*=s,e[8]*=r,e[1]*=n,e[5]*=s,e[9]*=r,e[2]*=n,e[6]*=s,e[10]*=r,e[3]*=n,e[7]*=s,e[11]*=r,this}getMaxScaleOnAxis(){let t=this.elements,e=t[0]*t[0]+t[1]*t[1]+t[2]*t[2],n=t[4]*t[4]+t[5]*t[5]+t[6]*t[6],s=t[8]*t[8]+t[9]*t[9]+t[10]*t[10];return Math.sqrt(Math.max(e,n,s))}makeTranslation(t,e,n){return t.isVector3?this.set(1,0,0,t.x,0,1,0,t.y,0,0,1,t.z,0,0,0,1):this.set(1,0,0,t,0,1,0,e,0,0,1,n,0,0,0,1),this}makeRotationX(t){let e=Math.cos(t),n=Math.sin(t);return this.set(1,0,0,0,0,e,-n,0,0,n,e,0,0,0,0,1),this}makeRotationY(t){let e=Math.cos(t),n=Math.sin(t);return this.set(e,0,n,0,0,1,0,0,-n,0,e,0,0,0,0,1),this}makeRotationZ(t){let e=Math.cos(t),n=Math.sin(t);return this.set(e,-n,0,0,n,e,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(t,e){let n=Math.cos(e),s=Math.sin(e),r=1-n,o=t.x,a=t.y,l=t.z,c=r*o,h=r*a;return this.set(c*o+n,c*a-s*l,c*l+s*a,0,c*a+s*l,h*a+n,h*l-s*o,0,c*l-s*a,h*l+s*o,r*l*l+n,0,0,0,0,1),this}makeScale(t,e,n){return this.set(t,0,0,0,0,e,0,0,0,0,n,0,0,0,0,1),this}makeShear(t,e,n,s,r,o){return this.set(1,n,r,0,t,1,o,0,e,s,1,0,0,0,0,1),this}compose(t,e,n){let s=this.elements,r=e._x,o=e._y,a=e._z,l=e._w,c=r+r,h=o+o,u=a+a,d=r*c,p=r*h,g=r*u,_=o*h,m=o*u,f=a*u,w=l*c,M=l*h,x=l*u,R=n.x,T=n.y,P=n.z;return s[0]=(1-(_+f))*R,s[1]=(p+x)*R,s[2]=(g-M)*R,s[3]=0,s[4]=(p-x)*T,s[5]=(1-(d+f))*T,s[6]=(m+w)*T,s[7]=0,s[8]=(g+M)*P,s[9]=(m-w)*P,s[10]=(1-(d+_))*P,s[11]=0,s[12]=t.x,s[13]=t.y,s[14]=t.z,s[15]=1,this}decompose(t,e,n){let s=this.elements,r=ts.set(s[0],s[1],s[2]).length(),o=ts.set(s[4],s[5],s[6]).length(),a=ts.set(s[8],s[9],s[10]).length();this.determinant()<0&&(r=-r),t.x=s[12],t.y=s[13],t.z=s[14],_n.copy(this);let c=1/r,h=1/o,u=1/a;return _n.elements[0]*=c,_n.elements[1]*=c,_n.elements[2]*=c,_n.elements[4]*=h,_n.elements[5]*=h,_n.elements[6]*=h,_n.elements[8]*=u,_n.elements[9]*=u,_n.elements[10]*=u,e.setFromRotationMatrix(_n),n.x=r,n.y=o,n.z=a,this}makePerspective(t,e,n,s,r,o,a=yn,l=!1){let c=this.elements,h=2*r/(e-t),u=2*r/(n-s),d=(e+t)/(e-t),p=(n+s)/(n-s),g,_;if(l)g=r/(o-r),_=o*r/(o-r);else if(a===yn)g=-(o+r)/(o-r),_=-2*o*r/(o-r);else if(a===Zs)g=-o/(o-r),_=-o*r/(o-r);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);return c[0]=h,c[4]=0,c[8]=d,c[12]=0,c[1]=0,c[5]=u,c[9]=p,c[13]=0,c[2]=0,c[6]=0,c[10]=g,c[14]=_,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(t,e,n,s,r,o,a=yn,l=!1){let c=this.elements,h=2/(e-t),u=2/(n-s),d=-(e+t)/(e-t),p=-(n+s)/(n-s),g,_;if(l)g=1/(o-r),_=o/(o-r);else if(a===yn)g=-2/(o-r),_=-(o+r)/(o-r);else if(a===Zs)g=-1/(o-r),_=-r/(o-r);else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);return c[0]=h,c[4]=0,c[8]=0,c[12]=d,c[1]=0,c[5]=u,c[9]=0,c[13]=p,c[2]=0,c[6]=0,c[10]=g,c[14]=_,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(t){let e=this.elements,n=t.elements;for(let s=0;s<16;s++)if(e[s]!==n[s])return!1;return!0}fromArray(t,e=0){for(let n=0;n<16;n++)this.elements[n]=t[n+e];return this}toArray(t=[],e=0){let n=this.elements;return t[e]=n[0],t[e+1]=n[1],t[e+2]=n[2],t[e+3]=n[3],t[e+4]=n[4],t[e+5]=n[5],t[e+6]=n[6],t[e+7]=n[7],t[e+8]=n[8],t[e+9]=n[9],t[e+10]=n[10],t[e+11]=n[11],t[e+12]=n[12],t[e+13]=n[13],t[e+14]=n[14],t[e+15]=n[15],t}},ts=new A,_n=new oe,sf=new A(0,0,0),rf=new A(1,1,1),si=new A,Yr=new A,je=new A,ih=new oe,sh=new ye,tn=class i{constructor(t=0,e=0,n=0,s=i.DEFAULT_ORDER){this.isEuler=!0,this._x=t,this._y=e,this._z=n,this._order=s}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get order(){return this._order}set order(t){this._order=t,this._onChangeCallback()}set(t,e,n,s=this._order){return this._x=t,this._y=e,this._z=n,this._order=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(t){return this._x=t._x,this._y=t._y,this._z=t._z,this._order=t._order,this._onChangeCallback(),this}setFromRotationMatrix(t,e=this._order,n=!0){let s=t.elements,r=s[0],o=s[4],a=s[8],l=s[1],c=s[5],h=s[9],u=s[2],d=s[6],p=s[10];switch(e){case"XYZ":this._y=Math.asin(Zt(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-h,p),this._z=Math.atan2(-o,r)):(this._x=Math.atan2(d,c),this._z=0);break;case"YXZ":this._x=Math.asin(-Zt(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(a,p),this._z=Math.atan2(l,c)):(this._y=Math.atan2(-u,r),this._z=0);break;case"ZXY":this._x=Math.asin(Zt(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-u,p),this._z=Math.atan2(-o,c)):(this._y=0,this._z=Math.atan2(l,r));break;case"ZYX":this._y=Math.asin(-Zt(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(d,p),this._z=Math.atan2(l,r)):(this._x=0,this._z=Math.atan2(-o,c));break;case"YZX":this._z=Math.asin(Zt(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(-h,c),this._y=Math.atan2(-u,r)):(this._x=0,this._y=Math.atan2(a,p));break;case"XZY":this._z=Math.asin(-Zt(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(d,c),this._y=Math.atan2(a,r)):(this._x=Math.atan2(-h,p),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+e)}return this._order=e,n===!0&&this._onChangeCallback(),this}setFromQuaternion(t,e,n){return ih.makeRotationFromQuaternion(t),this.setFromRotationMatrix(ih,e,n)}setFromVector3(t,e=this._order){return this.set(t.x,t.y,t.z,e)}reorder(t){return sh.setFromEuler(this),this.setFromQuaternion(sh,t)}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._order===this._order}fromArray(t){return this._x=t[0],this._y=t[1],this._z=t[2],t[3]!==void 0&&(this._order=t[3]),this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._order,t}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}};tn.DEFAULT_ORDER="XYZ";var ms=class{constructor(){this.mask=1}set(t){this.mask=(1<>>0}enable(t){this.mask|=1<1){for(let e=0;e1){for(let n=0;n0&&(s.userData=this.userData),s.layers=this.layers.mask,s.matrix=this.matrix.toArray(),s.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(s.matrixAutoUpdate=!1),this.isInstancedMesh&&(s.type="InstancedMesh",s.count=this.count,s.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(s.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(s.type="BatchedMesh",s.perObjectFrustumCulled=this.perObjectFrustumCulled,s.sortObjects=this.sortObjects,s.drawRanges=this._drawRanges,s.reservedRanges=this._reservedRanges,s.geometryInfo=this._geometryInfo.map(a=>({...a,boundingBox:a.boundingBox?a.boundingBox.toJSON():void 0,boundingSphere:a.boundingSphere?a.boundingSphere.toJSON():void 0})),s.instanceInfo=this._instanceInfo.map(a=>({...a})),s.availableInstanceIds=this._availableInstanceIds.slice(),s.availableGeometryIds=this._availableGeometryIds.slice(),s.nextIndexStart=this._nextIndexStart,s.nextVertexStart=this._nextVertexStart,s.geometryCount=this._geometryCount,s.maxInstanceCount=this._maxInstanceCount,s.maxVertexCount=this._maxVertexCount,s.maxIndexCount=this._maxIndexCount,s.geometryInitialized=this._geometryInitialized,s.matricesTexture=this._matricesTexture.toJSON(t),s.indirectTexture=this._indirectTexture.toJSON(t),this._colorsTexture!==null&&(s.colorsTexture=this._colorsTexture.toJSON(t)),this.boundingSphere!==null&&(s.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(s.boundingBox=this.boundingBox.toJSON()));function r(a,l){return a[l.uuid]===void 0&&(a[l.uuid]=l.toJSON(t)),l.uuid}if(this.isScene)this.background&&(this.background.isColor?s.background=this.background.toJSON():this.background.isTexture&&(s.background=this.background.toJSON(t).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(s.environment=this.environment.toJSON(t).uuid);else if(this.isMesh||this.isLine||this.isPoints){s.geometry=r(t.geometries,this.geometry);let a=this.geometry.parameters;if(a!==void 0&&a.shapes!==void 0){let l=a.shapes;if(Array.isArray(l))for(let c=0,h=l.length;c0){s.children=[];for(let a=0;a0){s.animations=[];for(let a=0;a0&&(n.geometries=a),l.length>0&&(n.materials=l),c.length>0&&(n.textures=c),h.length>0&&(n.images=h),u.length>0&&(n.shapes=u),d.length>0&&(n.skeletons=d),p.length>0&&(n.animations=p),g.length>0&&(n.nodes=g)}return n.object=s,n;function o(a){let l=[];for(let c in a){let h=a[c];delete h.metadata,l.push(h)}return l}}clone(t){return new this.constructor().copy(this,t)}copy(t,e=!0){if(this.name=t.name,this.up.copy(t.up),this.position.copy(t.position),this.rotation.order=t.rotation.order,this.quaternion.copy(t.quaternion),this.scale.copy(t.scale),this.matrix.copy(t.matrix),this.matrixWorld.copy(t.matrixWorld),this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrixWorldAutoUpdate=t.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=t.matrixWorldNeedsUpdate,this.layers.mask=t.layers.mask,this.visible=t.visible,this.castShadow=t.castShadow,this.receiveShadow=t.receiveShadow,this.frustumCulled=t.frustumCulled,this.renderOrder=t.renderOrder,this.animations=t.animations.slice(),this.userData=JSON.parse(JSON.stringify(t.userData)),e===!0)for(let n=0;n0?s.multiplyScalar(1/Math.sqrt(r)):s.set(0,0,0)}static getBarycoord(t,e,n,s,r){xn.subVectors(s,e),Gn.subVectors(n,e),cl.subVectors(t,e);let o=xn.dot(xn),a=xn.dot(Gn),l=xn.dot(cl),c=Gn.dot(Gn),h=Gn.dot(cl),u=o*c-a*a;if(u===0)return r.set(0,0,0),null;let d=1/u,p=(c*l-a*h)*d,g=(o*h-a*l)*d;return r.set(1-p-g,g,p)}static containsPoint(t,e,n,s){return this.getBarycoord(t,e,n,s,Wn)===null?!1:Wn.x>=0&&Wn.y>=0&&Wn.x+Wn.y<=1}static getInterpolation(t,e,n,s,r,o,a,l){return this.getBarycoord(t,e,n,s,Wn)===null?(l.x=0,l.y=0,"z"in l&&(l.z=0),"w"in l&&(l.w=0),null):(l.setScalar(0),l.addScaledVector(r,Wn.x),l.addScaledVector(o,Wn.y),l.addScaledVector(a,Wn.z),l)}static getInterpolatedAttribute(t,e,n,s,r,o){return fl.setScalar(0),pl.setScalar(0),ml.setScalar(0),fl.fromBufferAttribute(t,e),pl.fromBufferAttribute(t,n),ml.fromBufferAttribute(t,s),o.setScalar(0),o.addScaledVector(fl,r.x),o.addScaledVector(pl,r.y),o.addScaledVector(ml,r.z),o}static isFrontFacing(t,e,n,s){return xn.subVectors(n,e),Gn.subVectors(t,e),xn.cross(Gn).dot(s)<0}set(t,e,n){return this.a.copy(t),this.b.copy(e),this.c.copy(n),this}setFromPointsAndIndices(t,e,n,s){return this.a.copy(t[e]),this.b.copy(t[n]),this.c.copy(t[s]),this}setFromAttributeAndIndices(t,e,n,s){return this.a.fromBufferAttribute(t,e),this.b.fromBufferAttribute(t,n),this.c.fromBufferAttribute(t,s),this}clone(){return new this.constructor().copy(this)}copy(t){return this.a.copy(t.a),this.b.copy(t.b),this.c.copy(t.c),this}getArea(){return xn.subVectors(this.c,this.b),Gn.subVectors(this.a,this.b),xn.cross(Gn).length()*.5}getMidpoint(t){return t.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return i.getNormal(this.a,this.b,this.c,t)}getPlane(t){return t.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,e){return i.getBarycoord(t,this.a,this.b,this.c,e)}getInterpolation(t,e,n,s,r){return i.getInterpolation(t,this.a,this.b,this.c,e,n,s,r)}containsPoint(t){return i.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return i.isFrontFacing(this.a,this.b,this.c,t)}intersectsBox(t){return t.intersectsTriangle(this)}closestPointToPoint(t,e){let n=this.a,s=this.b,r=this.c,o,a;is.subVectors(s,n),ss.subVectors(r,n),hl.subVectors(t,n);let l=is.dot(hl),c=ss.dot(hl);if(l<=0&&c<=0)return e.copy(n);ul.subVectors(t,s);let h=is.dot(ul),u=ss.dot(ul);if(h>=0&&u<=h)return e.copy(s);let d=l*u-h*c;if(d<=0&&l>=0&&h<=0)return o=l/(l-h),e.copy(n).addScaledVector(is,o);dl.subVectors(t,r);let p=is.dot(dl),g=ss.dot(dl);if(g>=0&&p<=g)return e.copy(r);let _=p*c-l*g;if(_<=0&&c>=0&&g<=0)return a=c/(c-g),e.copy(n).addScaledVector(ss,a);let m=h*g-p*u;if(m<=0&&u-h>=0&&p-g>=0)return hh.subVectors(r,s),a=(u-h)/(u-h+(p-g)),e.copy(s).addScaledVector(hh,a);let f=1/(m+_+d);return o=_*f,a=d*f,e.copy(n).addScaledVector(is,o).addScaledVector(ss,a)}equals(t){return t.a.equals(this.a)&&t.b.equals(this.b)&&t.c.equals(this.c)}},mu={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},ri={h:0,s:0,l:0},Jr={h:0,s:0,l:0};function gl(i,t,e){return e<0&&(e+=1),e>1&&(e-=1),e<1/6?i+(t-i)*6*e:e<1/2?t:e<2/3?i+(t-i)*6*(2/3-e):i}var Gt=class{constructor(t,e,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(t,e,n)}set(t,e,n){if(e===void 0&&n===void 0){let s=t;s&&s.isColor?this.copy(s):typeof s=="number"?this.setHex(s):typeof s=="string"&&this.setStyle(s)}else this.setRGB(t,e,n);return this}setScalar(t){return this.r=t,this.g=t,this.b=t,this}setHex(t,e=De){return t=Math.floor(t),this.r=(t>>16&255)/255,this.g=(t>>8&255)/255,this.b=(t&255)/255,Qt.colorSpaceToWorking(this,e),this}setRGB(t,e,n,s=Qt.workingColorSpace){return this.r=t,this.g=e,this.b=n,Qt.colorSpaceToWorking(this,s),this}setHSL(t,e,n,s=Qt.workingColorSpace){if(t=ec(t,1),e=Zt(e,0,1),n=Zt(n,0,1),e===0)this.r=this.g=this.b=n;else{let r=n<=.5?n*(1+e):n+e-n*e,o=2*n-r;this.r=gl(o,r,t+1/3),this.g=gl(o,r,t),this.b=gl(o,r,t-1/3)}return Qt.colorSpaceToWorking(this,s),this}setStyle(t,e=De){function n(r){r!==void 0&&parseFloat(r)<1&&console.warn("THREE.Color: Alpha component of "+t+" will be ignored.")}let s;if(s=/^(\w+)\(([^\)]*)\)/.exec(t)){let r,o=s[1],a=s[2];switch(o){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setRGB(Math.min(255,parseInt(r[1],10))/255,Math.min(255,parseInt(r[2],10))/255,Math.min(255,parseInt(r[3],10))/255,e);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setRGB(Math.min(100,parseInt(r[1],10))/100,Math.min(100,parseInt(r[2],10))/100,Math.min(100,parseInt(r[3],10))/100,e);break;case"hsl":case"hsla":if(r=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,e);break;default:console.warn("THREE.Color: Unknown color model "+t)}}else if(s=/^\#([A-Fa-f\d]+)$/.exec(t)){let r=s[1],o=r.length;if(o===3)return this.setRGB(parseInt(r.charAt(0),16)/15,parseInt(r.charAt(1),16)/15,parseInt(r.charAt(2),16)/15,e);if(o===6)return this.setHex(parseInt(r,16),e);console.warn("THREE.Color: Invalid hex color "+t)}else if(t&&t.length>0)return this.setColorName(t,e);return this}setColorName(t,e=De){let n=mu[t.toLowerCase()];return n!==void 0?this.setHex(n,e):console.warn("THREE.Color: Unknown color "+t),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(t){return this.r=t.r,this.g=t.g,this.b=t.b,this}copySRGBToLinear(t){return this.r=Xn(t.r),this.g=Xn(t.g),this.b=Xn(t.b),this}copyLinearToSRGB(t){return this.r=cs(t.r),this.g=cs(t.g),this.b=cs(t.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(t=De){return Qt.workingToColorSpace(Ue.copy(this),t),Math.round(Zt(Ue.r*255,0,255))*65536+Math.round(Zt(Ue.g*255,0,255))*256+Math.round(Zt(Ue.b*255,0,255))}getHexString(t=De){return("000000"+this.getHex(t).toString(16)).slice(-6)}getHSL(t,e=Qt.workingColorSpace){Qt.workingToColorSpace(Ue.copy(this),e);let n=Ue.r,s=Ue.g,r=Ue.b,o=Math.max(n,s,r),a=Math.min(n,s,r),l,c,h=(a+o)/2;if(a===o)l=0,c=0;else{let u=o-a;switch(c=h<=.5?u/(o+a):u/(2-o-a),o){case n:l=(s-r)/u+(s0!=t>0&&this.version++,this._alphaTest=t}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(t){if(t!==void 0)for(let e in t){let n=t[e];if(n===void 0){console.warn(`THREE.Material: parameter '${e}' has value of undefined.`);continue}let s=this[e];if(s===void 0){console.warn(`THREE.Material: '${e}' is not a property of THREE.${this.type}.`);continue}s&&s.isColor?s.set(n):s&&s.isVector3&&n&&n.isVector3?s.copy(n):this[e]=n}}toJSON(t){let e=t===void 0||typeof t=="string";e&&(t={textures:{},images:{}});let n={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};n.uuid=this.uuid,n.type=this.type,this.name!==""&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),this.roughness!==void 0&&(n.roughness=this.roughness),this.metalness!==void 0&&(n.metalness=this.metalness),this.sheen!==void 0&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(n.shininess=this.shininess),this.clearcoat!==void 0&&(n.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(t).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(t).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(t).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(n.sheenColorMap=this.sheenColorMap.toJSON(t).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(n.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(t).uuid),this.dispersion!==void 0&&(n.dispersion=this.dispersion),this.iridescence!==void 0&&(n.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(n.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(t).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(t).uuid),this.anisotropy!==void 0&&(n.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(t).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(t).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(t).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(t).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(t).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(t).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(t).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(t).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(t).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(t).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(t).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(t).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(t).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(t).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(t).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(t).uuid,this.combine!==void 0&&(n.combine=this.combine)),this.envMapRotation!==void 0&&(n.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(n.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(n.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(t).uuid),this.transmission!==void 0&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(t).uuid),this.thickness!==void 0&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(t).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(n.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(n.size=this.size),this.shadowSide!==null&&(n.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),this.blending!==Pi&&(n.blending=this.blending),this.side!==qn&&(n.side=this.side),this.vertexColors===!0&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),this.transparent===!0&&(n.transparent=!0),this.blendSrc!==fo&&(n.blendSrc=this.blendSrc),this.blendDst!==po&&(n.blendDst=this.blendDst),this.blendEquation!==ci&&(n.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(n.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(n.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(n.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(n.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(n.blendAlpha=this.blendAlpha),this.depthFunc!==Ii&&(n.depthFunc=this.depthFunc),this.depthTest===!1&&(n.depthTest=this.depthTest),this.depthWrite===!1&&(n.depthWrite=this.depthWrite),this.colorWrite===!1&&(n.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(n.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==Rl&&(n.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(n.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==Ri&&(n.stencilFail=this.stencilFail),this.stencilZFail!==Ri&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==Ri&&(n.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(n.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(n.rotation=this.rotation),this.polygonOffset===!0&&(n.polygonOffset=!0),this.polygonOffsetFactor!==0&&(n.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(n.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(n.linewidth=this.linewidth),this.dashSize!==void 0&&(n.dashSize=this.dashSize),this.gapSize!==void 0&&(n.gapSize=this.gapSize),this.scale!==void 0&&(n.scale=this.scale),this.dithering===!0&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),this.alphaHash===!0&&(n.alphaHash=!0),this.alphaToCoverage===!0&&(n.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(n.premultipliedAlpha=!0),this.forceSinglePass===!0&&(n.forceSinglePass=!0),this.wireframe===!0&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(n.flatShading=!0),this.visible===!1&&(n.visible=!1),this.toneMapped===!1&&(n.toneMapped=!1),this.fog===!1&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData);function s(r){let o=[];for(let a in r){let l=r[a];delete l.metadata,o.push(l)}return o}if(e){let r=s(t.textures),o=s(t.images);r.length>0&&(n.textures=r),o.length>0&&(n.images=o)}return n}clone(){return new this.constructor().copy(this)}copy(t){this.name=t.name,this.blending=t.blending,this.side=t.side,this.vertexColors=t.vertexColors,this.opacity=t.opacity,this.transparent=t.transparent,this.blendSrc=t.blendSrc,this.blendDst=t.blendDst,this.blendEquation=t.blendEquation,this.blendSrcAlpha=t.blendSrcAlpha,this.blendDstAlpha=t.blendDstAlpha,this.blendEquationAlpha=t.blendEquationAlpha,this.blendColor.copy(t.blendColor),this.blendAlpha=t.blendAlpha,this.depthFunc=t.depthFunc,this.depthTest=t.depthTest,this.depthWrite=t.depthWrite,this.stencilWriteMask=t.stencilWriteMask,this.stencilFunc=t.stencilFunc,this.stencilRef=t.stencilRef,this.stencilFuncMask=t.stencilFuncMask,this.stencilFail=t.stencilFail,this.stencilZFail=t.stencilZFail,this.stencilZPass=t.stencilZPass,this.stencilWrite=t.stencilWrite;let e=t.clippingPlanes,n=null;if(e!==null){let s=e.length;n=new Array(s);for(let r=0;r!==s;++r)n[r]=e[r].clone()}return this.clippingPlanes=n,this.clipIntersection=t.clipIntersection,this.clipShadows=t.clipShadows,this.shadowSide=t.shadowSide,this.colorWrite=t.colorWrite,this.precision=t.precision,this.polygonOffset=t.polygonOffset,this.polygonOffsetFactor=t.polygonOffsetFactor,this.polygonOffsetUnits=t.polygonOffsetUnits,this.dithering=t.dithering,this.alphaTest=t.alphaTest,this.alphaHash=t.alphaHash,this.alphaToCoverage=t.alphaToCoverage,this.premultipliedAlpha=t.premultipliedAlpha,this.forceSinglePass=t.forceSinglePass,this.visible=t.visible,this.toneMapped=t.toneMapped,this.userData=JSON.parse(JSON.stringify(t.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(t){t===!0&&this.version++}},en=class extends Zn{constructor(t){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Gt(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new tn,this.combine=Vl,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapRotation.copy(t.envMapRotation),this.combine=t.combine,this.reflectivity=t.reflectivity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.fog=t.fog,this}};var be=new A,$r=new ht,uf=0,Fe=class{constructor(t,e,n=!1){if(Array.isArray(t))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:uf++}),this.name="",this.array=t,this.itemSize=e,this.count=t!==void 0?t.length/e:0,this.normalized=n,this.usage=Cl,this.updateRanges=[],this.gpuType=Ln,this.version=0}onUploadCallback(){}set needsUpdate(t){t===!0&&this.version++}setUsage(t){return this.usage=t,this}addUpdateRange(t,e){this.updateRanges.push({start:t,count:e})}clearUpdateRanges(){this.updateRanges.length=0}copy(t){return this.name=t.name,this.array=new t.array.constructor(t.array),this.itemSize=t.itemSize,this.count=t.count,this.normalized=t.normalized,this.usage=t.usage,this.gpuType=t.gpuType,this}copyAt(t,e,n){t*=this.itemSize,n*=e.itemSize;for(let s=0,r=this.itemSize;se.count&&console.warn("THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),e.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new hi);let t=this.attributes.position,e=this.morphAttributes.position;if(t&&t.isGLBufferAttribute){console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new A(-1/0,-1/0,-1/0),new A(1/0,1/0,1/0));return}if(t!==void 0){if(this.boundingBox.setFromBufferAttribute(t),e)for(let n=0,s=e.length;n0&&(t.userData=this.userData),this.parameters!==void 0){let l=this.parameters;for(let c in l)l[c]!==void 0&&(t[c]=l[c]);return t}t.data={attributes:{}};let e=this.index;e!==null&&(t.data.index={type:e.array.constructor.name,array:Array.prototype.slice.call(e.array)});let n=this.attributes;for(let l in n){let c=n[l];t.data.attributes[l]=c.toJSON(t.data)}let s={},r=!1;for(let l in this.morphAttributes){let c=this.morphAttributes[l],h=[];for(let u=0,d=c.length;u0&&(s[l]=h,r=!0)}r&&(t.data.morphAttributes=s,t.data.morphTargetsRelative=this.morphTargetsRelative);let o=this.groups;o.length>0&&(t.data.groups=JSON.parse(JSON.stringify(o)));let a=this.boundingSphere;return a!==null&&(t.data.boundingSphere=a.toJSON()),t}clone(){return new this.constructor().copy(this)}copy(t){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;let e={};this.name=t.name;let n=t.index;n!==null&&this.setIndex(n.clone());let s=t.attributes;for(let c in s){let h=s[c];this.setAttribute(c,h.clone(e))}let r=t.morphAttributes;for(let c in r){let h=[],u=r[c];for(let d=0,p=u.length;d0){let s=e[n[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,o=s.length;r(t.far-t.near)**2))&&(uh.copy(r).invert(),Ti.copy(t.ray).applyMatrix4(uh),!(n.boundingBox!==null&&Ti.intersectsBox(n.boundingBox)===!1)&&this._computeIntersections(t,e,Ti)))}_computeIntersections(t,e,n){let s,r=this.geometry,o=this.material,a=r.index,l=r.attributes.position,c=r.attributes.uv,h=r.attributes.uv1,u=r.attributes.normal,d=r.groups,p=r.drawRange;if(a!==null)if(Array.isArray(o))for(let g=0,_=d.length;g<_;g++){let m=d[g],f=o[m.materialIndex],w=Math.max(m.start,p.start),M=Math.min(a.count,Math.min(m.start+m.count,p.start+p.count));for(let x=w,R=M;xe.far?null:{distance:c,point:no.clone(),object:i}}function io(i,t,e,n,s,r,o,a,l,c){i.getVertexPosition(a,jr),i.getVertexPosition(l,Qr),i.getVertexPosition(c,to);let h=ff(i,t,e,n,jr,Qr,to,fh);if(h){let u=new A;ai.getBarycoord(fh,jr,Qr,to,u),s&&(h.uv=ai.getInterpolatedAttribute(s,a,l,c,u,new ht)),r&&(h.uv1=ai.getInterpolatedAttribute(r,a,l,c,u,new ht)),o&&(h.normal=ai.getInterpolatedAttribute(o,a,l,c,u,new A),h.normal.dot(n.direction)>0&&h.normal.multiplyScalar(-1));let d={a,b:l,c,normal:new A,materialIndex:0};ai.getNormal(jr,Qr,to,d.normal),h.face=d,h.barycoord=u}return h}var pe=class i extends ue{constructor(t=1,e=1,n=1,s=1,r=1,o=1){super(),this.type="BoxGeometry",this.parameters={width:t,height:e,depth:n,widthSegments:s,heightSegments:r,depthSegments:o};let a=this;s=Math.floor(s),r=Math.floor(r),o=Math.floor(o);let l=[],c=[],h=[],u=[],d=0,p=0;g("z","y","x",-1,-1,n,e,t,o,r,0),g("z","y","x",1,-1,n,e,-t,o,r,1),g("x","z","y",1,1,t,n,e,s,o,2),g("x","z","y",1,-1,t,n,-e,s,o,3),g("x","y","z",1,-1,t,e,n,s,r,4),g("x","y","z",-1,-1,t,e,-n,s,r,5),this.setIndex(l),this.setAttribute("position",new Yt(c,3)),this.setAttribute("normal",new Yt(h,3)),this.setAttribute("uv",new Yt(u,2));function g(_,m,f,w,M,x,R,T,P,D,S){let v=x/P,I=R/D,F=x/2,z=R/2,k=T/2,V=P+1,G=D+1,tt=0,W=0,B=new A;for(let Z=0;Z0?1:-1,h.push(B.x,B.y,B.z),u.push(ut/P),u.push(1-Z/D),tt+=1}}for(let Z=0;Z0&&(e.defines=this.defines),e.vertexShader=this.vertexShader,e.fragmentShader=this.fragmentShader,e.lights=this.lights,e.clipping=this.clipping;let n={};for(let s in this.extensions)this.extensions[s]===!0&&(n[s]=!0);return Object.keys(n).length>0&&(e.extensions=n),e}},Qs=class extends Se{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new oe,this.projectionMatrix=new oe,this.projectionMatrixInverse=new oe,this.coordinateSystem=yn,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(t,e){return super.copy(t,e),this.matrixWorldInverse.copy(t.matrixWorldInverse),this.projectionMatrix.copy(t.projectionMatrix),this.projectionMatrixInverse.copy(t.projectionMatrixInverse),this.coordinateSystem=t.coordinateSystem,this}getWorldDirection(t){return super.getWorldDirection(t).negate()}updateMatrixWorld(t){super.updateMatrixWorld(t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(t,e){super.updateWorldMatrix(t,e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}},oi=new A,ph=new ht,mh=new ht,Ne=class extends Qs{constructor(t=50,e=1,n=.1,s=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=t,this.zoom=1,this.near=n,this.far=s,this.focus=10,this.aspect=e,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(t,e){return super.copy(t,e),this.fov=t.fov,this.zoom=t.zoom,this.near=t.near,this.far=t.far,this.focus=t.focus,this.aspect=t.aspect,this.view=t.view===null?null:Object.assign({},t.view),this.filmGauge=t.filmGauge,this.filmOffset=t.filmOffset,this}setFocalLength(t){let e=.5*this.getFilmHeight()/t;this.fov=ds*2*Math.atan(e),this.updateProjectionMatrix()}getFocalLength(){let t=Math.tan(Vs*.5*this.fov);return .5*this.getFilmHeight()/t}getEffectiveFOV(){return ds*2*Math.atan(Math.tan(Vs*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(t,e,n){oi.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),e.set(oi.x,oi.y).multiplyScalar(-t/oi.z),oi.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(oi.x,oi.y).multiplyScalar(-t/oi.z)}getViewSize(t,e){return this.getViewBounds(t,ph,mh),e.subVectors(mh,ph)}setViewOffset(t,e,n,s,r,o){this.aspect=t/e,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=t,this.view.fullHeight=e,this.view.offsetX=n,this.view.offsetY=s,this.view.width=r,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let t=this.near,e=t*Math.tan(Vs*.5*this.fov)/this.zoom,n=2*e,s=this.aspect*n,r=-.5*s,o=this.view;if(this.view!==null&&this.view.enabled){let l=o.fullWidth,c=o.fullHeight;r+=o.offsetX*s/l,e-=o.offsetY*n/c,s*=o.width/l,n*=o.height/c}let a=this.filmOffset;a!==0&&(r+=t*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+s,e,e-n,t,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(t){let e=super.toJSON(t);return e.object.fov=this.fov,e.object.zoom=this.zoom,e.object.near=this.near,e.object.far=this.far,e.object.focus=this.focus,e.object.aspect=this.aspect,this.view!==null&&(e.object.view=Object.assign({},this.view)),e.object.filmGauge=this.filmGauge,e.object.filmOffset=this.filmOffset,e}},os=-90,as=1,vo=class extends Se{constructor(t,e,n){super(),this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;let s=new Ne(os,as,t,e);s.layers=this.layers,this.add(s);let r=new Ne(os,as,t,e);r.layers=this.layers,this.add(r);let o=new Ne(os,as,t,e);o.layers=this.layers,this.add(o);let a=new Ne(os,as,t,e);a.layers=this.layers,this.add(a);let l=new Ne(os,as,t,e);l.layers=this.layers,this.add(l);let c=new Ne(os,as,t,e);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){let t=this.coordinateSystem,e=this.children.concat(),[n,s,r,o,a,l]=e;for(let c of e)this.remove(c);if(t===yn)n.up.set(0,1,0),n.lookAt(1,0,0),s.up.set(0,1,0),s.lookAt(-1,0,0),r.up.set(0,0,-1),r.lookAt(0,1,0),o.up.set(0,0,1),o.lookAt(0,-1,0),a.up.set(0,1,0),a.lookAt(0,0,1),l.up.set(0,1,0),l.lookAt(0,0,-1);else if(t===Zs)n.up.set(0,-1,0),n.lookAt(-1,0,0),s.up.set(0,-1,0),s.lookAt(1,0,0),r.up.set(0,0,1),r.lookAt(0,1,0),o.up.set(0,0,-1),o.lookAt(0,-1,0),a.up.set(0,-1,0),a.lookAt(0,0,1),l.up.set(0,-1,0),l.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+t);for(let c of e)this.add(c),c.updateMatrixWorld()}update(t,e){this.parent===null&&this.updateMatrixWorld();let{renderTarget:n,activeMipmapLevel:s}=this;this.coordinateSystem!==t.coordinateSystem&&(this.coordinateSystem=t.coordinateSystem,this.updateCoordinateSystem());let[r,o,a,l,c,h]=this.children,u=t.getRenderTarget(),d=t.getActiveCubeFace(),p=t.getActiveMipmapLevel(),g=t.xr.enabled;t.xr.enabled=!1;let _=n.texture.generateMipmaps;n.texture.generateMipmaps=!1,t.setRenderTarget(n,0,s),t.render(e,r),t.setRenderTarget(n,1,s),t.render(e,o),t.setRenderTarget(n,2,s),t.render(e,a),t.setRenderTarget(n,3,s),t.render(e,l),t.setRenderTarget(n,4,s),t.render(e,c),n.texture.generateMipmaps=_,t.setRenderTarget(n,5,s),t.render(e,h),t.setRenderTarget(u,d,p),t.xr.enabled=g,n.texture.needsPMREMUpdate=!0}},tr=class extends Ye{constructor(t=[],e=Fi,n,s,r,o,a,l,c,h){super(t,e,n,s,r,o,a,l,c,h),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(t){this.image=t}},Mo=class extends Cn{constructor(t=1,e={}){super(t,t,e),this.isWebGLCubeRenderTarget=!0;let n={width:t,height:t,depth:1},s=[n,n,n,n,n,n];this.texture=new tr(s),this._setTextureOptions(e),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(t,e){this.texture.type=e.type,this.texture.colorSpace=e.colorSpace,this.texture.generateMipmaps=e.generateMipmaps,this.texture.minFilter=e.minFilter,this.texture.magFilter=e.magFilter;let n={uniforms:{tEquirect:{value:null}},vertexShader:` + + varying vec3 vWorldDirection; + + vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); + + } + + void main() { + + vWorldDirection = transformDirection( position, modelMatrix ); + + #include + #include + + } + `,fragmentShader:` + + uniform sampler2D tEquirect; + + varying vec3 vWorldDirection; + + #include + + void main() { + + vec3 direction = normalize( vWorldDirection ); + + vec2 sampleUV = equirectUv( direction ); + + gl_FragColor = texture2D( tEquirect, sampleUV ); + + } + `},s=new pe(5,5,5),r=new Sn({name:"CubemapFromEquirect",uniforms:zi(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:Ve,blending:Kn});r.uniforms.tEquirect.value=e;let o=new _t(s,r),a=e.minFilter;return e.minFilter===xi&&(e.minFilter=Mn),new vo(1,10,this).update(t,o),e.minFilter=a,o.geometry.dispose(),o.material.dispose(),this}clear(t,e=!0,n=!0,s=!0){let r=t.getRenderTarget();for(let o=0;o<6;o++)t.setRenderTarget(this,o),t.clear(e,n,s);t.setRenderTarget(r)}},vn=class extends Se{constructor(){super(),this.isGroup=!0,this.type="Group"}},_f={type:"move"},gs=class{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new vn,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new vn,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new A,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new A),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new vn,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new A,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new A),this._grip}dispatchEvent(t){return this._targetRay!==null&&this._targetRay.dispatchEvent(t),this._grip!==null&&this._grip.dispatchEvent(t),this._hand!==null&&this._hand.dispatchEvent(t),this}connect(t){if(t&&t.hand){let e=this._hand;if(e)for(let n of t.hand.values())this._getHandJoint(e,n)}return this.dispatchEvent({type:"connected",data:t}),this}disconnect(t){return this.dispatchEvent({type:"disconnected",data:t}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(t,e,n){let s=null,r=null,o=null,a=this._targetRay,l=this._grip,c=this._hand;if(t&&e.session.visibilityState!=="visible-blurred"){if(c&&t.hand){o=!0;for(let _ of t.hand.values()){let m=e.getJointPose(_,n),f=this._getHandJoint(c,_);m!==null&&(f.matrix.fromArray(m.transform.matrix),f.matrix.decompose(f.position,f.rotation,f.scale),f.matrixWorldNeedsUpdate=!0,f.jointRadius=m.radius),f.visible=m!==null}let h=c.joints["index-finger-tip"],u=c.joints["thumb-tip"],d=h.position.distanceTo(u.position),p=.02,g=.005;c.inputState.pinching&&d>p+g?(c.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:t.handedness,target:this})):!c.inputState.pinching&&d<=p-g&&(c.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:t.handedness,target:this}))}else l!==null&&t.gripSpace&&(r=e.getPose(t.gripSpace,n),r!==null&&(l.matrix.fromArray(r.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),l.matrixWorldNeedsUpdate=!0,r.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(r.linearVelocity)):l.hasLinearVelocity=!1,r.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(r.angularVelocity)):l.hasAngularVelocity=!1));a!==null&&(s=e.getPose(t.targetRaySpace,n),s===null&&r!==null&&(s=r),s!==null&&(a.matrix.fromArray(s.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,s.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(s.linearVelocity)):a.hasLinearVelocity=!1,s.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(s.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(_f)))}return a!==null&&(a.visible=s!==null),l!==null&&(l.visible=r!==null),c!==null&&(c.visible=o!==null),this}_getHandJoint(t,e){if(t.joints[e.jointName]===void 0){let n=new vn;n.matrixAutoUpdate=!1,n.visible=!1,t.joints[e.jointName]=n,t.add(n)}return t.joints[e.jointName]}};var er=class i{constructor(t,e=1,n=1e3){this.isFog=!0,this.name="",this.color=new Gt(t),this.near=e,this.far=n}clone(){return new i(this.color,this.near,this.far)}toJSON(){return{type:"Fog",name:this.name,color:this.color.getHex(),near:this.near,far:this.far}}},nr=class extends Se{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new tn,this.environmentIntensity=1,this.environmentRotation=new tn,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(t,e){return super.copy(t,e),t.background!==null&&(this.background=t.background.clone()),t.environment!==null&&(this.environment=t.environment.clone()),t.fog!==null&&(this.fog=t.fog.clone()),this.backgroundBlurriness=t.backgroundBlurriness,this.backgroundIntensity=t.backgroundIntensity,this.backgroundRotation.copy(t.backgroundRotation),this.environmentIntensity=t.environmentIntensity,this.environmentRotation.copy(t.environmentRotation),t.overrideMaterial!==null&&(this.overrideMaterial=t.overrideMaterial.clone()),this.matrixAutoUpdate=t.matrixAutoUpdate,this}toJSON(t){let e=super.toJSON(t);return this.fog!==null&&(e.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(e.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(e.object.backgroundIntensity=this.backgroundIntensity),e.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(e.object.environmentIntensity=this.environmentIntensity),e.object.environmentRotation=this.environmentRotation.toArray(),e}};var yl=new A,xf=new A,yf=new Wt,hn=class{constructor(t=new A(1,0,0),e=0){this.isPlane=!0,this.normal=t,this.constant=e}set(t,e){return this.normal.copy(t),this.constant=e,this}setComponents(t,e,n,s){return this.normal.set(t,e,n),this.constant=s,this}setFromNormalAndCoplanarPoint(t,e){return this.normal.copy(t),this.constant=-e.dot(this.normal),this}setFromCoplanarPoints(t,e,n){let s=yl.subVectors(n,e).cross(xf.subVectors(t,e)).normalize();return this.setFromNormalAndCoplanarPoint(s,t),this}copy(t){return this.normal.copy(t.normal),this.constant=t.constant,this}normalize(){let t=1/this.normal.length();return this.normal.multiplyScalar(t),this.constant*=t,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(t){return this.normal.dot(t)+this.constant}distanceToSphere(t){return this.distanceToPoint(t.center)-t.radius}projectPoint(t,e){return e.copy(t).addScaledVector(this.normal,-this.distanceToPoint(t))}intersectLine(t,e){let n=t.delta(yl),s=this.normal.dot(n);if(s===0)return this.distanceToPoint(t.start)===0?e.copy(t.start):null;let r=-(t.start.dot(this.normal)+this.constant)/s;return r<0||r>1?null:e.copy(t.start).addScaledVector(n,r)}intersectsLine(t){let e=this.distanceToPoint(t.start),n=this.distanceToPoint(t.end);return e<0&&n>0||n<0&&e>0}intersectsBox(t){return t.intersectsPlane(this)}intersectsSphere(t){return t.intersectsPlane(this)}coplanarPoint(t){return t.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(t,e){let n=e||yf.getNormalMatrix(t),s=this.coplanarPoint(yl).applyMatrix4(t),r=this.normal.applyMatrix3(n).normalize();return this.constant=-s.dot(r),this}translate(t){return this.constant-=t.dot(this.normal),this}equals(t){return t.normal.equals(this.normal)&&t.constant===this.constant}clone(){return new this.constructor().copy(this)}},Ai=new Di,vf=new ht(.5,.5),so=new A,_s=class{constructor(t=new hn,e=new hn,n=new hn,s=new hn,r=new hn,o=new hn){this.planes=[t,e,n,s,r,o]}set(t,e,n,s,r,o){let a=this.planes;return a[0].copy(t),a[1].copy(e),a[2].copy(n),a[3].copy(s),a[4].copy(r),a[5].copy(o),this}copy(t){let e=this.planes;for(let n=0;n<6;n++)e[n].copy(t.planes[n]);return this}setFromProjectionMatrix(t,e=yn,n=!1){let s=this.planes,r=t.elements,o=r[0],a=r[1],l=r[2],c=r[3],h=r[4],u=r[5],d=r[6],p=r[7],g=r[8],_=r[9],m=r[10],f=r[11],w=r[12],M=r[13],x=r[14],R=r[15];if(s[0].setComponents(c-o,p-h,f-g,R-w).normalize(),s[1].setComponents(c+o,p+h,f+g,R+w).normalize(),s[2].setComponents(c+a,p+u,f+_,R+M).normalize(),s[3].setComponents(c-a,p-u,f-_,R-M).normalize(),n)s[4].setComponents(l,d,m,x).normalize(),s[5].setComponents(c-l,p-d,f-m,R-x).normalize();else if(s[4].setComponents(c-l,p-d,f-m,R-x).normalize(),e===yn)s[5].setComponents(c+l,p+d,f+m,R+x).normalize();else if(e===Zs)s[5].setComponents(l,d,m,x).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+e);return this}intersectsObject(t){if(t.boundingSphere!==void 0)t.boundingSphere===null&&t.computeBoundingSphere(),Ai.copy(t.boundingSphere).applyMatrix4(t.matrixWorld);else{let e=t.geometry;e.boundingSphere===null&&e.computeBoundingSphere(),Ai.copy(e.boundingSphere).applyMatrix4(t.matrixWorld)}return this.intersectsSphere(Ai)}intersectsSprite(t){Ai.center.set(0,0,0);let e=vf.distanceTo(t.center);return Ai.radius=.7071067811865476+e,Ai.applyMatrix4(t.matrixWorld),this.intersectsSphere(Ai)}intersectsSphere(t){let e=this.planes,n=t.center,s=-t.radius;for(let r=0;r<6;r++)if(e[r].distanceToPoint(n)0?t.max.x:t.min.x,so.y=s.normal.y>0?t.max.y:t.min.y,so.z=s.normal.z>0?t.max.z:t.min.z,s.distanceToPoint(so)<0)return!1}return!0}containsPoint(t){let e=this.planes;for(let n=0;n<6;n++)if(e[n].distanceToPoint(t)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}};var Pn=class extends Zn{constructor(t){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new Gt(16777215),this.map=null,this.linewidth=1,this.linecap="round",this.linejoin="round",this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.linewidth=t.linewidth,this.linecap=t.linecap,this.linejoin=t.linejoin,this.fog=t.fog,this}},So=new A,bo=new A,gh=new oe,ks=new ui,ro=new Di,vl=new A,_h=new A,Oe=class extends Se{constructor(t=new ue,e=new Pn){super(),this.isLine=!0,this.type="Line",this.geometry=t,this.material=e,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(t,e){return super.copy(t,e),this.material=Array.isArray(t.material)?t.material.slice():t.material,this.geometry=t.geometry,this}computeLineDistances(){let t=this.geometry;if(t.index===null){let e=t.attributes.position,n=[0];for(let s=1,r=e.count;s0){let s=e[n[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,o=s.length;rn)return;vl.applyMatrix4(i.matrixWorld);let c=t.ray.origin.distanceTo(vl);if(!(ct.far))return{distance:c,point:_h.clone().applyMatrix4(i.matrixWorld),index:o,face:null,faceIndex:null,barycoord:null,object:i}}var xh=new A,yh=new A,ir=class extends Oe{constructor(t,e){super(t,e),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){let t=this.geometry;if(t.index===null){let e=t.attributes.position,n=[];for(let s=0,r=e.count;s0){let S=(w-1)*_;for(let v=0;v0&&M(!0),e>0&&M(!1)),this.setIndex(h),this.setAttribute("position",new Yt(u,3)),this.setAttribute("normal",new Yt(d,3)),this.setAttribute("uv",new Yt(p,2));function w(){let x=new A,R=new A,T=0,P=(e-t)/n;for(let D=0;D<=r;D++){let S=[],v=D/r,I=v*(e-t)+t;for(let F=0;F<=s;F++){let z=F/s,k=z*l+a,V=Math.sin(k),G=Math.cos(k);R.x=I*V,R.y=-v*n+m,R.z=I*G,u.push(R.x,R.y,R.z),x.set(V,P,G).normalize(),d.push(x.x,x.y,x.z),p.push(z,1-v),S.push(g++)}_.push(S)}for(let D=0;D0||S!==0)&&(h.push(v,I,z),T+=3),(e>0||S!==r-1)&&(h.push(I,F,z),T+=3)}c.addGroup(f,T,0),f+=T}function M(x){let R=g,T=new ht,P=new A,D=0,S=x===!0?t:e,v=x===!0?1:-1;for(let F=1;F<=s;F++)u.push(0,m*v,0),d.push(0,v,0),p.push(.5,.5),g++;let I=g;for(let F=0;F<=s;F++){let k=F/s*l+a,V=Math.cos(k),G=Math.sin(k);P.x=S*G,P.y=m*v,P.z=S*V,u.push(P.x,P.y,P.z),d.push(0,v,0),T.x=V*.5+.5,T.y=G*.5*v+.5,p.push(T.x,T.y),g++}for(let F=0;F.9&&P<.1&&(M<.2&&(o[w+0]+=1),x<.2&&(o[w+2]+=1),R<.2&&(o[w+4]+=1))}}function d(w){r.push(w.x,w.y,w.z)}function p(w,M){let x=w*3;M.x=t[x+0],M.y=t[x+1],M.z=t[x+2]}function g(){let w=new A,M=new A,x=new A,R=new A,T=new ht,P=new ht,D=new ht;for(let S=0,v=0;S0)l=s-1;else{l=s;break}if(s=l,n[s]===o)return s/(r-1);let h=n[s],d=n[s+1]-h,p=(o-h)/d;return(s+p)/(r-1)}getTangent(t,e){let s=t-1e-4,r=t+1e-4;s<0&&(s=0),r>1&&(r=1);let o=this.getPoint(s),a=this.getPoint(r),l=e||(o.isVector2?new ht:new A);return l.copy(a).sub(o).normalize(),l}getTangentAt(t,e){let n=this.getUtoTmapping(t);return this.getTangent(n,e)}computeFrenetFrames(t,e=!1){let n=new A,s=[],r=[],o=[],a=new A,l=new oe;for(let p=0;p<=t;p++){let g=p/t;s[p]=this.getTangentAt(g,new A)}r[0]=new A,o[0]=new A;let c=Number.MAX_VALUE,h=Math.abs(s[0].x),u=Math.abs(s[0].y),d=Math.abs(s[0].z);h<=c&&(c=h,n.set(1,0,0)),u<=c&&(c=u,n.set(0,1,0)),d<=c&&n.set(0,0,1),a.crossVectors(s[0],n).normalize(),r[0].crossVectors(s[0],a),o[0].crossVectors(s[0],r[0]);for(let p=1;p<=t;p++){if(r[p]=r[p-1].clone(),o[p]=o[p-1].clone(),a.crossVectors(s[p-1],s[p]),a.length()>Number.EPSILON){a.normalize();let g=Math.acos(Zt(s[p-1].dot(s[p]),-1,1));r[p].applyMatrix4(l.makeRotationAxis(a,g))}o[p].crossVectors(s[p],r[p])}if(e===!0){let p=Math.acos(Zt(r[0].dot(r[t]),-1,1));p/=t,s[0].dot(a.crossVectors(r[0],r[t]))>0&&(p=-p);for(let g=1;g<=t;g++)r[g].applyMatrix4(l.makeRotationAxis(s[g],p*g)),o[g].crossVectors(s[g],r[g])}return{tangents:s,normals:r,binormals:o}}clone(){return new this.constructor().copy(this)}copy(t){return this.arcLengthDivisions=t.arcLengthDivisions,this}toJSON(){let t={metadata:{version:4.7,type:"Curve",generator:"Curve.toJSON"}};return t.arcLengthDivisions=this.arcLengthDivisions,t.type=this.type,t}fromJSON(t){return this.arcLengthDivisions=t.arcLengthDivisions,this}},ys=class extends nn{constructor(t=0,e=0,n=1,s=1,r=0,o=Math.PI*2,a=!1,l=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=t,this.aY=e,this.xRadius=n,this.yRadius=s,this.aStartAngle=r,this.aEndAngle=o,this.aClockwise=a,this.aRotation=l}getPoint(t,e=new ht){let n=e,s=Math.PI*2,r=this.aEndAngle-this.aStartAngle,o=Math.abs(r)s;)r-=s;r0?0:(Math.floor(Math.abs(a)/r)+1)*r:l===0&&a===r-1&&(a=r-2,l=1);let c,h;this.closed||a>0?c=s[(a-1)%r]:(ao.subVectors(s[0],s[1]).add(s[0]),c=ao);let u=s[a%r],d=s[(a+1)%r];if(this.closed||a+2s.length-2?s.length-1:o+1],u=s[o>s.length-3?s.length-1:o+2];return n.set(vh(a,l.x,c.x,h.x,u.x),vh(a,l.y,c.y,h.y,u.y)),n}copy(t){super.copy(t),this.points=[];for(let e=0,n=t.points.length;e=n){let o=s[r]-n,a=this.curves[r],l=a.getLength(),c=l===0?0:1-o/l;return a.getPointAt(c,e)}r++}return null}getLength(){let t=this.getCurveLengths();return t[t.length-1]}updateArcLengths(){this.needsUpdate=!0,this.cacheLengths=null,this.getCurveLengths()}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;let t=[],e=0;for(let n=0,s=this.curves.length;n1&&!e[e.length-1].equals(e[0])&&e.push(e[0]),e}copy(t){super.copy(t),this.curves=[];for(let e=0,n=t.curves.length;e0){let u=c.getPoint(0);u.equals(this.currentPoint)||this.lineTo(u.x,u.y)}this.curves.push(c);let h=c.getPoint(1);return this.currentPoint.copy(h),this}copy(t){return super.copy(t),this.currentPoint.copy(t.currentPoint),this}toJSON(){let t=super.toJSON();return t.currentPoint=this.currentPoint.toArray(),t}fromJSON(t){return super.fromJSON(t),this.currentPoint.fromArray(t.currentPoint),this}},vs=class extends fr{constructor(t){super(t),this.uuid=Bi(),this.type="Shape",this.holes=[]}getPointsHoles(t){let e=[];for(let n=0,s=this.holes.length;n80*e){a=1/0,l=1/0;let h=-1/0,u=-1/0;for(let d=e;dh&&(h=p),g>u&&(u=g)}c=Math.max(h-a,u-l),c=c!==0?32767/c:0}return pr(r,o,e,a,l,c,0),o}function _u(i,t,e,n,s){let r;if(s===Wf(i,t,e,n)>0)for(let o=t;o=t;o-=n)r=Mh(o/n|0,i[o],i[o+1],r);return r&&Ms(r,r.next)&&(gr(r),r=r.next),r}function Li(i,t){if(!i)return i;t||(t=i);let e=i,n;do if(n=!1,!e.steiner&&(Ms(e,e.next)||xe(e.prev,e,e.next)===0)){if(gr(e),e=t=e.prev,e===e.next)break;n=!0}else e=e.next;while(n||e!==t);return t}function pr(i,t,e,n,s,r,o){if(!i)return;!o&&r&&Bf(i,n,s,r);let a=i;for(;i.prev!==i.next;){let l=i.prev,c=i.next;if(r?Pf(i,n,s,r):Cf(i)){t.push(l.i,i.i,c.i),gr(i),i=c.next,a=c.next;continue}if(i=c,i===a){o?o===1?(i=If(Li(i),t),pr(i,t,e,n,s,r,2)):o===2&&Df(i,t,e,n,s,r):pr(Li(i),t,e,n,s,r,1);break}}}function Cf(i){let t=i.prev,e=i,n=i.next;if(xe(t,e,n)>=0)return!1;let s=t.x,r=e.x,o=n.x,a=t.y,l=e.y,c=n.y,h=Math.min(s,r,o),u=Math.min(a,l,c),d=Math.max(s,r,o),p=Math.max(a,l,c),g=n.next;for(;g!==t;){if(g.x>=h&&g.x<=d&&g.y>=u&&g.y<=p&&Hs(s,a,r,l,o,c,g.x,g.y)&&xe(g.prev,g,g.next)>=0)return!1;g=g.next}return!0}function Pf(i,t,e,n){let s=i.prev,r=i,o=i.next;if(xe(s,r,o)>=0)return!1;let a=s.x,l=r.x,c=o.x,h=s.y,u=r.y,d=o.y,p=Math.min(a,l,c),g=Math.min(h,u,d),_=Math.max(a,l,c),m=Math.max(h,u,d),f=Pl(p,g,t,e,n),w=Pl(_,m,t,e,n),M=i.prevZ,x=i.nextZ;for(;M&&M.z>=f&&x&&x.z<=w;){if(M.x>=p&&M.x<=_&&M.y>=g&&M.y<=m&&M!==s&&M!==o&&Hs(a,h,l,u,c,d,M.x,M.y)&&xe(M.prev,M,M.next)>=0||(M=M.prevZ,x.x>=p&&x.x<=_&&x.y>=g&&x.y<=m&&x!==s&&x!==o&&Hs(a,h,l,u,c,d,x.x,x.y)&&xe(x.prev,x,x.next)>=0))return!1;x=x.nextZ}for(;M&&M.z>=f;){if(M.x>=p&&M.x<=_&&M.y>=g&&M.y<=m&&M!==s&&M!==o&&Hs(a,h,l,u,c,d,M.x,M.y)&&xe(M.prev,M,M.next)>=0)return!1;M=M.prevZ}for(;x&&x.z<=w;){if(x.x>=p&&x.x<=_&&x.y>=g&&x.y<=m&&x!==s&&x!==o&&Hs(a,h,l,u,c,d,x.x,x.y)&&xe(x.prev,x,x.next)>=0)return!1;x=x.nextZ}return!0}function If(i,t){let e=i;do{let n=e.prev,s=e.next.next;!Ms(n,s)&&yu(n,e,e.next,s)&&mr(n,s)&&mr(s,n)&&(t.push(n.i,e.i,s.i),gr(e),gr(e.next),e=i=s),e=e.next}while(e!==i);return Li(e)}function Df(i,t,e,n,s,r){let o=i;do{let a=o.next.next;for(;a!==o.prev;){if(o.i!==a.i&&Hf(o,a)){let l=vu(o,a);o=Li(o,o.next),l=Li(l,l.next),pr(o,t,e,n,s,r,0),pr(l,t,e,n,s,r,0);return}a=a.next}o=o.next}while(o!==i)}function Lf(i,t,e,n){let s=[];for(let r=0,o=t.length;r=e.next.y&&e.next.y!==e.y){let u=e.x+(s-e.y)*(e.next.x-e.x)/(e.next.y-e.y);if(u<=n&&u>r&&(r=u,o=e.x=e.x&&e.x>=l&&n!==e.x&&xu(so.x||e.x===o.x&&Of(o,e)))&&(o=e,h=u)}e=e.next}while(e!==a);return o}function Of(i,t){return xe(i.prev,i,t.prev)<0&&xe(t.next,i,i.next)<0}function Bf(i,t,e,n){let s=i;do s.z===0&&(s.z=Pl(s.x,s.y,t,e,n)),s.prevZ=s.prev,s.nextZ=s.next,s=s.next;while(s!==i);s.prevZ.nextZ=null,s.prevZ=null,zf(s)}function zf(i){let t,e=1;do{let n=i,s;i=null;let r=null;for(t=0;n;){t++;let o=n,a=0;for(let c=0;c0||l>0&&o;)a!==0&&(l===0||!o||n.z<=o.z)?(s=n,n=n.nextZ,a--):(s=o,o=o.nextZ,l--),r?r.nextZ=s:i=s,s.prevZ=r,r=s;n=o}r.nextZ=null,e*=2}while(t>1);return i}function Pl(i,t,e,n,s){return i=(i-e)*s|0,t=(t-n)*s|0,i=(i|i<<8)&16711935,i=(i|i<<4)&252645135,i=(i|i<<2)&858993459,i=(i|i<<1)&1431655765,t=(t|t<<8)&16711935,t=(t|t<<4)&252645135,t=(t|t<<2)&858993459,t=(t|t<<1)&1431655765,i|t<<1}function kf(i){let t=i,e=i;do(t.x=(i-o)*(r-a)&&(i-o)*(n-a)>=(e-o)*(t-a)&&(e-o)*(r-a)>=(s-o)*(n-a)}function Hs(i,t,e,n,s,r,o,a){return!(i===o&&t===a)&&xu(i,t,e,n,s,r,o,a)}function Hf(i,t){return i.next.i!==t.i&&i.prev.i!==t.i&&!Vf(i,t)&&(mr(i,t)&&mr(t,i)&&Gf(i,t)&&(xe(i.prev,i,t.prev)||xe(i,t.prev,t))||Ms(i,t)&&xe(i.prev,i,i.next)>0&&xe(t.prev,t,t.next)>0)}function xe(i,t,e){return(t.y-i.y)*(e.x-t.x)-(t.x-i.x)*(e.y-t.y)}function Ms(i,t){return i.x===t.x&&i.y===t.y}function yu(i,t,e,n){let s=co(xe(i,t,e)),r=co(xe(i,t,n)),o=co(xe(e,n,i)),a=co(xe(e,n,t));return!!(s!==r&&o!==a||s===0&&lo(i,e,t)||r===0&&lo(i,n,t)||o===0&&lo(e,i,n)||a===0&&lo(e,t,n))}function lo(i,t,e){return t.x<=Math.max(i.x,e.x)&&t.x>=Math.min(i.x,e.x)&&t.y<=Math.max(i.y,e.y)&&t.y>=Math.min(i.y,e.y)}function co(i){return i>0?1:i<0?-1:0}function Vf(i,t){let e=i;do{if(e.i!==i.i&&e.next.i!==i.i&&e.i!==t.i&&e.next.i!==t.i&&yu(e,e.next,i,t))return!0;e=e.next}while(e!==i);return!1}function mr(i,t){return xe(i.prev,i,i.next)<0?xe(i,t,i.next)>=0&&xe(i,i.prev,t)>=0:xe(i,t,i.prev)<0||xe(i,i.next,t)<0}function Gf(i,t){let e=i,n=!1,s=(i.x+t.x)/2,r=(i.y+t.y)/2;do e.y>r!=e.next.y>r&&e.next.y!==e.y&&s<(e.next.x-e.x)*(r-e.y)/(e.next.y-e.y)+e.x&&(n=!n),e=e.next;while(e!==i);return n}function vu(i,t){let e=Il(i.i,i.x,i.y),n=Il(t.i,t.x,t.y),s=i.next,r=t.prev;return i.next=t,t.prev=i,e.next=s,s.prev=e,n.next=e,e.prev=n,r.next=n,n.prev=r,n}function Mh(i,t,e,n){let s=Il(i,t,e);return n?(s.next=n.next,s.prev=n,n.next.prev=s,n.next=s):(s.prev=s,s.next=s),s}function gr(i){i.next.prev=i.prev,i.prev.next=i.next,i.prevZ&&(i.prevZ.nextZ=i.nextZ),i.nextZ&&(i.nextZ.prevZ=i.prevZ)}function Il(i,t,e){return{i,x:t,y:e,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function Wf(i,t,e,n){let s=0;for(let r=t,o=e-n;r2&&i[t-1].equals(i[0])&&i.pop()}function bh(i,t){for(let e=0;eNumber.EPSILON){let q=Math.sqrt(y),it=Math.sqrt(zt*zt+E*E),Y=et.x-Ht/q,Pt=et.y+mt/q,ft=j.x-E/it,At=j.y+zt/it,Rt=((ft-Y)*E-(At-Pt)*zt)/(mt*E-Ht*zt);$=Y+mt*Rt-st.x,pt=Pt+Ht*Rt-st.y;let at=$*$+pt*pt;if(at<=2)return new ht($,pt);ot=Math.sqrt(at/2)}else{let q=!1;mt>Number.EPSILON?zt>Number.EPSILON&&(q=!0):mt<-Number.EPSILON?zt<-Number.EPSILON&&(q=!0):Math.sign(Ht)===Math.sign(E)&&(q=!0),q?($=-Ht,pt=mt,ot=Math.sqrt(y)):($=mt,pt=Ht,ot=Math.sqrt(y/2))}return new ht($/ot,pt/ot)}let B=[];for(let st=0,et=V.length,j=et-1,$=st+1;st=0;st--){let et=st/m,j=p*Math.cos(et*Math.PI/2),$=g*Math.sin(et*Math.PI/2)+_;for(let pt=0,ot=V.length;pt=0;){let $=j,pt=j-1;pt<0&&(pt=st.length-1);for(let ot=0,mt=h+m*2;ot0)&&p.push(M,x,T),(f!==n-1||l=r)){let a=e[1];t=r)break t}o=n,n=0;break e}break n}for(;n>>1;te;)--o;if(++o,r!==0||o!==s){r>=o&&(o=Math.max(o,1),r=o-1);let a=this.getValueSize();this.times=n.slice(r,o),this.values=this.values.slice(r*a,o*a)}return this}validate(){let t=!0,e=this.getValueSize();e-Math.floor(e)!==0&&(console.error("THREE.KeyframeTrack: Invalid value size in track.",this),t=!1);let n=this.times,s=this.values,r=n.length;r===0&&(console.error("THREE.KeyframeTrack: Track is empty.",this),t=!1);let o=null;for(let a=0;a!==r;a++){let l=n[a];if(typeof l=="number"&&isNaN(l)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,a,l),t=!1;break}if(o!==null&&o>l){console.error("THREE.KeyframeTrack: Out of order keys.",this,a,l,o),t=!1;break}o=l}if(s!==void 0&&Yf(s))for(let a=0,l=s.length;a!==l;++a){let c=s[a];if(isNaN(c)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,a,c),t=!1;break}}return t}optimize(){let t=this.times.slice(),e=this.values.slice(),n=this.getValueSize(),s=this.getInterpolation()===uo,r=t.length-1,o=1;for(let a=1;a0){t[o]=t[r];for(let a=r*n,l=o*n,c=0;c!==n;++c)e[l+c]=e[a+c];++o}return o!==t.length?(this.times=t.slice(0,o),this.values=e.slice(0,o*n)):(this.times=t,this.values=e),this}clone(){let t=this.times.slice(),e=this.values.slice(),n=this.constructor,s=new n(this.name,t,e);return s.createInterpolant=this.createInterpolant,s}};sn.prototype.ValueTypeName="";sn.prototype.TimeBufferType=Float32Array;sn.prototype.ValueBufferType=Float32Array;sn.prototype.DefaultInterpolation=go;var pi=class extends sn{constructor(t,e,n){super(t,e,n)}};pi.prototype.ValueTypeName="bool";pi.prototype.ValueBufferType=Array;pi.prototype.DefaultInterpolation=qs;pi.prototype.InterpolantFactoryMethodLinear=void 0;pi.prototype.InterpolantFactoryMethodSmooth=void 0;var No=class extends sn{constructor(t,e,n,s){super(t,e,n,s)}};No.prototype.ValueTypeName="color";var Fo=class extends sn{constructor(t,e,n,s){super(t,e,n,s)}};Fo.prototype.ValueTypeName="number";var Oo=class extends Ui{constructor(t,e,n,s){super(t,e,n,s)}interpolate_(t,e,n,s){let r=this.resultBuffer,o=this.sampleValues,a=this.valueSize,l=(n-e)/(s-e),c=t*a;for(let h=c+a;c!==h;c+=4)ye.slerpFlat(r,0,o,c-a,o,c,l);return r}},yr=class extends sn{constructor(t,e,n,s){super(t,e,n,s)}InterpolantFactoryMethodLinear(t){return new Oo(this.times,this.values,this.getValueSize(),t)}};yr.prototype.ValueTypeName="quaternion";yr.prototype.InterpolantFactoryMethodSmooth=void 0;var mi=class extends sn{constructor(t,e,n){super(t,e,n)}};mi.prototype.ValueTypeName="string";mi.prototype.ValueBufferType=Array;mi.prototype.DefaultInterpolation=qs;mi.prototype.InterpolantFactoryMethodLinear=void 0;mi.prototype.InterpolantFactoryMethodSmooth=void 0;var Bo=class extends sn{constructor(t,e,n,s){super(t,e,n,s)}};Bo.prototype.ValueTypeName="vector";var zo=class{constructor(t,e,n){let s=this,r=!1,o=0,a=0,l,c=[];this.onStart=void 0,this.onLoad=t,this.onProgress=e,this.onError=n,this.abortController=new AbortController,this.itemStart=function(h){a++,r===!1&&s.onStart!==void 0&&s.onStart(h,o,a),r=!0},this.itemEnd=function(h){o++,s.onProgress!==void 0&&s.onProgress(h,o,a),o===a&&(r=!1,s.onLoad!==void 0&&s.onLoad())},this.itemError=function(h){s.onError!==void 0&&s.onError(h)},this.resolveURL=function(h){return l?l(h):h},this.setURLModifier=function(h){return l=h,this},this.addHandler=function(h,u){return c.push(h,u),this},this.removeHandler=function(h){let u=c.indexOf(h);return u!==-1&&c.splice(u,2),this},this.getHandler=function(h){for(let u=0,d=c.length;up.start-g.start);let d=0;for(let p=1;p 0 + vec4 plane; + #ifdef ALPHA_TO_COVERAGE + float distanceToPlane, distanceGradient; + float clipOpacity = 1.0; + #pragma unroll_loop_start + for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; + distanceGradient = fwidth( distanceToPlane ) / 2.0; + clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); + if ( clipOpacity == 0.0 ) discard; + } + #pragma unroll_loop_end + #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES + float unionClipOpacity = 1.0; + #pragma unroll_loop_start + for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; + distanceGradient = fwidth( distanceToPlane ) / 2.0; + unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); + } + #pragma unroll_loop_end + clipOpacity *= 1.0 - unionClipOpacity; + #endif + diffuseColor.a *= clipOpacity; + if ( diffuseColor.a == 0.0 ) discard; + #else + #pragma unroll_loop_start + for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard; + } + #pragma unroll_loop_end + #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES + bool clipped = true; + #pragma unroll_loop_start + for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped; + } + #pragma unroll_loop_end + if ( clipped ) discard; + #endif + #endif +#endif`,Mp=`#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; + uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; +#endif`,Sp=`#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; +#endif`,bp=`#if NUM_CLIPPING_PLANES > 0 + vClipPosition = - mvPosition.xyz; +#endif`,wp=`#if defined( USE_COLOR_ALPHA ) + diffuseColor *= vColor; +#elif defined( USE_COLOR ) + diffuseColor.rgb *= vColor; +#endif`,Ep=`#if defined( USE_COLOR_ALPHA ) + varying vec4 vColor; +#elif defined( USE_COLOR ) + varying vec3 vColor; +#endif`,Tp=`#if defined( USE_COLOR_ALPHA ) + varying vec4 vColor; +#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) + varying vec3 vColor; +#endif`,Ap=`#if defined( USE_COLOR_ALPHA ) + vColor = vec4( 1.0 ); +#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) + vColor = vec3( 1.0 ); +#endif +#ifdef USE_COLOR + vColor *= color; +#endif +#ifdef USE_INSTANCING_COLOR + vColor.xyz *= instanceColor.xyz; +#endif +#ifdef USE_BATCHING_COLOR + vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) ); + vColor.xyz *= batchingColor.xyz; +#endif`,Rp=`#define PI 3.141592653589793 +#define PI2 6.283185307179586 +#define PI_HALF 1.5707963267948966 +#define RECIPROCAL_PI 0.3183098861837907 +#define RECIPROCAL_PI2 0.15915494309189535 +#define EPSILON 1e-6 +#ifndef saturate +#define saturate( a ) clamp( a, 0.0, 1.0 ) +#endif +#define whiteComplement( a ) ( 1.0 - saturate( a ) ) +float pow2( const in float x ) { return x*x; } +vec3 pow2( const in vec3 x ) { return x*x; } +float pow3( const in float x ) { return x*x*x; } +float pow4( const in float x ) { float x2 = x*x; return x2*x2; } +float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); } +float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); } +highp float rand( const in vec2 uv ) { + const highp float a = 12.9898, b = 78.233, c = 43758.5453; + highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI ); + return fract( sin( sn ) * c ); +} +#ifdef HIGH_PRECISION + float precisionSafeLength( vec3 v ) { return length( v ); } +#else + float precisionSafeLength( vec3 v ) { + float maxComponent = max3( abs( v ) ); + return length( v / maxComponent ) * maxComponent; + } +#endif +struct IncidentLight { + vec3 color; + vec3 direction; + bool visible; +}; +struct ReflectedLight { + vec3 directDiffuse; + vec3 directSpecular; + vec3 indirectDiffuse; + vec3 indirectSpecular; +}; +#ifdef USE_ALPHAHASH + varying vec3 vPosition; +#endif +vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); +} +vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) { + return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz ); +} +mat3 transposeMat3( const in mat3 m ) { + mat3 tmp; + tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x ); + tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y ); + tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z ); + return tmp; +} +bool isPerspectiveMatrix( mat4 m ) { + return m[ 2 ][ 3 ] == - 1.0; +} +vec2 equirectUv( in vec3 dir ) { + float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5; + float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5; + return vec2( u, v ); +} +vec3 BRDF_Lambert( const in vec3 diffuseColor ) { + return RECIPROCAL_PI * diffuseColor; +} +vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) { + float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); + return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); +} +float F_Schlick( const in float f0, const in float f90, const in float dotVH ) { + float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); + return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); +} // validated`,Cp=`#ifdef ENVMAP_TYPE_CUBE_UV + #define cubeUV_minMipLevel 4.0 + #define cubeUV_minTileSize 16.0 + float getFace( vec3 direction ) { + vec3 absDirection = abs( direction ); + float face = - 1.0; + if ( absDirection.x > absDirection.z ) { + if ( absDirection.x > absDirection.y ) + face = direction.x > 0.0 ? 0.0 : 3.0; + else + face = direction.y > 0.0 ? 1.0 : 4.0; + } else { + if ( absDirection.z > absDirection.y ) + face = direction.z > 0.0 ? 2.0 : 5.0; + else + face = direction.y > 0.0 ? 1.0 : 4.0; + } + return face; + } + vec2 getUV( vec3 direction, float face ) { + vec2 uv; + if ( face == 0.0 ) { + uv = vec2( direction.z, direction.y ) / abs( direction.x ); + } else if ( face == 1.0 ) { + uv = vec2( - direction.x, - direction.z ) / abs( direction.y ); + } else if ( face == 2.0 ) { + uv = vec2( - direction.x, direction.y ) / abs( direction.z ); + } else if ( face == 3.0 ) { + uv = vec2( - direction.z, direction.y ) / abs( direction.x ); + } else if ( face == 4.0 ) { + uv = vec2( - direction.x, direction.z ) / abs( direction.y ); + } else { + uv = vec2( direction.x, direction.y ) / abs( direction.z ); + } + return 0.5 * ( uv + 1.0 ); + } + vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) { + float face = getFace( direction ); + float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 ); + mipInt = max( mipInt, cubeUV_minMipLevel ); + float faceSize = exp2( mipInt ); + highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0; + if ( face > 2.0 ) { + uv.y += faceSize; + face -= 3.0; + } + uv.x += face * faceSize; + uv.x += filterInt * 3.0 * cubeUV_minTileSize; + uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize ); + uv.x *= CUBEUV_TEXEL_WIDTH; + uv.y *= CUBEUV_TEXEL_HEIGHT; + #ifdef texture2DGradEXT + return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb; + #else + return texture2D( envMap, uv ).rgb; + #endif + } + #define cubeUV_r0 1.0 + #define cubeUV_m0 - 2.0 + #define cubeUV_r1 0.8 + #define cubeUV_m1 - 1.0 + #define cubeUV_r4 0.4 + #define cubeUV_m4 2.0 + #define cubeUV_r5 0.305 + #define cubeUV_m5 3.0 + #define cubeUV_r6 0.21 + #define cubeUV_m6 4.0 + float roughnessToMip( float roughness ) { + float mip = 0.0; + if ( roughness >= cubeUV_r1 ) { + mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0; + } else if ( roughness >= cubeUV_r4 ) { + mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1; + } else if ( roughness >= cubeUV_r5 ) { + mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4; + } else if ( roughness >= cubeUV_r6 ) { + mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5; + } else { + mip = - 2.0 * log2( 1.16 * roughness ); } + return mip; + } + vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) { + float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP ); + float mipF = fract( mip ); + float mipInt = floor( mip ); + vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt ); + if ( mipF == 0.0 ) { + return vec4( color0, 1.0 ); + } else { + vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 ); + return vec4( mix( color0, color1, mipF ), 1.0 ); + } + } +#endif`,Pp=`vec3 transformedNormal = objectNormal; +#ifdef USE_TANGENT + vec3 transformedTangent = objectTangent; +#endif +#ifdef USE_BATCHING + mat3 bm = mat3( batchingMatrix ); + transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) ); + transformedNormal = bm * transformedNormal; + #ifdef USE_TANGENT + transformedTangent = bm * transformedTangent; + #endif +#endif +#ifdef USE_INSTANCING + mat3 im = mat3( instanceMatrix ); + transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) ); + transformedNormal = im * transformedNormal; + #ifdef USE_TANGENT + transformedTangent = im * transformedTangent; + #endif +#endif +transformedNormal = normalMatrix * transformedNormal; +#ifdef FLIP_SIDED + transformedNormal = - transformedNormal; +#endif +#ifdef USE_TANGENT + transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz; + #ifdef FLIP_SIDED + transformedTangent = - transformedTangent; + #endif +#endif`,Ip=`#ifdef USE_DISPLACEMENTMAP + uniform sampler2D displacementMap; + uniform float displacementScale; + uniform float displacementBias; +#endif`,Dp=`#ifdef USE_DISPLACEMENTMAP + transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias ); +#endif`,Lp=`#ifdef USE_EMISSIVEMAP + vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); + #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE + emissiveColor = sRGBTransferEOTF( emissiveColor ); + #endif + totalEmissiveRadiance *= emissiveColor.rgb; +#endif`,Up=`#ifdef USE_EMISSIVEMAP + uniform sampler2D emissiveMap; +#endif`,Np="gl_FragColor = linearToOutputTexel( gl_FragColor );",Fp=`vec4 LinearTransferOETF( in vec4 value ) { + return value; +} +vec4 sRGBTransferEOTF( in vec4 value ) { + return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a ); +} +vec4 sRGBTransferOETF( in vec4 value ) { + return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a ); +}`,Op=`#ifdef USE_ENVMAP + #ifdef ENV_WORLDPOS + vec3 cameraToFrag; + if ( isOrthographic ) { + cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); + } else { + cameraToFrag = normalize( vWorldPosition - cameraPosition ); + } + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + #ifdef ENVMAP_MODE_REFLECTION + vec3 reflectVec = reflect( cameraToFrag, worldNormal ); + #else + vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio ); + #endif + #else + vec3 reflectVec = vReflect; + #endif + #ifdef ENVMAP_TYPE_CUBE + vec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) ); + #else + vec4 envColor = vec4( 0.0 ); + #endif + #ifdef ENVMAP_BLENDING_MULTIPLY + outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity ); + #elif defined( ENVMAP_BLENDING_MIX ) + outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity ); + #elif defined( ENVMAP_BLENDING_ADD ) + outgoingLight += envColor.xyz * specularStrength * reflectivity; + #endif +#endif`,Bp=`#ifdef USE_ENVMAP + uniform float envMapIntensity; + uniform float flipEnvMap; + uniform mat3 envMapRotation; + #ifdef ENVMAP_TYPE_CUBE + uniform samplerCube envMap; + #else + uniform sampler2D envMap; + #endif + +#endif`,zp=`#ifdef USE_ENVMAP + uniform float reflectivity; + #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) + #define ENV_WORLDPOS + #endif + #ifdef ENV_WORLDPOS + varying vec3 vWorldPosition; + uniform float refractionRatio; + #else + varying vec3 vReflect; + #endif +#endif`,kp=`#ifdef USE_ENVMAP + #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) + #define ENV_WORLDPOS + #endif + #ifdef ENV_WORLDPOS + + varying vec3 vWorldPosition; + #else + varying vec3 vReflect; + uniform float refractionRatio; + #endif +#endif`,Hp=`#ifdef USE_ENVMAP + #ifdef ENV_WORLDPOS + vWorldPosition = worldPosition.xyz; + #else + vec3 cameraToVertex; + if ( isOrthographic ) { + cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); + } else { + cameraToVertex = normalize( worldPosition.xyz - cameraPosition ); + } + vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); + #ifdef ENVMAP_MODE_REFLECTION + vReflect = reflect( cameraToVertex, worldNormal ); + #else + vReflect = refract( cameraToVertex, worldNormal, refractionRatio ); + #endif + #endif +#endif`,Vp=`#ifdef USE_FOG + vFogDepth = - mvPosition.z; +#endif`,Gp=`#ifdef USE_FOG + varying float vFogDepth; +#endif`,Wp=`#ifdef USE_FOG + #ifdef FOG_EXP2 + float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth ); + #else + float fogFactor = smoothstep( fogNear, fogFar, vFogDepth ); + #endif + gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor ); +#endif`,Xp=`#ifdef USE_FOG + uniform vec3 fogColor; + varying float vFogDepth; + #ifdef FOG_EXP2 + uniform float fogDensity; + #else + uniform float fogNear; + uniform float fogFar; + #endif +#endif`,qp=`#ifdef USE_GRADIENTMAP + uniform sampler2D gradientMap; +#endif +vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { + float dotNL = dot( normal, lightDirection ); + vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 ); + #ifdef USE_GRADIENTMAP + return vec3( texture2D( gradientMap, coord ).r ); + #else + vec2 fw = fwidth( coord ) * 0.5; + return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) ); + #endif +}`,Yp=`#ifdef USE_LIGHTMAP + uniform sampler2D lightMap; + uniform float lightMapIntensity; +#endif`,Zp=`LambertMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularStrength = specularStrength;`,Jp=`varying vec3 vViewPosition; +struct LambertMaterial { + vec3 diffuseColor; + float specularStrength; +}; +void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_Lambert +#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,$p=`uniform bool receiveShadow; +uniform vec3 ambientLightColor; +#if defined( USE_LIGHT_PROBES ) + uniform vec3 lightProbe[ 9 ]; +#endif +vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) { + float x = normal.x, y = normal.y, z = normal.z; + vec3 result = shCoefficients[ 0 ] * 0.886227; + result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y; + result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z; + result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x; + result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y; + result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z; + result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 ); + result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z; + result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y ); + return result; +} +vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) { + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe ); + return irradiance; +} +vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) { + vec3 irradiance = ambientLightColor; + return irradiance; +} +float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) { + float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 ); + if ( cutoffDistance > 0.0 ) { + distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) ); + } + return distanceFalloff; +} +float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) { + return smoothstep( coneCosine, penumbraCosine, angleCosine ); +} +#if NUM_DIR_LIGHTS > 0 + struct DirectionalLight { + vec3 direction; + vec3 color; + }; + uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ]; + void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) { + light.color = directionalLight.color; + light.direction = directionalLight.direction; + light.visible = true; + } +#endif +#if NUM_POINT_LIGHTS > 0 + struct PointLight { + vec3 position; + vec3 color; + float distance; + float decay; + }; + uniform PointLight pointLights[ NUM_POINT_LIGHTS ]; + void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) { + vec3 lVector = pointLight.position - geometryPosition; + light.direction = normalize( lVector ); + float lightDistance = length( lVector ); + light.color = pointLight.color; + light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay ); + light.visible = ( light.color != vec3( 0.0 ) ); + } +#endif +#if NUM_SPOT_LIGHTS > 0 + struct SpotLight { + vec3 position; + vec3 direction; + vec3 color; + float distance; + float decay; + float coneCos; + float penumbraCos; + }; + uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ]; + void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) { + vec3 lVector = spotLight.position - geometryPosition; + light.direction = normalize( lVector ); + float angleCos = dot( light.direction, spotLight.direction ); + float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos ); + if ( spotAttenuation > 0.0 ) { + float lightDistance = length( lVector ); + light.color = spotLight.color * spotAttenuation; + light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay ); + light.visible = ( light.color != vec3( 0.0 ) ); + } else { + light.color = vec3( 0.0 ); + light.visible = false; + } + } +#endif +#if NUM_RECT_AREA_LIGHTS > 0 + struct RectAreaLight { + vec3 color; + vec3 position; + vec3 halfWidth; + vec3 halfHeight; + }; + uniform sampler2D ltc_1; uniform sampler2D ltc_2; + uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ]; +#endif +#if NUM_HEMI_LIGHTS > 0 + struct HemisphereLight { + vec3 direction; + vec3 skyColor; + vec3 groundColor; + }; + uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ]; + vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) { + float dotNL = dot( normal, hemiLight.direction ); + float hemiDiffuseWeight = 0.5 * dotNL + 0.5; + vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight ); + return irradiance; + } +#endif`,Kp=`#ifdef USE_ENVMAP + vec3 getIBLIrradiance( const in vec3 normal ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 ); + return PI * envMapColor.rgb * envMapIntensity; + #else + return vec3( 0.0 ); + #endif + } + vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 reflectVec = reflect( - viewDir, normal ); + reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) ); + reflectVec = inverseTransformDirection( reflectVec, viewMatrix ); + vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness ); + return envMapColor.rgb * envMapIntensity; + #else + return vec3( 0.0 ); + #endif + } + #ifdef USE_ANISOTROPY + vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 bentNormal = cross( bitangent, viewDir ); + bentNormal = normalize( cross( bentNormal, bitangent ) ); + bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) ); + return getIBLRadiance( viewDir, bentNormal, roughness ); + #else + return vec3( 0.0 ); + #endif + } + #endif +#endif`,jp=`ToonMaterial material; +material.diffuseColor = diffuseColor.rgb;`,Qp=`varying vec3 vViewPosition; +struct ToonMaterial { + vec3 diffuseColor; +}; +void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { + vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_Toon +#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,tm=`BlinnPhongMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularColor = specular; +material.specularShininess = shininess; +material.specularStrength = specularStrength;`,em=`varying vec3 vViewPosition; +struct BlinnPhongMaterial { + vec3 diffuseColor; + vec3 specularColor; + float specularShininess; + float specularStrength; +}; +void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); + reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength; +} +void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_BlinnPhong +#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,nm=`PhysicalMaterial material; +material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor ); +vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) ); +float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z ); +material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness; +material.roughness = min( material.roughness, 1.0 ); +#ifdef IOR + material.ior = ior; + #ifdef USE_SPECULAR + float specularIntensityFactor = specularIntensity; + vec3 specularColorFactor = specularColor; + #ifdef USE_SPECULAR_COLORMAP + specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb; + #endif + #ifdef USE_SPECULAR_INTENSITYMAP + specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a; + #endif + material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor ); + #else + float specularIntensityFactor = 1.0; + vec3 specularColorFactor = vec3( 1.0 ); + material.specularF90 = 1.0; + #endif + material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor ); +#else + material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor ); + material.specularF90 = 1.0; +#endif +#ifdef USE_CLEARCOAT + material.clearcoat = clearcoat; + material.clearcoatRoughness = clearcoatRoughness; + material.clearcoatF0 = vec3( 0.04 ); + material.clearcoatF90 = 1.0; + #ifdef USE_CLEARCOATMAP + material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x; + #endif + #ifdef USE_CLEARCOAT_ROUGHNESSMAP + material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y; + #endif + material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 ); + material.clearcoatRoughness += geometryRoughness; + material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 ); +#endif +#ifdef USE_DISPERSION + material.dispersion = dispersion; +#endif +#ifdef USE_IRIDESCENCE + material.iridescence = iridescence; + material.iridescenceIOR = iridescenceIOR; + #ifdef USE_IRIDESCENCEMAP + material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r; + #endif + #ifdef USE_IRIDESCENCE_THICKNESSMAP + material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum; + #else + material.iridescenceThickness = iridescenceThicknessMaximum; + #endif +#endif +#ifdef USE_SHEEN + material.sheenColor = sheenColor; + #ifdef USE_SHEEN_COLORMAP + material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb; + #endif + material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 ); + #ifdef USE_SHEEN_ROUGHNESSMAP + material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a; + #endif +#endif +#ifdef USE_ANISOTROPY + #ifdef USE_ANISOTROPYMAP + mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x ); + vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb; + vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b; + #else + vec2 anisotropyV = anisotropyVector; + #endif + material.anisotropy = length( anisotropyV ); + if( material.anisotropy == 0.0 ) { + anisotropyV = vec2( 1.0, 0.0 ); + } else { + anisotropyV /= material.anisotropy; + material.anisotropy = saturate( material.anisotropy ); + } + material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) ); + material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y; + material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y; +#endif`,im=`struct PhysicalMaterial { + vec3 diffuseColor; + float roughness; + vec3 specularColor; + float specularF90; + float dispersion; + #ifdef USE_CLEARCOAT + float clearcoat; + float clearcoatRoughness; + vec3 clearcoatF0; + float clearcoatF90; + #endif + #ifdef USE_IRIDESCENCE + float iridescence; + float iridescenceIOR; + float iridescenceThickness; + vec3 iridescenceFresnel; + vec3 iridescenceF0; + #endif + #ifdef USE_SHEEN + vec3 sheenColor; + float sheenRoughness; + #endif + #ifdef IOR + float ior; + #endif + #ifdef USE_TRANSMISSION + float transmission; + float transmissionAlpha; + float thickness; + float attenuationDistance; + vec3 attenuationColor; + #endif + #ifdef USE_ANISOTROPY + float anisotropy; + float alphaT; + vec3 anisotropyT; + vec3 anisotropyB; + #endif +}; +vec3 clearcoatSpecularDirect = vec3( 0.0 ); +vec3 clearcoatSpecularIndirect = vec3( 0.0 ); +vec3 sheenSpecularDirect = vec3( 0.0 ); +vec3 sheenSpecularIndirect = vec3(0.0 ); +vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) { + float x = clamp( 1.0 - dotVH, 0.0, 1.0 ); + float x2 = x * x; + float x5 = clamp( x * x2 * x2, 0.0, 0.9999 ); + return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 ); +} +float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) { + float a2 = pow2( alpha ); + float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) ); + float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) ); + return 0.5 / max( gv + gl, EPSILON ); +} +float D_GGX( const in float alpha, const in float dotNH ) { + float a2 = pow2( alpha ); + float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; + return RECIPROCAL_PI * a2 / pow2( denom ); +} +#ifdef USE_ANISOTROPY + float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) { + float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) ); + float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) ); + float v = 0.5 / ( gv + gl ); + return saturate(v); + } + float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) { + float a2 = alphaT * alphaB; + highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH ); + highp float v2 = dot( v, v ); + float w2 = a2 / v2; + return RECIPROCAL_PI * a2 * pow2 ( w2 ); + } +#endif +#ifdef USE_CLEARCOAT + vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) { + vec3 f0 = material.clearcoatF0; + float f90 = material.clearcoatF90; + float roughness = material.clearcoatRoughness; + float alpha = pow2( roughness ); + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( f0, f90, dotVH ); + float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); + float D = D_GGX( alpha, dotNH ); + return F * ( V * D ); + } +#endif +vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { + vec3 f0 = material.specularColor; + float f90 = material.specularF90; + float roughness = material.roughness; + float alpha = pow2( roughness ); + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( f0, f90, dotVH ); + #ifdef USE_IRIDESCENCE + F = mix( F, material.iridescenceFresnel, material.iridescence ); + #endif + #ifdef USE_ANISOTROPY + float dotTL = dot( material.anisotropyT, lightDir ); + float dotTV = dot( material.anisotropyT, viewDir ); + float dotTH = dot( material.anisotropyT, halfDir ); + float dotBL = dot( material.anisotropyB, lightDir ); + float dotBV = dot( material.anisotropyB, viewDir ); + float dotBH = dot( material.anisotropyB, halfDir ); + float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL ); + float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH ); + #else + float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); + float D = D_GGX( alpha, dotNH ); + #endif + return F * ( V * D ); +} +vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) { + const float LUT_SIZE = 64.0; + const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE; + const float LUT_BIAS = 0.5 / LUT_SIZE; + float dotNV = saturate( dot( N, V ) ); + vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) ); + uv = uv * LUT_SCALE + LUT_BIAS; + return uv; +} +float LTC_ClippedSphereFormFactor( const in vec3 f ) { + float l = length( f ); + return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 ); +} +vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) { + float x = dot( v1, v2 ); + float y = abs( x ); + float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y; + float b = 3.4175940 + ( 4.1616724 + y ) * y; + float v = a / b; + float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v; + return cross( v1, v2 ) * theta_sintheta; +} +vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) { + vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ]; + vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ]; + vec3 lightNormal = cross( v1, v2 ); + if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 ); + vec3 T1, T2; + T1 = normalize( V - N * dot( V, N ) ); + T2 = - cross( N, T1 ); + mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) ); + vec3 coords[ 4 ]; + coords[ 0 ] = mat * ( rectCoords[ 0 ] - P ); + coords[ 1 ] = mat * ( rectCoords[ 1 ] - P ); + coords[ 2 ] = mat * ( rectCoords[ 2 ] - P ); + coords[ 3 ] = mat * ( rectCoords[ 3 ] - P ); + coords[ 0 ] = normalize( coords[ 0 ] ); + coords[ 1 ] = normalize( coords[ 1 ] ); + coords[ 2 ] = normalize( coords[ 2 ] ); + coords[ 3 ] = normalize( coords[ 3 ] ); + vec3 vectorFormFactor = vec3( 0.0 ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] ); + float result = LTC_ClippedSphereFormFactor( vectorFormFactor ); + return vec3( result ); +} +#if defined( USE_SHEEN ) +float D_Charlie( float roughness, float dotNH ) { + float alpha = pow2( roughness ); + float invAlpha = 1.0 / alpha; + float cos2h = dotNH * dotNH; + float sin2h = max( 1.0 - cos2h, 0.0078125 ); + return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI ); +} +float V_Neubelt( float dotNV, float dotNL ) { + return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) ); +} +vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) { + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float D = D_Charlie( sheenRoughness, dotNH ); + float V = V_Neubelt( dotNV, dotNL ); + return sheenColor * ( D * V ); +} +#endif +float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { + float dotNV = saturate( dot( normal, viewDir ) ); + float r2 = roughness * roughness; + float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95; + float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72; + float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) ); + return saturate( DG * RECIPROCAL_PI ); +} +vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { + float dotNV = saturate( dot( normal, viewDir ) ); + const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 ); + const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 ); + vec4 r = roughness * c0 + c1; + float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y; + vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw; + return fab; +} +vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) { + vec2 fab = DFGApprox( normal, viewDir, roughness ); + return specularColor * fab.x + specularF90 * fab.y; +} +#ifdef USE_IRIDESCENCE +void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { +#else +void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { +#endif + vec2 fab = DFGApprox( normal, viewDir, roughness ); + #ifdef USE_IRIDESCENCE + vec3 Fr = mix( specularColor, iridescenceF0, iridescence ); + #else + vec3 Fr = specularColor; + #endif + vec3 FssEss = Fr * fab.x + specularF90 * fab.y; + float Ess = fab.x + fab.y; + float Ems = 1.0 - Ess; + vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg ); + singleScatter += FssEss; + multiScatter += Fms * Ems; +} +#if NUM_RECT_AREA_LIGHTS > 0 + void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + vec3 normal = geometryNormal; + vec3 viewDir = geometryViewDir; + vec3 position = geometryPosition; + vec3 lightPos = rectAreaLight.position; + vec3 halfWidth = rectAreaLight.halfWidth; + vec3 halfHeight = rectAreaLight.halfHeight; + vec3 lightColor = rectAreaLight.color; + float roughness = material.roughness; + vec3 rectCoords[ 4 ]; + rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight; + rectCoords[ 2 ] = lightPos - halfWidth + halfHeight; + rectCoords[ 3 ] = lightPos + halfWidth + halfHeight; + vec2 uv = LTC_Uv( normal, viewDir, roughness ); + vec4 t1 = texture2D( ltc_1, uv ); + vec4 t2 = texture2D( ltc_2, uv ); + mat3 mInv = mat3( + vec3( t1.x, 0, t1.y ), + vec3( 0, 1, 0 ), + vec3( t1.z, 0, t1.w ) + ); + vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y ); + reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords ); + reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords ); + } +#endif +void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + #ifdef USE_CLEARCOAT + float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) ); + vec3 ccIrradiance = dotNLcc * directLight.color; + clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material ); + #endif + #ifdef USE_SHEEN + sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness ); + #endif + reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material ); + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) { + #ifdef USE_CLEARCOAT + clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness ); + #endif + #ifdef USE_SHEEN + sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); + #endif + vec3 singleScattering = vec3( 0.0 ); + vec3 multiScattering = vec3( 0.0 ); + vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI; + #ifdef USE_IRIDESCENCE + computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering ); + #else + computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering ); + #endif + vec3 totalScattering = singleScattering + multiScattering; + vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) ); + reflectedLight.indirectSpecular += radiance * singleScattering; + reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance; + reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance; +} +#define RE_Direct RE_Direct_Physical +#define RE_Direct_RectArea RE_Direct_RectArea_Physical +#define RE_IndirectDiffuse RE_IndirectDiffuse_Physical +#define RE_IndirectSpecular RE_IndirectSpecular_Physical +float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) { + return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); +}`,sm=` +vec3 geometryPosition = - vViewPosition; +vec3 geometryNormal = normal; +vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); +vec3 geometryClearcoatNormal = vec3( 0.0 ); +#ifdef USE_CLEARCOAT + geometryClearcoatNormal = clearcoatNormal; +#endif +#ifdef USE_IRIDESCENCE + float dotNVi = saturate( dot( normal, geometryViewDir ) ); + if ( material.iridescenceThickness == 0.0 ) { + material.iridescence = 0.0; + } else { + material.iridescence = saturate( material.iridescence ); + } + if ( material.iridescence > 0.0 ) { + material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor ); + material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi ); + } +#endif +IncidentLight directLight; +#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) + PointLight pointLight; + #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 + PointLightShadow pointLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { + pointLight = pointLights[ i ]; + getPointLightInfo( pointLight, geometryPosition, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) + pointLightShadow = pointLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) + SpotLight spotLight; + vec4 spotColor; + vec3 spotLightCoord; + bool inSpotLightMap; + #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { + spotLight = spotLights[ i ]; + getSpotLightInfo( spotLight, geometryPosition, directLight ); + #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) + #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX + #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS + #else + #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) + #endif + #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS ) + spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w; + inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) ); + spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy ); + directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color; + #endif + #undef SPOT_LIGHT_MAP_INDEX + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + spotLightShadow = spotLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) + DirectionalLight directionalLight; + #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + directionalLight = directionalLights[ i ]; + getDirectionalLightInfo( directionalLight, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) + directionalLightShadow = directionalLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) + RectAreaLight rectAreaLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { + rectAreaLight = rectAreaLights[ i ]; + RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if defined( RE_IndirectDiffuse ) + vec3 iblIrradiance = vec3( 0.0 ); + vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); + #if defined( USE_LIGHT_PROBES ) + irradiance += getLightProbeIrradiance( lightProbe, geometryNormal ); + #endif + #if ( NUM_HEMI_LIGHTS > 0 ) + #pragma unroll_loop_start + for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { + irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); + } + #pragma unroll_loop_end + #endif +#endif +#if defined( RE_IndirectSpecular ) + vec3 radiance = vec3( 0.0 ); + vec3 clearcoatRadiance = vec3( 0.0 ); +#endif`,rm=`#if defined( RE_IndirectDiffuse ) + #ifdef USE_LIGHTMAP + vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); + vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; + irradiance += lightMapIrradiance; + #endif + #if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV ) + iblIrradiance += getIBLIrradiance( geometryNormal ); + #endif +#endif +#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular ) + #ifdef USE_ANISOTROPY + radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy ); + #else + radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness ); + #endif + #ifdef USE_CLEARCOAT + clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness ); + #endif +#endif`,om=`#if defined( RE_IndirectDiffuse ) + RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); +#endif +#if defined( RE_IndirectSpecular ) + RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); +#endif`,am=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) + gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; +#endif`,lm=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) + uniform float logDepthBufFC; + varying float vFragDepth; + varying float vIsPerspective; +#endif`,cm=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER + varying float vFragDepth; + varying float vIsPerspective; +#endif`,hm=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER + vFragDepth = 1.0 + gl_Position.w; + vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); +#endif`,um=`#ifdef USE_MAP + vec4 sampledDiffuseColor = texture2D( map, vMapUv ); + #ifdef DECODE_VIDEO_TEXTURE + sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor ); + #endif + diffuseColor *= sampledDiffuseColor; +#endif`,dm=`#ifdef USE_MAP + uniform sampler2D map; +#endif`,fm=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) + #if defined( USE_POINTS_UV ) + vec2 uv = vUv; + #else + vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy; + #endif +#endif +#ifdef USE_MAP + diffuseColor *= texture2D( map, uv ); +#endif +#ifdef USE_ALPHAMAP + diffuseColor.a *= texture2D( alphaMap, uv ).g; +#endif`,pm=`#if defined( USE_POINTS_UV ) + varying vec2 vUv; +#else + #if defined( USE_MAP ) || defined( USE_ALPHAMAP ) + uniform mat3 uvTransform; + #endif +#endif +#ifdef USE_MAP + uniform sampler2D map; +#endif +#ifdef USE_ALPHAMAP + uniform sampler2D alphaMap; +#endif`,mm=`float metalnessFactor = metalness; +#ifdef USE_METALNESSMAP + vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); + metalnessFactor *= texelMetalness.b; +#endif`,gm=`#ifdef USE_METALNESSMAP + uniform sampler2D metalnessMap; +#endif`,_m=`#ifdef USE_INSTANCING_MORPH + float morphTargetInfluences[ MORPHTARGETS_COUNT ]; + float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r; + } +#endif`,xm=`#if defined( USE_MORPHCOLORS ) + vColor *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + #if defined( USE_COLOR_ALPHA ) + if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ]; + #elif defined( USE_COLOR ) + if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ]; + #endif + } +#endif`,ym=`#ifdef USE_MORPHNORMALS + objectNormal *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ]; + } +#endif`,vm=`#ifdef USE_MORPHTARGETS + #ifndef USE_INSTANCING_MORPH + uniform float morphTargetBaseInfluence; + uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ]; + #endif + uniform sampler2DArray morphTargetsTexture; + uniform ivec2 morphTargetsTextureSize; + vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) { + int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset; + int y = texelIndex / morphTargetsTextureSize.x; + int x = texelIndex - y * morphTargetsTextureSize.x; + ivec3 morphUV = ivec3( x, y, morphTargetIndex ); + return texelFetch( morphTargetsTexture, morphUV, 0 ); + } +#endif`,Mm=`#ifdef USE_MORPHTARGETS + transformed *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ]; + } +#endif`,Sm=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; +#ifdef FLAT_SHADED + vec3 fdx = dFdx( vViewPosition ); + vec3 fdy = dFdy( vViewPosition ); + vec3 normal = normalize( cross( fdx, fdy ) ); +#else + vec3 normal = normalize( vNormal ); + #ifdef DOUBLE_SIDED + normal *= faceDirection; + #endif +#endif +#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) + #ifdef USE_TANGENT + mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); + #else + mat3 tbn = getTangentFrame( - vViewPosition, normal, + #if defined( USE_NORMALMAP ) + vNormalMapUv + #elif defined( USE_CLEARCOAT_NORMALMAP ) + vClearcoatNormalMapUv + #else + vUv + #endif + ); + #endif + #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) + tbn[0] *= faceDirection; + tbn[1] *= faceDirection; + #endif +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + #ifdef USE_TANGENT + mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); + #else + mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv ); + #endif + #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) + tbn2[0] *= faceDirection; + tbn2[1] *= faceDirection; + #endif +#endif +vec3 nonPerturbedNormal = normal;`,bm=`#ifdef USE_NORMALMAP_OBJECTSPACE + normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; + #ifdef FLIP_SIDED + normal = - normal; + #endif + #ifdef DOUBLE_SIDED + normal = normal * faceDirection; + #endif + normal = normalize( normalMatrix * normal ); +#elif defined( USE_NORMALMAP_TANGENTSPACE ) + vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; + mapN.xy *= normalScale; + normal = normalize( tbn * mapN ); +#elif defined( USE_BUMPMAP ) + normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection ); +#endif`,wm=`#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`,Em=`#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`,Tm=`#ifndef FLAT_SHADED + vNormal = normalize( transformedNormal ); + #ifdef USE_TANGENT + vTangent = normalize( transformedTangent ); + vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); + #endif +#endif`,Am=`#ifdef USE_NORMALMAP + uniform sampler2D normalMap; + uniform vec2 normalScale; +#endif +#ifdef USE_NORMALMAP_OBJECTSPACE + uniform mat3 normalMatrix; +#endif +#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) ) + mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) { + vec3 q0 = dFdx( eye_pos.xyz ); + vec3 q1 = dFdy( eye_pos.xyz ); + vec2 st0 = dFdx( uv.st ); + vec2 st1 = dFdy( uv.st ); + vec3 N = surf_norm; + vec3 q1perp = cross( q1, N ); + vec3 q0perp = cross( N, q0 ); + vec3 T = q1perp * st0.x + q0perp * st1.x; + vec3 B = q1perp * st0.y + q0perp * st1.y; + float det = max( dot( T, T ), dot( B, B ) ); + float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det ); + return mat3( T * scale, B * scale, N ); + } +#endif`,Rm=`#ifdef USE_CLEARCOAT + vec3 clearcoatNormal = nonPerturbedNormal; +#endif`,Cm=`#ifdef USE_CLEARCOAT_NORMALMAP + vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; + clearcoatMapN.xy *= clearcoatNormalScale; + clearcoatNormal = normalize( tbn2 * clearcoatMapN ); +#endif`,Pm=`#ifdef USE_CLEARCOATMAP + uniform sampler2D clearcoatMap; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + uniform sampler2D clearcoatNormalMap; + uniform vec2 clearcoatNormalScale; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + uniform sampler2D clearcoatRoughnessMap; +#endif`,Im=`#ifdef USE_IRIDESCENCEMAP + uniform sampler2D iridescenceMap; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + uniform sampler2D iridescenceThicknessMap; +#endif`,Dm=`#ifdef OPAQUE +diffuseColor.a = 1.0; +#endif +#ifdef USE_TRANSMISSION +diffuseColor.a *= material.transmissionAlpha; +#endif +gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,Lm=`vec3 packNormalToRGB( const in vec3 normal ) { + return normalize( normal ) * 0.5 + 0.5; +} +vec3 unpackRGBToNormal( const in vec3 rgb ) { + return 2.0 * rgb.xyz - 1.0; +} +const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.; +const float Inv255 = 1. / 255.; +const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 ); +const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g ); +const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b ); +const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a ); +vec4 packDepthToRGBA( const in float v ) { + if( v <= 0.0 ) + return vec4( 0., 0., 0., 0. ); + if( v >= 1.0 ) + return vec4( 1., 1., 1., 1. ); + float vuf; + float af = modf( v * PackFactors.a, vuf ); + float bf = modf( vuf * ShiftRight8, vuf ); + float gf = modf( vuf * ShiftRight8, vuf ); + return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af ); +} +vec3 packDepthToRGB( const in float v ) { + if( v <= 0.0 ) + return vec3( 0., 0., 0. ); + if( v >= 1.0 ) + return vec3( 1., 1., 1. ); + float vuf; + float bf = modf( v * PackFactors.b, vuf ); + float gf = modf( vuf * ShiftRight8, vuf ); + return vec3( vuf * Inv255, gf * PackUpscale, bf ); +} +vec2 packDepthToRG( const in float v ) { + if( v <= 0.0 ) + return vec2( 0., 0. ); + if( v >= 1.0 ) + return vec2( 1., 1. ); + float vuf; + float gf = modf( v * 256., vuf ); + return vec2( vuf * Inv255, gf ); +} +float unpackRGBAToDepth( const in vec4 v ) { + return dot( v, UnpackFactors4 ); +} +float unpackRGBToDepth( const in vec3 v ) { + return dot( v, UnpackFactors3 ); +} +float unpackRGToDepth( const in vec2 v ) { + return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g; +} +vec4 pack2HalfToRGBA( const in vec2 v ) { + vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) ); + return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w ); +} +vec2 unpackRGBATo2Half( const in vec4 v ) { + return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) ); +} +float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) { + return ( viewZ + near ) / ( near - far ); +} +float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) { + return depth * ( near - far ) - near; +} +float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) { + return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ ); +} +float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) { + return ( near * far ) / ( ( far - near ) * depth - far ); +}`,Um=`#ifdef PREMULTIPLIED_ALPHA + gl_FragColor.rgb *= gl_FragColor.a; +#endif`,Nm=`vec4 mvPosition = vec4( transformed, 1.0 ); +#ifdef USE_BATCHING + mvPosition = batchingMatrix * mvPosition; +#endif +#ifdef USE_INSTANCING + mvPosition = instanceMatrix * mvPosition; +#endif +mvPosition = modelViewMatrix * mvPosition; +gl_Position = projectionMatrix * mvPosition;`,Fm=`#ifdef DITHERING + gl_FragColor.rgb = dithering( gl_FragColor.rgb ); +#endif`,Om=`#ifdef DITHERING + vec3 dithering( vec3 color ) { + float grid_position = rand( gl_FragCoord.xy ); + vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 ); + dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position ); + return color + dither_shift_RGB; + } +#endif`,Bm=`float roughnessFactor = roughness; +#ifdef USE_ROUGHNESSMAP + vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); + roughnessFactor *= texelRoughness.g; +#endif`,zm=`#ifdef USE_ROUGHNESSMAP + uniform sampler2D roughnessMap; +#endif`,km=`#if NUM_SPOT_LIGHT_COORDS > 0 + varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; +#endif +#if NUM_SPOT_LIGHT_MAPS > 0 + uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ]; +#endif +#ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; + varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; + struct DirectionalLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; + struct SpotLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; + varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; + struct PointLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + float shadowCameraNear; + float shadowCameraFar; + }; + uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; + #endif + float texture2DCompare( sampler2D depths, vec2 uv, float compare ) { + float depth = unpackRGBAToDepth( texture2D( depths, uv ) ); + #ifdef USE_REVERSED_DEPTH_BUFFER + return step( depth, compare ); + #else + return step( compare, depth ); + #endif + } + vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) { + return unpackRGBATo2Half( texture2D( shadow, uv ) ); + } + float VSMShadow( sampler2D shadow, vec2 uv, float compare ) { + float occlusion = 1.0; + vec2 distribution = texture2DDistribution( shadow, uv ); + #ifdef USE_REVERSED_DEPTH_BUFFER + float hard_shadow = step( distribution.x, compare ); + #else + float hard_shadow = step( compare, distribution.x ); + #endif + if ( hard_shadow != 1.0 ) { + float distance = compare - distribution.x; + float variance = max( 0.00000, distribution.y * distribution.y ); + float softness_probability = variance / (variance + distance * distance ); softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 ); occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 ); + } + return occlusion; + } + float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { + float shadow = 1.0; + shadowCoord.xyz /= shadowCoord.w; + shadowCoord.z += shadowBias; + bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; + bool frustumTest = inFrustum && shadowCoord.z <= 1.0; + if ( frustumTest ) { + #if defined( SHADOWMAP_TYPE_PCF ) + vec2 texelSize = vec2( 1.0 ) / shadowMapSize; + float dx0 = - texelSize.x * shadowRadius; + float dy0 = - texelSize.y * shadowRadius; + float dx1 = + texelSize.x * shadowRadius; + float dy1 = + texelSize.y * shadowRadius; + float dx2 = dx0 / 2.0; + float dy2 = dy0 / 2.0; + float dx3 = dx1 / 2.0; + float dy3 = dy1 / 2.0; + shadow = ( + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z ) + ) * ( 1.0 / 17.0 ); + #elif defined( SHADOWMAP_TYPE_PCF_SOFT ) + vec2 texelSize = vec2( 1.0 ) / shadowMapSize; + float dx = texelSize.x; + float dy = texelSize.y; + vec2 uv = shadowCoord.xy; + vec2 f = fract( uv * shadowMapSize + 0.5 ); + uv -= f * texelSize; + shadow = ( + texture2DCompare( shadowMap, uv, shadowCoord.z ) + + texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) + + texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) + + mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ), + f.x ) + + mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ), + f.x ) + + mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ), + f.y ) + + mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ), + f.y ) + + mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ), + f.x ), + mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ), + f.x ), + f.y ) + ) * ( 1.0 / 9.0 ); + #elif defined( SHADOWMAP_TYPE_VSM ) + shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z ); + #else + shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ); + #endif + } + return mix( 1.0, shadow, shadowIntensity ); + } + vec2 cubeToUV( vec3 v, float texelSizeY ) { + vec3 absV = abs( v ); + float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) ); + absV *= scaleToCube; + v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY ); + vec2 planar = v.xy; + float almostATexel = 1.5 * texelSizeY; + float almostOne = 1.0 - almostATexel; + if ( absV.z >= almostOne ) { + if ( v.z > 0.0 ) + planar.x = 4.0 - v.x; + } else if ( absV.x >= almostOne ) { + float signX = sign( v.x ); + planar.x = v.z * signX + 2.0 * signX; + } else if ( absV.y >= almostOne ) { + float signY = sign( v.y ); + planar.x = v.x + 2.0 * signY + 2.0; + planar.y = v.z * signY - 2.0; + } + return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 ); + } + float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { + float shadow = 1.0; + vec3 lightToPosition = shadowCoord.xyz; + + float lightToPositionLength = length( lightToPosition ); + if ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) { + float dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); dp += shadowBias; + vec3 bd3D = normalize( lightToPosition ); + vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) ); + #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM ) + vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y; + shadow = ( + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp ) + ) * ( 1.0 / 9.0 ); + #else + shadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ); + #endif + } + return mix( 1.0, shadow, shadowIntensity ); + } +#endif`,Hm=`#if NUM_SPOT_LIGHT_COORDS > 0 + uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ]; + varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; +#endif +#ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ]; + varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; + struct DirectionalLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + struct SpotLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ]; + varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; + struct PointLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + float shadowCameraNear; + float shadowCameraFar; + }; + uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; + #endif +#endif`,Vm=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) + vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); + vec4 shadowWorldPosition; +#endif +#if defined( USE_SHADOWMAP ) + #if NUM_DIR_LIGHT_SHADOWS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { + shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 ); + vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { + shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 ); + vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end + #endif +#endif +#if NUM_SPOT_LIGHT_COORDS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) { + shadowWorldPosition = worldPosition; + #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias; + #endif + vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end +#endif`,Gm=`float getShadowMask() { + float shadow = 1.0; + #ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { + directionalLight = directionalLightShadows[ i ]; + shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + } + #pragma unroll_loop_end + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) { + spotLight = spotLightShadows[ i ]; + shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; + } + #pragma unroll_loop_end + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + PointLightShadow pointLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { + pointLight = pointLightShadows[ i ]; + shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0; + } + #pragma unroll_loop_end + #endif + #endif + return shadow; +}`,Wm=`#ifdef USE_SKINNING + mat4 boneMatX = getBoneMatrix( skinIndex.x ); + mat4 boneMatY = getBoneMatrix( skinIndex.y ); + mat4 boneMatZ = getBoneMatrix( skinIndex.z ); + mat4 boneMatW = getBoneMatrix( skinIndex.w ); +#endif`,Xm=`#ifdef USE_SKINNING + uniform mat4 bindMatrix; + uniform mat4 bindMatrixInverse; + uniform highp sampler2D boneTexture; + mat4 getBoneMatrix( const in float i ) { + int size = textureSize( boneTexture, 0 ).x; + int j = int( i ) * 4; + int x = j % size; + int y = j / size; + vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); + vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); + vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); + vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); + return mat4( v1, v2, v3, v4 ); + } +#endif`,qm=`#ifdef USE_SKINNING + vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); + vec4 skinned = vec4( 0.0 ); + skinned += boneMatX * skinVertex * skinWeight.x; + skinned += boneMatY * skinVertex * skinWeight.y; + skinned += boneMatZ * skinVertex * skinWeight.z; + skinned += boneMatW * skinVertex * skinWeight.w; + transformed = ( bindMatrixInverse * skinned ).xyz; +#endif`,Ym=`#ifdef USE_SKINNING + mat4 skinMatrix = mat4( 0.0 ); + skinMatrix += skinWeight.x * boneMatX; + skinMatrix += skinWeight.y * boneMatY; + skinMatrix += skinWeight.z * boneMatZ; + skinMatrix += skinWeight.w * boneMatW; + skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; + objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; + #ifdef USE_TANGENT + objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; + #endif +#endif`,Zm=`float specularStrength; +#ifdef USE_SPECULARMAP + vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); + specularStrength = texelSpecular.r; +#else + specularStrength = 1.0; +#endif`,Jm=`#ifdef USE_SPECULARMAP + uniform sampler2D specularMap; +#endif`,$m=`#if defined( TONE_MAPPING ) + gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); +#endif`,Km=`#ifndef saturate +#define saturate( a ) clamp( a, 0.0, 1.0 ) +#endif +uniform float toneMappingExposure; +vec3 LinearToneMapping( vec3 color ) { + return saturate( toneMappingExposure * color ); +} +vec3 ReinhardToneMapping( vec3 color ) { + color *= toneMappingExposure; + return saturate( color / ( vec3( 1.0 ) + color ) ); +} +vec3 CineonToneMapping( vec3 color ) { + color *= toneMappingExposure; + color = max( vec3( 0.0 ), color - 0.004 ); + return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) ); +} +vec3 RRTAndODTFit( vec3 v ) { + vec3 a = v * ( v + 0.0245786 ) - 0.000090537; + vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081; + return a / b; +} +vec3 ACESFilmicToneMapping( vec3 color ) { + const mat3 ACESInputMat = mat3( + vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ), + vec3( 0.04823, 0.01566, 0.83777 ) + ); + const mat3 ACESOutputMat = mat3( + vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ), + vec3( -0.07367, -0.00605, 1.07602 ) + ); + color *= toneMappingExposure / 0.6; + color = ACESInputMat * color; + color = RRTAndODTFit( color ); + color = ACESOutputMat * color; + return saturate( color ); +} +const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3( + vec3( 1.6605, - 0.1246, - 0.0182 ), + vec3( - 0.5876, 1.1329, - 0.1006 ), + vec3( - 0.0728, - 0.0083, 1.1187 ) +); +const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3( + vec3( 0.6274, 0.0691, 0.0164 ), + vec3( 0.3293, 0.9195, 0.0880 ), + vec3( 0.0433, 0.0113, 0.8956 ) +); +vec3 agxDefaultContrastApprox( vec3 x ) { + vec3 x2 = x * x; + vec3 x4 = x2 * x2; + return + 15.5 * x4 * x2 + - 40.14 * x4 * x + + 31.96 * x4 + - 6.868 * x2 * x + + 0.4298 * x2 + + 0.1191 * x + - 0.00232; +} +vec3 AgXToneMapping( vec3 color ) { + const mat3 AgXInsetMatrix = mat3( + vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), + vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), + vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) + ); + const mat3 AgXOutsetMatrix = mat3( + vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), + vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), + vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) + ); + const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069; + color *= toneMappingExposure; + color = LINEAR_SRGB_TO_LINEAR_REC2020 * color; + color = AgXInsetMatrix * color; + color = max( color, 1e-10 ); color = log2( color ); + color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv ); + color = clamp( color, 0.0, 1.0 ); + color = agxDefaultContrastApprox( color ); + color = AgXOutsetMatrix * color; + color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) ); + color = LINEAR_REC2020_TO_LINEAR_SRGB * color; + color = clamp( color, 0.0, 1.0 ); + return color; +} +vec3 NeutralToneMapping( vec3 color ) { + const float StartCompression = 0.8 - 0.04; + const float Desaturation = 0.15; + color *= toneMappingExposure; + float x = min( color.r, min( color.g, color.b ) ); + float offset = x < 0.08 ? x - 6.25 * x * x : 0.04; + color -= offset; + float peak = max( color.r, max( color.g, color.b ) ); + if ( peak < StartCompression ) return color; + float d = 1. - StartCompression; + float newPeak = 1. - d * d / ( peak + d - StartCompression ); + color *= newPeak / peak; + float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. ); + return mix( color, vec3( newPeak ), g ); +} +vec3 CustomToneMapping( vec3 color ) { return color; }`,jm=`#ifdef USE_TRANSMISSION + material.transmission = transmission; + material.transmissionAlpha = 1.0; + material.thickness = thickness; + material.attenuationDistance = attenuationDistance; + material.attenuationColor = attenuationColor; + #ifdef USE_TRANSMISSIONMAP + material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r; + #endif + #ifdef USE_THICKNESSMAP + material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g; + #endif + vec3 pos = vWorldPosition; + vec3 v = normalize( cameraPosition - pos ); + vec3 n = inverseTransformDirection( normal, viewMatrix ); + vec4 transmitted = getIBLVolumeRefraction( + n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90, + pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness, + material.attenuationColor, material.attenuationDistance ); + material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission ); + totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission ); +#endif`,Qm=`#ifdef USE_TRANSMISSION + uniform float transmission; + uniform float thickness; + uniform float attenuationDistance; + uniform vec3 attenuationColor; + #ifdef USE_TRANSMISSIONMAP + uniform sampler2D transmissionMap; + #endif + #ifdef USE_THICKNESSMAP + uniform sampler2D thicknessMap; + #endif + uniform vec2 transmissionSamplerSize; + uniform sampler2D transmissionSamplerMap; + uniform mat4 modelMatrix; + uniform mat4 projectionMatrix; + varying vec3 vWorldPosition; + float w0( float a ) { + return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 ); + } + float w1( float a ) { + return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 ); + } + float w2( float a ){ + return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 ); + } + float w3( float a ) { + return ( 1.0 / 6.0 ) * ( a * a * a ); + } + float g0( float a ) { + return w0( a ) + w1( a ); + } + float g1( float a ) { + return w2( a ) + w3( a ); + } + float h0( float a ) { + return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) ); + } + float h1( float a ) { + return 1.0 + w3( a ) / ( w2( a ) + w3( a ) ); + } + vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) { + uv = uv * texelSize.zw + 0.5; + vec2 iuv = floor( uv ); + vec2 fuv = fract( uv ); + float g0x = g0( fuv.x ); + float g1x = g1( fuv.x ); + float h0x = h0( fuv.x ); + float h1x = h1( fuv.x ); + float h0y = h0( fuv.y ); + float h1y = h1( fuv.y ); + vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; + vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; + vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; + vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; + return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) + + g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) ); + } + vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) { + vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) ); + vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) ); + vec2 fLodSizeInv = 1.0 / fLodSize; + vec2 cLodSizeInv = 1.0 / cLodSize; + vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) ); + vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) ); + return mix( fSample, cSample, fract( lod ) ); + } + vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) { + vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior ); + vec3 modelScale; + modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) ); + modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) ); + modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) ); + return normalize( refractionVector ) * thickness * modelScale; + } + float applyIorToRoughness( const in float roughness, const in float ior ) { + return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 ); + } + vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) { + float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior ); + return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod ); + } + vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) { + if ( isinf( attenuationDistance ) ) { + return vec3( 1.0 ); + } else { + vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance; + vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance; + } + } + vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor, + const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix, + const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness, + const in vec3 attenuationColor, const in float attenuationDistance ) { + vec4 transmittedLight; + vec3 transmittance; + #ifdef USE_DISPERSION + float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion; + vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread ); + for ( int i = 0; i < 3; i ++ ) { + vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix ); + vec3 refractedRayExit = position + transmissionRay; + vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); + vec2 refractionCoords = ndcPos.xy / ndcPos.w; + refractionCoords += 1.0; + refractionCoords /= 2.0; + vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] ); + transmittedLight[ i ] = transmissionSample[ i ]; + transmittedLight.a += transmissionSample.a; + transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ]; + } + transmittedLight.a /= 3.0; + #else + vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix ); + vec3 refractedRayExit = position + transmissionRay; + vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); + vec2 refractionCoords = ndcPos.xy / ndcPos.w; + refractionCoords += 1.0; + refractionCoords /= 2.0; + transmittedLight = getTransmissionSample( refractionCoords, roughness, ior ); + transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ); + #endif + vec3 attenuatedColor = transmittance * transmittedLight.rgb; + vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness ); + float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0; + return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor ); + } +#endif`,tg=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + varying vec2 vUv; +#endif +#ifdef USE_MAP + varying vec2 vMapUv; +#endif +#ifdef USE_ALPHAMAP + varying vec2 vAlphaMapUv; +#endif +#ifdef USE_LIGHTMAP + varying vec2 vLightMapUv; +#endif +#ifdef USE_AOMAP + varying vec2 vAoMapUv; +#endif +#ifdef USE_BUMPMAP + varying vec2 vBumpMapUv; +#endif +#ifdef USE_NORMALMAP + varying vec2 vNormalMapUv; +#endif +#ifdef USE_EMISSIVEMAP + varying vec2 vEmissiveMapUv; +#endif +#ifdef USE_METALNESSMAP + varying vec2 vMetalnessMapUv; +#endif +#ifdef USE_ROUGHNESSMAP + varying vec2 vRoughnessMapUv; +#endif +#ifdef USE_ANISOTROPYMAP + varying vec2 vAnisotropyMapUv; +#endif +#ifdef USE_CLEARCOATMAP + varying vec2 vClearcoatMapUv; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + varying vec2 vClearcoatNormalMapUv; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + varying vec2 vClearcoatRoughnessMapUv; +#endif +#ifdef USE_IRIDESCENCEMAP + varying vec2 vIridescenceMapUv; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + varying vec2 vIridescenceThicknessMapUv; +#endif +#ifdef USE_SHEEN_COLORMAP + varying vec2 vSheenColorMapUv; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + varying vec2 vSheenRoughnessMapUv; +#endif +#ifdef USE_SPECULARMAP + varying vec2 vSpecularMapUv; +#endif +#ifdef USE_SPECULAR_COLORMAP + varying vec2 vSpecularColorMapUv; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + varying vec2 vSpecularIntensityMapUv; +#endif +#ifdef USE_TRANSMISSIONMAP + uniform mat3 transmissionMapTransform; + varying vec2 vTransmissionMapUv; +#endif +#ifdef USE_THICKNESSMAP + uniform mat3 thicknessMapTransform; + varying vec2 vThicknessMapUv; +#endif`,eg=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + varying vec2 vUv; +#endif +#ifdef USE_MAP + uniform mat3 mapTransform; + varying vec2 vMapUv; +#endif +#ifdef USE_ALPHAMAP + uniform mat3 alphaMapTransform; + varying vec2 vAlphaMapUv; +#endif +#ifdef USE_LIGHTMAP + uniform mat3 lightMapTransform; + varying vec2 vLightMapUv; +#endif +#ifdef USE_AOMAP + uniform mat3 aoMapTransform; + varying vec2 vAoMapUv; +#endif +#ifdef USE_BUMPMAP + uniform mat3 bumpMapTransform; + varying vec2 vBumpMapUv; +#endif +#ifdef USE_NORMALMAP + uniform mat3 normalMapTransform; + varying vec2 vNormalMapUv; +#endif +#ifdef USE_DISPLACEMENTMAP + uniform mat3 displacementMapTransform; + varying vec2 vDisplacementMapUv; +#endif +#ifdef USE_EMISSIVEMAP + uniform mat3 emissiveMapTransform; + varying vec2 vEmissiveMapUv; +#endif +#ifdef USE_METALNESSMAP + uniform mat3 metalnessMapTransform; + varying vec2 vMetalnessMapUv; +#endif +#ifdef USE_ROUGHNESSMAP + uniform mat3 roughnessMapTransform; + varying vec2 vRoughnessMapUv; +#endif +#ifdef USE_ANISOTROPYMAP + uniform mat3 anisotropyMapTransform; + varying vec2 vAnisotropyMapUv; +#endif +#ifdef USE_CLEARCOATMAP + uniform mat3 clearcoatMapTransform; + varying vec2 vClearcoatMapUv; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + uniform mat3 clearcoatNormalMapTransform; + varying vec2 vClearcoatNormalMapUv; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + uniform mat3 clearcoatRoughnessMapTransform; + varying vec2 vClearcoatRoughnessMapUv; +#endif +#ifdef USE_SHEEN_COLORMAP + uniform mat3 sheenColorMapTransform; + varying vec2 vSheenColorMapUv; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + uniform mat3 sheenRoughnessMapTransform; + varying vec2 vSheenRoughnessMapUv; +#endif +#ifdef USE_IRIDESCENCEMAP + uniform mat3 iridescenceMapTransform; + varying vec2 vIridescenceMapUv; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + uniform mat3 iridescenceThicknessMapTransform; + varying vec2 vIridescenceThicknessMapUv; +#endif +#ifdef USE_SPECULARMAP + uniform mat3 specularMapTransform; + varying vec2 vSpecularMapUv; +#endif +#ifdef USE_SPECULAR_COLORMAP + uniform mat3 specularColorMapTransform; + varying vec2 vSpecularColorMapUv; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + uniform mat3 specularIntensityMapTransform; + varying vec2 vSpecularIntensityMapUv; +#endif +#ifdef USE_TRANSMISSIONMAP + uniform mat3 transmissionMapTransform; + varying vec2 vTransmissionMapUv; +#endif +#ifdef USE_THICKNESSMAP + uniform mat3 thicknessMapTransform; + varying vec2 vThicknessMapUv; +#endif`,ng=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + vUv = vec3( uv, 1 ).xy; +#endif +#ifdef USE_MAP + vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ALPHAMAP + vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_LIGHTMAP + vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_AOMAP + vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_BUMPMAP + vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_NORMALMAP + vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_DISPLACEMENTMAP + vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_EMISSIVEMAP + vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_METALNESSMAP + vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ROUGHNESSMAP + vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ANISOTROPYMAP + vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOATMAP + vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_IRIDESCENCEMAP + vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SHEEN_COLORMAP + vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULARMAP + vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULAR_COLORMAP + vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_TRANSMISSIONMAP + vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_THICKNESSMAP + vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy; +#endif`,ig=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0 + vec4 worldPosition = vec4( transformed, 1.0 ); + #ifdef USE_BATCHING + worldPosition = batchingMatrix * worldPosition; + #endif + #ifdef USE_INSTANCING + worldPosition = instanceMatrix * worldPosition; + #endif + worldPosition = modelMatrix * worldPosition; +#endif`,sg=`varying vec2 vUv; +uniform mat3 uvTransform; +void main() { + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; + gl_Position = vec4( position.xy, 1.0, 1.0 ); +}`,rg=`uniform sampler2D t2D; +uniform float backgroundIntensity; +varying vec2 vUv; +void main() { + vec4 texColor = texture2D( t2D, vUv ); + #ifdef DECODE_VIDEO_TEXTURE + texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w ); + #endif + texColor.rgb *= backgroundIntensity; + gl_FragColor = texColor; + #include + #include +}`,og=`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include + gl_Position.z = gl_Position.w; +}`,ag=`#ifdef ENVMAP_TYPE_CUBE + uniform samplerCube envMap; +#elif defined( ENVMAP_TYPE_CUBE_UV ) + uniform sampler2D envMap; +#endif +uniform float flipEnvMap; +uniform float backgroundBlurriness; +uniform float backgroundIntensity; +uniform mat3 backgroundRotation; +varying vec3 vWorldDirection; +#include +void main() { + #ifdef ENVMAP_TYPE_CUBE + vec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) ); + #elif defined( ENVMAP_TYPE_CUBE_UV ) + vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness ); + #else + vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + #endif + texColor.rgb *= backgroundIntensity; + gl_FragColor = texColor; + #include + #include +}`,lg=`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include + gl_Position.z = gl_Position.w; +}`,cg=`uniform samplerCube tCube; +uniform float tFlip; +uniform float opacity; +varying vec3 vWorldDirection; +void main() { + vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) ); + gl_FragColor = texColor; + gl_FragColor.a *= opacity; + #include + #include +}`,hg=`#include +#include +#include +#include +#include +#include +#include +#include +varying vec2 vHighPrecisionZW; +void main() { + #include + #include + #include + #include + #ifdef USE_DISPLACEMENTMAP + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + vHighPrecisionZW = gl_Position.zw; +}`,ug=`#if DEPTH_PACKING == 3200 + uniform float opacity; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +varying vec2 vHighPrecisionZW; +void main() { + vec4 diffuseColor = vec4( 1.0 ); + #include + #if DEPTH_PACKING == 3200 + diffuseColor.a = opacity; + #endif + #include + #include + #include + #include + #include + #ifdef USE_REVERSED_DEPTH_BUFFER + float fragCoordZ = vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ]; + #else + float fragCoordZ = 0.5 * vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ] + 0.5; + #endif + #if DEPTH_PACKING == 3200 + gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity ); + #elif DEPTH_PACKING == 3201 + gl_FragColor = packDepthToRGBA( fragCoordZ ); + #elif DEPTH_PACKING == 3202 + gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 ); + #elif DEPTH_PACKING == 3203 + gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 ); + #endif +}`,dg=`#define DISTANCE +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #ifdef USE_DISPLACEMENTMAP + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + vWorldPosition = worldPosition.xyz; +}`,fg=`#define DISTANCE +uniform vec3 referencePosition; +uniform float nearDistance; +uniform float farDistance; +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +#include +#include +void main () { + vec4 diffuseColor = vec4( 1.0 ); + #include + #include + #include + #include + #include + float dist = length( vWorldPosition - referencePosition ); + dist = ( dist - nearDistance ) / ( farDistance - nearDistance ); + dist = saturate( dist ); + gl_FragColor = packDepthToRGBA( dist ); +}`,pg=`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include +}`,mg=`uniform sampler2D tEquirect; +varying vec3 vWorldDirection; +#include +void main() { + vec3 direction = normalize( vWorldDirection ); + vec2 sampleUV = equirectUv( direction ); + gl_FragColor = texture2D( tEquirect, sampleUV ); + #include + #include +}`,gg=`uniform float scale; +attribute float lineDistance; +varying float vLineDistance; +#include +#include +#include +#include +#include +#include +#include +void main() { + vLineDistance = scale * lineDistance; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`,_g=`uniform vec3 diffuse; +uniform float opacity; +uniform float dashSize; +uniform float totalSize; +varying float vLineDistance; +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + if ( mod( vLineDistance, totalSize ) > dashSize ) { + discard; + } + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include + #include +}`,xg=`#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING ) + #include + #include + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`,yg=`uniform vec3 diffuse; +uniform float opacity; +#ifndef FLAT_SHADED + varying vec3 vNormal; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + #include + #include + #include + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + #ifdef USE_LIGHTMAP + vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); + reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI; + #else + reflectedLight.indirectDiffuse += vec3( 1.0 ); + #endif + #include + reflectedLight.indirectDiffuse *= diffuseColor.rgb; + vec3 outgoingLight = reflectedLight.indirectDiffuse; + #include + #include + #include + #include + #include + #include + #include +}`,vg=`#define LAMBERT +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include + #include +}`,Mg=`#define LAMBERT +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include + #include +}`,Sg=`#define MATCAP +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; +}`,bg=`#define MATCAP +uniform vec3 diffuse; +uniform float opacity; +uniform sampler2D matcap; +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 viewDir = normalize( vViewPosition ); + vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) ); + vec3 y = cross( viewDir, x ); + vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5; + #ifdef USE_MATCAP + vec4 matcapColor = texture2D( matcap, uv ); + #else + vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 ); + #endif + vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb; + #include + #include + #include + #include + #include + #include +}`,wg=`#define NORMAL +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + varying vec3 vViewPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + vViewPosition = - mvPosition.xyz; +#endif +}`,Eg=`#define NORMAL +uniform float opacity; +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + varying vec3 vViewPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity ); + #include + #include + #include + #include + gl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a ); + #ifdef OPAQUE + gl_FragColor.a = 1.0; + #endif +}`,Tg=`#define PHONG +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include + #include +}`,Ag=`#define PHONG +uniform vec3 diffuse; +uniform vec3 emissive; +uniform vec3 specular; +uniform float shininess; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include + #include +}`,Rg=`#define STANDARD +varying vec3 vViewPosition; +#ifdef USE_TRANSMISSION + varying vec3 vWorldPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include +#ifdef USE_TRANSMISSION + vWorldPosition = worldPosition.xyz; +#endif +}`,Cg=`#define STANDARD +#ifdef PHYSICAL + #define IOR + #define USE_SPECULAR +#endif +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float roughness; +uniform float metalness; +uniform float opacity; +#ifdef IOR + uniform float ior; +#endif +#ifdef USE_SPECULAR + uniform float specularIntensity; + uniform vec3 specularColor; + #ifdef USE_SPECULAR_COLORMAP + uniform sampler2D specularColorMap; + #endif + #ifdef USE_SPECULAR_INTENSITYMAP + uniform sampler2D specularIntensityMap; + #endif +#endif +#ifdef USE_CLEARCOAT + uniform float clearcoat; + uniform float clearcoatRoughness; +#endif +#ifdef USE_DISPERSION + uniform float dispersion; +#endif +#ifdef USE_IRIDESCENCE + uniform float iridescence; + uniform float iridescenceIOR; + uniform float iridescenceThicknessMinimum; + uniform float iridescenceThicknessMaximum; +#endif +#ifdef USE_SHEEN + uniform vec3 sheenColor; + uniform float sheenRoughness; + #ifdef USE_SHEEN_COLORMAP + uniform sampler2D sheenColorMap; + #endif + #ifdef USE_SHEEN_ROUGHNESSMAP + uniform sampler2D sheenRoughnessMap; + #endif +#endif +#ifdef USE_ANISOTROPY + uniform vec2 anisotropyVector; + #ifdef USE_ANISOTROPYMAP + uniform sampler2D anisotropyMap; + #endif +#endif +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse; + vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular; + #include + vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance; + #ifdef USE_SHEEN + float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor ); + outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect; + #endif + #ifdef USE_CLEARCOAT + float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) ); + vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc ); + outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat; + #endif + #include + #include + #include + #include + #include + #include +}`,Pg=`#define TOON +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include +}`,Ig=`#define TOON +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include +}`,Dg=`uniform float size; +uniform float scale; +#include +#include +#include +#include +#include +#include +#ifdef USE_POINTS_UV + varying vec2 vUv; + uniform mat3 uvTransform; +#endif +void main() { + #ifdef USE_POINTS_UV + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; + #endif + #include + #include + #include + #include + #include + #include + gl_PointSize = size; + #ifdef USE_SIZEATTENUATION + bool isPerspective = isPerspectiveMatrix( projectionMatrix ); + if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z ); + #endif + #include + #include + #include + #include +}`,Lg=`uniform vec3 diffuse; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include + #include +}`,Ug=`#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`,Ng=`uniform vec3 color; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) ); + #include + #include + #include +}`,Fg=`uniform float rotation; +uniform vec2 center; +#include +#include +#include +#include +#include +void main() { + #include + vec4 mvPosition = modelViewMatrix[ 3 ]; + vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) ); + #ifndef USE_SIZEATTENUATION + bool isPerspective = isPerspectiveMatrix( projectionMatrix ); + if ( isPerspective ) scale *= - mvPosition.z; + #endif + vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale; + vec2 rotatedPosition; + rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y; + rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y; + mvPosition.xy += rotatedPosition; + gl_Position = projectionMatrix * mvPosition; + #include + #include + #include +}`,Og=`uniform vec3 diffuse; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include +}`,Jt={alphahash_fragment:rp,alphahash_pars_fragment:op,alphamap_fragment:ap,alphamap_pars_fragment:lp,alphatest_fragment:cp,alphatest_pars_fragment:hp,aomap_fragment:up,aomap_pars_fragment:dp,batching_pars_vertex:fp,batching_vertex:pp,begin_vertex:mp,beginnormal_vertex:gp,bsdfs:_p,iridescence_fragment:xp,bumpmap_pars_fragment:yp,clipping_planes_fragment:vp,clipping_planes_pars_fragment:Mp,clipping_planes_pars_vertex:Sp,clipping_planes_vertex:bp,color_fragment:wp,color_pars_fragment:Ep,color_pars_vertex:Tp,color_vertex:Ap,common:Rp,cube_uv_reflection_fragment:Cp,defaultnormal_vertex:Pp,displacementmap_pars_vertex:Ip,displacementmap_vertex:Dp,emissivemap_fragment:Lp,emissivemap_pars_fragment:Up,colorspace_fragment:Np,colorspace_pars_fragment:Fp,envmap_fragment:Op,envmap_common_pars_fragment:Bp,envmap_pars_fragment:zp,envmap_pars_vertex:kp,envmap_physical_pars_fragment:Kp,envmap_vertex:Hp,fog_vertex:Vp,fog_pars_vertex:Gp,fog_fragment:Wp,fog_pars_fragment:Xp,gradientmap_pars_fragment:qp,lightmap_pars_fragment:Yp,lights_lambert_fragment:Zp,lights_lambert_pars_fragment:Jp,lights_pars_begin:$p,lights_toon_fragment:jp,lights_toon_pars_fragment:Qp,lights_phong_fragment:tm,lights_phong_pars_fragment:em,lights_physical_fragment:nm,lights_physical_pars_fragment:im,lights_fragment_begin:sm,lights_fragment_maps:rm,lights_fragment_end:om,logdepthbuf_fragment:am,logdepthbuf_pars_fragment:lm,logdepthbuf_pars_vertex:cm,logdepthbuf_vertex:hm,map_fragment:um,map_pars_fragment:dm,map_particle_fragment:fm,map_particle_pars_fragment:pm,metalnessmap_fragment:mm,metalnessmap_pars_fragment:gm,morphinstance_vertex:_m,morphcolor_vertex:xm,morphnormal_vertex:ym,morphtarget_pars_vertex:vm,morphtarget_vertex:Mm,normal_fragment_begin:Sm,normal_fragment_maps:bm,normal_pars_fragment:wm,normal_pars_vertex:Em,normal_vertex:Tm,normalmap_pars_fragment:Am,clearcoat_normal_fragment_begin:Rm,clearcoat_normal_fragment_maps:Cm,clearcoat_pars_fragment:Pm,iridescence_pars_fragment:Im,opaque_fragment:Dm,packing:Lm,premultiplied_alpha_fragment:Um,project_vertex:Nm,dithering_fragment:Fm,dithering_pars_fragment:Om,roughnessmap_fragment:Bm,roughnessmap_pars_fragment:zm,shadowmap_pars_fragment:km,shadowmap_pars_vertex:Hm,shadowmap_vertex:Vm,shadowmask_pars_fragment:Gm,skinbase_vertex:Wm,skinning_pars_vertex:Xm,skinning_vertex:qm,skinnormal_vertex:Ym,specularmap_fragment:Zm,specularmap_pars_fragment:Jm,tonemapping_fragment:$m,tonemapping_pars_fragment:Km,transmission_fragment:jm,transmission_pars_fragment:Qm,uv_pars_fragment:tg,uv_pars_vertex:eg,uv_vertex:ng,worldpos_vertex:ig,background_vert:sg,background_frag:rg,backgroundCube_vert:og,backgroundCube_frag:ag,cube_vert:lg,cube_frag:cg,depth_vert:hg,depth_frag:ug,distanceRGBA_vert:dg,distanceRGBA_frag:fg,equirect_vert:pg,equirect_frag:mg,linedashed_vert:gg,linedashed_frag:_g,meshbasic_vert:xg,meshbasic_frag:yg,meshlambert_vert:vg,meshlambert_frag:Mg,meshmatcap_vert:Sg,meshmatcap_frag:bg,meshnormal_vert:wg,meshnormal_frag:Eg,meshphong_vert:Tg,meshphong_frag:Ag,meshphysical_vert:Rg,meshphysical_frag:Cg,meshtoon_vert:Pg,meshtoon_frag:Ig,points_vert:Dg,points_frag:Lg,shadow_vert:Ug,shadow_frag:Ng,sprite_vert:Fg,sprite_frag:Og},xt={common:{diffuse:{value:new Gt(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new Wt},alphaMap:{value:null},alphaMapTransform:{value:new Wt},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new Wt}},envmap:{envMap:{value:null},envMapRotation:{value:new Wt},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new Wt}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new Wt}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new Wt},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new Wt},normalScale:{value:new ht(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new Wt},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new Wt}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new Wt}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new Wt}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new Gt(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new Gt(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new Wt},alphaTest:{value:0},uvTransform:{value:new Wt}},sprite:{diffuse:{value:new Gt(16777215)},opacity:{value:1},center:{value:new ht(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new Wt},alphaMap:{value:null},alphaMapTransform:{value:new Wt},alphaTest:{value:0}}},Un={basic:{uniforms:Be([xt.common,xt.specularmap,xt.envmap,xt.aomap,xt.lightmap,xt.fog]),vertexShader:Jt.meshbasic_vert,fragmentShader:Jt.meshbasic_frag},lambert:{uniforms:Be([xt.common,xt.specularmap,xt.envmap,xt.aomap,xt.lightmap,xt.emissivemap,xt.bumpmap,xt.normalmap,xt.displacementmap,xt.fog,xt.lights,{emissive:{value:new Gt(0)}}]),vertexShader:Jt.meshlambert_vert,fragmentShader:Jt.meshlambert_frag},phong:{uniforms:Be([xt.common,xt.specularmap,xt.envmap,xt.aomap,xt.lightmap,xt.emissivemap,xt.bumpmap,xt.normalmap,xt.displacementmap,xt.fog,xt.lights,{emissive:{value:new Gt(0)},specular:{value:new Gt(1118481)},shininess:{value:30}}]),vertexShader:Jt.meshphong_vert,fragmentShader:Jt.meshphong_frag},standard:{uniforms:Be([xt.common,xt.envmap,xt.aomap,xt.lightmap,xt.emissivemap,xt.bumpmap,xt.normalmap,xt.displacementmap,xt.roughnessmap,xt.metalnessmap,xt.fog,xt.lights,{emissive:{value:new Gt(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Jt.meshphysical_vert,fragmentShader:Jt.meshphysical_frag},toon:{uniforms:Be([xt.common,xt.aomap,xt.lightmap,xt.emissivemap,xt.bumpmap,xt.normalmap,xt.displacementmap,xt.gradientmap,xt.fog,xt.lights,{emissive:{value:new Gt(0)}}]),vertexShader:Jt.meshtoon_vert,fragmentShader:Jt.meshtoon_frag},matcap:{uniforms:Be([xt.common,xt.bumpmap,xt.normalmap,xt.displacementmap,xt.fog,{matcap:{value:null}}]),vertexShader:Jt.meshmatcap_vert,fragmentShader:Jt.meshmatcap_frag},points:{uniforms:Be([xt.points,xt.fog]),vertexShader:Jt.points_vert,fragmentShader:Jt.points_frag},dashed:{uniforms:Be([xt.common,xt.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Jt.linedashed_vert,fragmentShader:Jt.linedashed_frag},depth:{uniforms:Be([xt.common,xt.displacementmap]),vertexShader:Jt.depth_vert,fragmentShader:Jt.depth_frag},normal:{uniforms:Be([xt.common,xt.bumpmap,xt.normalmap,xt.displacementmap,{opacity:{value:1}}]),vertexShader:Jt.meshnormal_vert,fragmentShader:Jt.meshnormal_frag},sprite:{uniforms:Be([xt.sprite,xt.fog]),vertexShader:Jt.sprite_vert,fragmentShader:Jt.sprite_frag},background:{uniforms:{uvTransform:{value:new Wt},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:Jt.background_vert,fragmentShader:Jt.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new Wt}},vertexShader:Jt.backgroundCube_vert,fragmentShader:Jt.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Jt.cube_vert,fragmentShader:Jt.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Jt.equirect_vert,fragmentShader:Jt.equirect_frag},distanceRGBA:{uniforms:Be([xt.common,xt.displacementmap,{referencePosition:{value:new A},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Jt.distanceRGBA_vert,fragmentShader:Jt.distanceRGBA_frag},shadow:{uniforms:Be([xt.lights,xt.fog,{color:{value:new Gt(0)},opacity:{value:1}}]),vertexShader:Jt.shadow_vert,fragmentShader:Jt.shadow_frag}};Un.physical={uniforms:Be([Un.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new Wt},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new Wt},clearcoatNormalScale:{value:new ht(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new Wt},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new Wt},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new Wt},sheen:{value:0},sheenColor:{value:new Gt(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new Wt},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new Wt},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new Wt},transmissionSamplerSize:{value:new ht},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new Wt},attenuationDistance:{value:0},attenuationColor:{value:new Gt(0)},specularColor:{value:new Gt(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new Wt},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new Wt},anisotropyVector:{value:new ht},anisotropyMap:{value:null},anisotropyMapTransform:{value:new Wt}}]),vertexShader:Jt.meshphysical_vert,fragmentShader:Jt.meshphysical_frag};var Ua={r:0,b:0,g:0},ki=new tn,Bg=new oe;function zg(i,t,e,n,s,r,o){let a=new Gt(0),l=r===!0?0:1,c,h,u=null,d=0,p=null;function g(M){let x=M.isScene===!0?M.background:null;return x&&x.isTexture&&(x=(M.backgroundBlurriness>0?e:t).get(x)),x}function _(M){let x=!1,R=g(M);R===null?f(a,l):R&&R.isColor&&(f(R,1),x=!0);let T=i.xr.getEnvironmentBlendMode();T==="additive"?n.buffers.color.setClear(0,0,0,1,o):T==="alpha-blend"&&n.buffers.color.setClear(0,0,0,0,o),(i.autoClear||x)&&(n.buffers.depth.setTest(!0),n.buffers.depth.setMask(!0),n.buffers.color.setMask(!0),i.clear(i.autoClearColor,i.autoClearDepth,i.autoClearStencil))}function m(M,x){let R=g(x);R&&(R.isCubeTexture||R.mapping===wr)?(h===void 0&&(h=new _t(new pe(1,1,1),new Sn({name:"BackgroundCubeMaterial",uniforms:zi(Un.backgroundCube.uniforms),vertexShader:Un.backgroundCube.vertexShader,fragmentShader:Un.backgroundCube.fragmentShader,side:Ve,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),h.geometry.deleteAttribute("normal"),h.geometry.deleteAttribute("uv"),h.onBeforeRender=function(T,P,D){this.matrixWorld.copyPosition(D.matrixWorld)},Object.defineProperty(h.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),s.update(h)),ki.copy(x.backgroundRotation),ki.x*=-1,ki.y*=-1,ki.z*=-1,R.isCubeTexture&&R.isRenderTargetTexture===!1&&(ki.y*=-1,ki.z*=-1),h.material.uniforms.envMap.value=R,h.material.uniforms.flipEnvMap.value=R.isCubeTexture&&R.isRenderTargetTexture===!1?-1:1,h.material.uniforms.backgroundBlurriness.value=x.backgroundBlurriness,h.material.uniforms.backgroundIntensity.value=x.backgroundIntensity,h.material.uniforms.backgroundRotation.value.setFromMatrix4(Bg.makeRotationFromEuler(ki)),h.material.toneMapped=Qt.getTransfer(R.colorSpace)!==ne,(u!==R||d!==R.version||p!==i.toneMapping)&&(h.material.needsUpdate=!0,u=R,d=R.version,p=i.toneMapping),h.layers.enableAll(),M.unshift(h,h.geometry,h.material,0,0,null)):R&&R.isTexture&&(c===void 0&&(c=new _t(new In(2,2),new Sn({name:"BackgroundMaterial",uniforms:zi(Un.background.uniforms),vertexShader:Un.background.vertexShader,fragmentShader:Un.background.fragmentShader,side:qn,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),c.geometry.deleteAttribute("normal"),Object.defineProperty(c.material,"map",{get:function(){return this.uniforms.t2D.value}}),s.update(c)),c.material.uniforms.t2D.value=R,c.material.uniforms.backgroundIntensity.value=x.backgroundIntensity,c.material.toneMapped=Qt.getTransfer(R.colorSpace)!==ne,R.matrixAutoUpdate===!0&&R.updateMatrix(),c.material.uniforms.uvTransform.value.copy(R.matrix),(u!==R||d!==R.version||p!==i.toneMapping)&&(c.material.needsUpdate=!0,u=R,d=R.version,p=i.toneMapping),c.layers.enableAll(),M.unshift(c,c.geometry,c.material,0,0,null))}function f(M,x){M.getRGB(Ua,sc(i)),n.buffers.color.setClear(Ua.r,Ua.g,Ua.b,x,o)}function w(){h!==void 0&&(h.geometry.dispose(),h.material.dispose(),h=void 0),c!==void 0&&(c.geometry.dispose(),c.material.dispose(),c=void 0)}return{getClearColor:function(){return a},setClearColor:function(M,x=1){a.set(M),l=x,f(a,l)},getClearAlpha:function(){return l},setClearAlpha:function(M){l=M,f(a,l)},render:_,addToRenderList:m,dispose:w}}function kg(i,t){let e=i.getParameter(i.MAX_VERTEX_ATTRIBS),n={},s=d(null),r=s,o=!1;function a(v,I,F,z,k){let V=!1,G=u(z,F,I);r!==G&&(r=G,c(r.object)),V=p(v,z,F,k),V&&g(v,z,F,k),k!==null&&t.update(k,i.ELEMENT_ARRAY_BUFFER),(V||o)&&(o=!1,x(v,I,F,z),k!==null&&i.bindBuffer(i.ELEMENT_ARRAY_BUFFER,t.get(k).buffer))}function l(){return i.createVertexArray()}function c(v){return i.bindVertexArray(v)}function h(v){return i.deleteVertexArray(v)}function u(v,I,F){let z=F.wireframe===!0,k=n[v.id];k===void 0&&(k={},n[v.id]=k);let V=k[I.id];V===void 0&&(V={},k[I.id]=V);let G=V[z];return G===void 0&&(G=d(l()),V[z]=G),G}function d(v){let I=[],F=[],z=[];for(let k=0;k=0){let Z=k[W],Q=V[W];if(Q===void 0&&(W==="instanceMatrix"&&v.instanceMatrix&&(Q=v.instanceMatrix),W==="instanceColor"&&v.instanceColor&&(Q=v.instanceColor)),Z===void 0||Z.attribute!==Q||Q&&Z.data!==Q.data)return!0;G++}return r.attributesNum!==G||r.index!==z}function g(v,I,F,z){let k={},V=I.attributes,G=0,tt=F.getAttributes();for(let W in tt)if(tt[W].location>=0){let Z=V[W];Z===void 0&&(W==="instanceMatrix"&&v.instanceMatrix&&(Z=v.instanceMatrix),W==="instanceColor"&&v.instanceColor&&(Z=v.instanceColor));let Q={};Q.attribute=Z,Z&&Z.data&&(Q.data=Z.data),k[W]=Q,G++}r.attributes=k,r.attributesNum=G,r.index=z}function _(){let v=r.newAttributes;for(let I=0,F=v.length;I=0){let B=k[tt];if(B===void 0&&(tt==="instanceMatrix"&&v.instanceMatrix&&(B=v.instanceMatrix),tt==="instanceColor"&&v.instanceColor&&(B=v.instanceColor)),B!==void 0){let Z=B.normalized,Q=B.itemSize,ut=t.get(B);if(ut===void 0)continue;let Ut=ut.buffer,kt=ut.type,$t=ut.bytesPerElement,J=kt===i.INT||kt===i.UNSIGNED_INT||B.gpuType===ta;if(B.isInterleavedBufferAttribute){let rt=B.data,bt=rt.stride,Dt=B.offset;if(rt.isInstancedInterleavedBuffer){for(let Tt=0;Tt0&&i.getShaderPrecisionFormat(i.FRAGMENT_SHADER,i.HIGH_FLOAT).precision>0)return"highp";P="mediump"}return P==="mediump"&&i.getShaderPrecisionFormat(i.VERTEX_SHADER,i.MEDIUM_FLOAT).precision>0&&i.getShaderPrecisionFormat(i.FRAGMENT_SHADER,i.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let c=e.precision!==void 0?e.precision:"highp",h=l(c);h!==c&&(console.warn("THREE.WebGLRenderer:",c,"not supported, using",h,"instead."),c=h);let u=e.logarithmicDepthBuffer===!0,d=e.reversedDepthBuffer===!0&&t.has("EXT_clip_control"),p=i.getParameter(i.MAX_TEXTURE_IMAGE_UNITS),g=i.getParameter(i.MAX_VERTEX_TEXTURE_IMAGE_UNITS),_=i.getParameter(i.MAX_TEXTURE_SIZE),m=i.getParameter(i.MAX_CUBE_MAP_TEXTURE_SIZE),f=i.getParameter(i.MAX_VERTEX_ATTRIBS),w=i.getParameter(i.MAX_VERTEX_UNIFORM_VECTORS),M=i.getParameter(i.MAX_VARYING_VECTORS),x=i.getParameter(i.MAX_FRAGMENT_UNIFORM_VECTORS),R=g>0,T=i.getParameter(i.MAX_SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:r,getMaxPrecision:l,textureFormatReadable:o,textureTypeReadable:a,precision:c,logarithmicDepthBuffer:u,reversedDepthBuffer:d,maxTextures:p,maxVertexTextures:g,maxTextureSize:_,maxCubemapSize:m,maxAttributes:f,maxVertexUniforms:w,maxVaryings:M,maxFragmentUniforms:x,vertexTextures:R,maxSamples:T}}function Gg(i){let t=this,e=null,n=0,s=!1,r=!1,o=new hn,a=new Wt,l={value:null,needsUpdate:!1};this.uniform=l,this.numPlanes=0,this.numIntersection=0,this.init=function(u,d){let p=u.length!==0||d||n!==0||s;return s=d,n=u.length,p},this.beginShadows=function(){r=!0,h(null)},this.endShadows=function(){r=!1},this.setGlobalState=function(u,d){e=h(u,d,0)},this.setState=function(u,d,p){let g=u.clippingPlanes,_=u.clipIntersection,m=u.clipShadows,f=i.get(u);if(!s||g===null||g.length===0||r&&!m)r?h(null):c();else{let w=r?0:n,M=w*4,x=f.clippingState||null;l.value=x,x=h(g,d,M,p);for(let R=0;R!==M;++R)x[R]=e[R];f.clippingState=x,this.numIntersection=_?this.numPlanes:0,this.numPlanes+=w}};function c(){l.value!==e&&(l.value=e,l.needsUpdate=n>0),t.numPlanes=n,t.numIntersection=0}function h(u,d,p,g){let _=u!==null?u.length:0,m=null;if(_!==0){if(m=l.value,g!==!0||m===null){let f=p+_*4,w=d.matrixWorldInverse;a.getNormalMatrix(w),(m===null||m.length0){let c=new Mo(l.height);return c.fromEquirectangularTexture(i,o),t.set(o,c),o.addEventListener("dispose",s),e(c.texture,o.mapping)}else return null}}return o}function s(o){let a=o.target;a.removeEventListener("dispose",s);let l=t.get(a);l!==void 0&&(t.delete(a),l.dispose())}function r(){t=new WeakMap}return{get:n,dispose:r}}var Cs=4,Su=[.125,.215,.35,.446,.526,.582],Gi=20,cc=new Sr,bu=new Gt,hc=null,uc=0,dc=0,fc=!1,Vi=(1+Math.sqrt(5))/2,Rs=1/Vi,wu=[new A(-Vi,Rs,0),new A(Vi,Rs,0),new A(-Rs,0,Vi),new A(Rs,0,Vi),new A(0,Vi,-Rs),new A(0,Vi,Rs),new A(-1,1,-1),new A(1,1,-1),new A(-1,1,1),new A(1,1,1)],Xg=new A,Oa=class{constructor(t){this._renderer=t,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(t,e=0,n=.1,s=100,r={}){let{size:o=256,position:a=Xg}=r;hc=this._renderer.getRenderTarget(),uc=this._renderer.getActiveCubeFace(),dc=this._renderer.getActiveMipmapLevel(),fc=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(o);let l=this._allocateTargets();return l.depthBuffer=!0,this._sceneToCubeUV(t,n,s,l,a),e>0&&this._blur(l,0,0,e),this._applyPMREM(l),this._cleanup(l),l}fromEquirectangular(t,e=null){return this._fromTexture(t,e)}fromCubemap(t,e=null){return this._fromTexture(t,e)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=Au(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=Tu(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose()}_setSize(t){this._lodMax=Math.floor(Math.log2(t)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let t=0;t2?R:0,R,R),u.setRenderTarget(s),f&&u.render(m,l),u.render(t,l)}m.geometry.dispose(),m.material.dispose(),u.toneMapping=p,u.autoClear=d,t.background=w}_textureToCubeUV(t,e){let n=this._renderer,s=t.mapping===Fi||t.mapping===Oi;s?(this._cubemapMaterial===null&&(this._cubemapMaterial=Au()),this._cubemapMaterial.uniforms.flipEnvMap.value=t.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=Tu());let r=s?this._cubemapMaterial:this._equirectMaterial,o=new _t(this._lodPlanes[0],r),a=r.uniforms;a.envMap.value=t;let l=this._cubeSize;Na(e,0,0,3*l,2*l),n.setRenderTarget(e),n.render(o,cc)}_applyPMREM(t){let e=this._renderer,n=e.autoClear;e.autoClear=!1;let s=this._lodPlanes.length;for(let r=1;rGi&&console.warn(`sigmaRadians, ${r}, is too large and will clip, as it requested ${m} samples when the maximum is set to ${Gi}`);let f=[],w=0;for(let P=0;PM-Cs?s-M+Cs:0),T=4*(this._cubeSize-x);Na(e,R,T,3*x,2*x),l.setRenderTarget(e),l.render(u,cc)}};function qg(i){let t=[],e=[],n=[],s=i,r=i-Cs+1+Su.length;for(let o=0;oi-Cs?l=Su[o-i+Cs-1]:o===0&&(l=0),n.push(l);let c=1/(a-2),h=-c,u=1+c,d=[h,h,u,h,u,u,h,h,u,u,h,u],p=6,g=6,_=3,m=2,f=1,w=new Float32Array(_*g*p),M=new Float32Array(m*g*p),x=new Float32Array(f*g*p);for(let T=0;T2?0:-1,S=[P,D,0,P+2/3,D,0,P+2/3,D+1,0,P,D,0,P+2/3,D+1,0,P,D+1,0];w.set(S,_*g*T),M.set(d,m*g*T);let v=[T,T,T,T,T,T];x.set(v,f*g*T)}let R=new ue;R.setAttribute("position",new Fe(w,_)),R.setAttribute("uv",new Fe(M,m)),R.setAttribute("faceIndex",new Fe(x,f)),t.push(R),s>Cs&&s--}return{lodPlanes:t,sizeLods:e,sigmas:n}}function Eu(i,t,e){let n=new Cn(i,t,e);return n.texture.mapping=wr,n.texture.name="PMREM.cubeUv",n.scissorTest=!0,n}function Na(i,t,e,n,s){i.viewport.set(t,e,n,s),i.scissor.set(t,e,n,s)}function Yg(i,t,e){let n=new Float32Array(Gi),s=new A(0,1,0);return new Sn({name:"SphericalGaussianBlur",defines:{n:Gi,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/e,CUBEUV_MAX_MIP:`${i}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:n},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:s}},vertexShader:bc(),fragmentShader:` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + uniform int samples; + uniform float weights[ n ]; + uniform bool latitudinal; + uniform float dTheta; + uniform float mipInt; + uniform vec3 poleAxis; + + #define ENVMAP_TYPE_CUBE_UV + #include + + vec3 getSample( float theta, vec3 axis ) { + + float cosTheta = cos( theta ); + // Rodrigues' axis-angle rotation + vec3 sampleDirection = vOutputDirection * cosTheta + + cross( axis, vOutputDirection ) * sin( theta ) + + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); + + return bilinearCubeUV( envMap, sampleDirection, mipInt ); + + } + + void main() { + + vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); + + if ( all( equal( axis, vec3( 0.0 ) ) ) ) { + + axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); + + } + + axis = normalize( axis ); + + gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); + + for ( int i = 1; i < n; i++ ) { + + if ( i >= samples ) { + + break; + + } + + float theta = dTheta * float( i ); + gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); + gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); + + } + + } + `,blending:Kn,depthTest:!1,depthWrite:!1})}function Tu(){return new Sn({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:bc(),fragmentShader:` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + + #include + + void main() { + + vec3 outputDirection = normalize( vOutputDirection ); + vec2 uv = equirectUv( outputDirection ); + + gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); + + } + `,blending:Kn,depthTest:!1,depthWrite:!1})}function Au(){return new Sn({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:bc(),fragmentShader:` + + precision mediump float; + precision mediump int; + + uniform float flipEnvMap; + + varying vec3 vOutputDirection; + + uniform samplerCube envMap; + + void main() { + + gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); + + } + `,blending:Kn,depthTest:!1,depthWrite:!1})}function bc(){return` + + precision mediump float; + precision mediump int; + + attribute float faceIndex; + + varying vec3 vOutputDirection; + + // RH coordinate system; PMREM face-indexing convention + vec3 getDirection( vec2 uv, float face ) { + + uv = 2.0 * uv - 1.0; + + vec3 direction = vec3( uv, 1.0 ); + + if ( face == 0.0 ) { + + direction = direction.zyx; // ( 1, v, u ) pos x + + } else if ( face == 1.0 ) { + + direction = direction.xzy; + direction.xz *= -1.0; // ( -u, 1, -v ) pos y + + } else if ( face == 2.0 ) { + + direction.x *= -1.0; // ( -u, v, 1 ) pos z + + } else if ( face == 3.0 ) { + + direction = direction.zyx; + direction.xz *= -1.0; // ( -1, v, -u ) neg x + + } else if ( face == 4.0 ) { + + direction = direction.xzy; + direction.xy *= -1.0; // ( -u, -1, v ) neg y + + } else if ( face == 5.0 ) { + + direction.z *= -1.0; // ( u, v, -1 ) neg z + + } + + return direction; + + } + + void main() { + + vOutputDirection = getDirection( uv, faceIndex ); + gl_Position = vec4( position, 1.0 ); + + } + `}function Zg(i){let t=new WeakMap,e=null;function n(a){if(a&&a.isTexture){let l=a.mapping,c=l===Ko||l===jo,h=l===Fi||l===Oi;if(c||h){let u=t.get(a),d=u!==void 0?u.texture.pmremVersion:0;if(a.isRenderTargetTexture&&a.pmremVersion!==d)return e===null&&(e=new Oa(i)),u=c?e.fromEquirectangular(a,u):e.fromCubemap(a,u),u.texture.pmremVersion=a.pmremVersion,t.set(a,u),u.texture;if(u!==void 0)return u.texture;{let p=a.image;return c&&p&&p.height>0||h&&p&&s(p)?(e===null&&(e=new Oa(i)),u=c?e.fromEquirectangular(a):e.fromCubemap(a),u.texture.pmremVersion=a.pmremVersion,t.set(a,u),a.addEventListener("dispose",r),u.texture):null}}}return a}function s(a){let l=0,c=6;for(let h=0;ht.maxTextureSize&&(R=Math.ceil(x/t.maxTextureSize),x=t.maxTextureSize);let T=new Float32Array(x*R*4*u),P=new $s(T,x,R,u);P.type=Ln,P.needsUpdate=!0;let D=M*4;for(let v=0;v0)return i;let s=t*e,r=Cu[s];if(r===void 0&&(r=new Float32Array(s),Cu[s]=r),t!==0){n.toArray(r,0);for(let o=1,a=0;o!==t;++o)a+=e,i[o].toArray(r,a)}return r}function Te(i,t){if(i.length!==t.length)return!1;for(let e=0,n=i.length;e":" "} ${a}: ${e[o]}`)}return n.join(` +`)}var Fu=new Wt;function X_(i){Qt._getMatrix(Fu,Qt.workingColorSpace,i);let t=`mat3( ${Fu.elements.map(e=>e.toFixed(4))} )`;switch(Qt.getTransfer(i)){case Ys:return[t,"LinearTransferOETF"];case ne:return[t,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space: ",i),[t,"LinearTransferOETF"]}}function Ou(i,t,e){let n=i.getShaderParameter(t,i.COMPILE_STATUS),r=(i.getShaderInfoLog(t)||"").trim();if(n&&r==="")return"";let o=/ERROR: 0:(\d+)/.exec(r);if(o){let a=parseInt(o[1]);return e.toUpperCase()+` + +`+r+` + +`+W_(i.getShaderSource(t),a)}else return r}function q_(i,t){let e=X_(t);return[`vec4 ${i}( vec4 value ) {`,` return ${e[1]}( vec4( value.rgb * ${e[0]}, value.a ) );`,"}"].join(` +`)}function Y_(i,t){let e;switch(t){case $h:e="Linear";break;case Kh:e="Reinhard";break;case jh:e="Cineon";break;case $o:e="ACESFilmic";break;case tu:e="AgX";break;case eu:e="Neutral";break;case Qh:e="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",t),e="Linear"}return"vec3 "+i+"( vec3 color ) { return "+e+"ToneMapping( color ); }"}var Fa=new A;function Z_(){Qt.getLuminanceCoefficients(Fa);let i=Fa.x.toFixed(4),t=Fa.y.toFixed(4),e=Fa.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${i}, ${t}, ${e} );`," return dot( weights, rgb );","}"].join(` +`)}function J_(i){return[i.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",i.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(Pr).join(` +`)}function $_(i){let t=[];for(let e in i){let n=i[e];n!==!1&&t.push("#define "+e+" "+n)}return t.join(` +`)}function K_(i,t){let e={},n=i.getProgramParameter(t,i.ACTIVE_ATTRIBUTES);for(let s=0;s/gm;function xc(i){return i.replace(j_,t0)}var Q_=new Map;function t0(i,t){let e=Jt[t];if(e===void 0){let n=Q_.get(t);if(n!==void 0)e=Jt[n],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',t,n);else throw new Error("Can not resolve #include <"+t+">")}return xc(e)}var e0=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function ku(i){return i.replace(e0,n0)}function n0(i,t,e,n){let s="";for(let r=parseInt(t);r0&&(m+=` +`),f=["#define SHADER_TYPE "+e.shaderType,"#define SHADER_NAME "+e.shaderName,g].filter(Pr).join(` +`),f.length>0&&(f+=` +`)):(m=[Hu(e),"#define SHADER_TYPE "+e.shaderType,"#define SHADER_NAME "+e.shaderName,g,e.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",e.batching?"#define USE_BATCHING":"",e.batchingColor?"#define USE_BATCHING_COLOR":"",e.instancing?"#define USE_INSTANCING":"",e.instancingColor?"#define USE_INSTANCING_COLOR":"",e.instancingMorph?"#define USE_INSTANCING_MORPH":"",e.useFog&&e.fog?"#define USE_FOG":"",e.useFog&&e.fogExp2?"#define FOG_EXP2":"",e.map?"#define USE_MAP":"",e.envMap?"#define USE_ENVMAP":"",e.envMap?"#define "+h:"",e.lightMap?"#define USE_LIGHTMAP":"",e.aoMap?"#define USE_AOMAP":"",e.bumpMap?"#define USE_BUMPMAP":"",e.normalMap?"#define USE_NORMALMAP":"",e.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",e.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",e.displacementMap?"#define USE_DISPLACEMENTMAP":"",e.emissiveMap?"#define USE_EMISSIVEMAP":"",e.anisotropy?"#define USE_ANISOTROPY":"",e.anisotropyMap?"#define USE_ANISOTROPYMAP":"",e.clearcoatMap?"#define USE_CLEARCOATMAP":"",e.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",e.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",e.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",e.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",e.specularMap?"#define USE_SPECULARMAP":"",e.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",e.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",e.roughnessMap?"#define USE_ROUGHNESSMAP":"",e.metalnessMap?"#define USE_METALNESSMAP":"",e.alphaMap?"#define USE_ALPHAMAP":"",e.alphaHash?"#define USE_ALPHAHASH":"",e.transmission?"#define USE_TRANSMISSION":"",e.transmissionMap?"#define USE_TRANSMISSIONMAP":"",e.thicknessMap?"#define USE_THICKNESSMAP":"",e.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",e.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",e.mapUv?"#define MAP_UV "+e.mapUv:"",e.alphaMapUv?"#define ALPHAMAP_UV "+e.alphaMapUv:"",e.lightMapUv?"#define LIGHTMAP_UV "+e.lightMapUv:"",e.aoMapUv?"#define AOMAP_UV "+e.aoMapUv:"",e.emissiveMapUv?"#define EMISSIVEMAP_UV "+e.emissiveMapUv:"",e.bumpMapUv?"#define BUMPMAP_UV "+e.bumpMapUv:"",e.normalMapUv?"#define NORMALMAP_UV "+e.normalMapUv:"",e.displacementMapUv?"#define DISPLACEMENTMAP_UV "+e.displacementMapUv:"",e.metalnessMapUv?"#define METALNESSMAP_UV "+e.metalnessMapUv:"",e.roughnessMapUv?"#define ROUGHNESSMAP_UV "+e.roughnessMapUv:"",e.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+e.anisotropyMapUv:"",e.clearcoatMapUv?"#define CLEARCOATMAP_UV "+e.clearcoatMapUv:"",e.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+e.clearcoatNormalMapUv:"",e.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+e.clearcoatRoughnessMapUv:"",e.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+e.iridescenceMapUv:"",e.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+e.iridescenceThicknessMapUv:"",e.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+e.sheenColorMapUv:"",e.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+e.sheenRoughnessMapUv:"",e.specularMapUv?"#define SPECULARMAP_UV "+e.specularMapUv:"",e.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+e.specularColorMapUv:"",e.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+e.specularIntensityMapUv:"",e.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+e.transmissionMapUv:"",e.thicknessMapUv?"#define THICKNESSMAP_UV "+e.thicknessMapUv:"",e.vertexTangents&&e.flatShading===!1?"#define USE_TANGENT":"",e.vertexColors?"#define USE_COLOR":"",e.vertexAlphas?"#define USE_COLOR_ALPHA":"",e.vertexUv1s?"#define USE_UV1":"",e.vertexUv2s?"#define USE_UV2":"",e.vertexUv3s?"#define USE_UV3":"",e.pointsUvs?"#define USE_POINTS_UV":"",e.flatShading?"#define FLAT_SHADED":"",e.skinning?"#define USE_SKINNING":"",e.morphTargets?"#define USE_MORPHTARGETS":"",e.morphNormals&&e.flatShading===!1?"#define USE_MORPHNORMALS":"",e.morphColors?"#define USE_MORPHCOLORS":"",e.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+e.morphTextureStride:"",e.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+e.morphTargetsCount:"",e.doubleSided?"#define DOUBLE_SIDED":"",e.flipSided?"#define FLIP_SIDED":"",e.shadowMapEnabled?"#define USE_SHADOWMAP":"",e.shadowMapEnabled?"#define "+l:"",e.sizeAttenuation?"#define USE_SIZEATTENUATION":"",e.numLightProbes>0?"#define USE_LIGHT_PROBES":"",e.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",e.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING"," attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR"," attribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH"," uniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1"," attribute vec2 uv1;","#endif","#ifdef USE_UV2"," attribute vec2 uv2;","#endif","#ifdef USE_UV3"," attribute vec2 uv3;","#endif","#ifdef USE_TANGENT"," attribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )"," attribute vec4 color;","#elif defined( USE_COLOR )"," attribute vec3 color;","#endif","#ifdef USE_SKINNING"," attribute vec4 skinIndex;"," attribute vec4 skinWeight;","#endif",` +`].filter(Pr).join(` +`),f=[Hu(e),"#define SHADER_TYPE "+e.shaderType,"#define SHADER_NAME "+e.shaderName,g,e.useFog&&e.fog?"#define USE_FOG":"",e.useFog&&e.fogExp2?"#define FOG_EXP2":"",e.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",e.map?"#define USE_MAP":"",e.matcap?"#define USE_MATCAP":"",e.envMap?"#define USE_ENVMAP":"",e.envMap?"#define "+c:"",e.envMap?"#define "+h:"",e.envMap?"#define "+u:"",d?"#define CUBEUV_TEXEL_WIDTH "+d.texelWidth:"",d?"#define CUBEUV_TEXEL_HEIGHT "+d.texelHeight:"",d?"#define CUBEUV_MAX_MIP "+d.maxMip+".0":"",e.lightMap?"#define USE_LIGHTMAP":"",e.aoMap?"#define USE_AOMAP":"",e.bumpMap?"#define USE_BUMPMAP":"",e.normalMap?"#define USE_NORMALMAP":"",e.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",e.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",e.emissiveMap?"#define USE_EMISSIVEMAP":"",e.anisotropy?"#define USE_ANISOTROPY":"",e.anisotropyMap?"#define USE_ANISOTROPYMAP":"",e.clearcoat?"#define USE_CLEARCOAT":"",e.clearcoatMap?"#define USE_CLEARCOATMAP":"",e.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",e.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",e.dispersion?"#define USE_DISPERSION":"",e.iridescence?"#define USE_IRIDESCENCE":"",e.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",e.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",e.specularMap?"#define USE_SPECULARMAP":"",e.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",e.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",e.roughnessMap?"#define USE_ROUGHNESSMAP":"",e.metalnessMap?"#define USE_METALNESSMAP":"",e.alphaMap?"#define USE_ALPHAMAP":"",e.alphaTest?"#define USE_ALPHATEST":"",e.alphaHash?"#define USE_ALPHAHASH":"",e.sheen?"#define USE_SHEEN":"",e.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",e.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",e.transmission?"#define USE_TRANSMISSION":"",e.transmissionMap?"#define USE_TRANSMISSIONMAP":"",e.thicknessMap?"#define USE_THICKNESSMAP":"",e.vertexTangents&&e.flatShading===!1?"#define USE_TANGENT":"",e.vertexColors||e.instancingColor||e.batchingColor?"#define USE_COLOR":"",e.vertexAlphas?"#define USE_COLOR_ALPHA":"",e.vertexUv1s?"#define USE_UV1":"",e.vertexUv2s?"#define USE_UV2":"",e.vertexUv3s?"#define USE_UV3":"",e.pointsUvs?"#define USE_POINTS_UV":"",e.gradientMap?"#define USE_GRADIENTMAP":"",e.flatShading?"#define FLAT_SHADED":"",e.doubleSided?"#define DOUBLE_SIDED":"",e.flipSided?"#define FLIP_SIDED":"",e.shadowMapEnabled?"#define USE_SHADOWMAP":"",e.shadowMapEnabled?"#define "+l:"",e.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",e.numLightProbes>0?"#define USE_LIGHT_PROBES":"",e.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",e.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",e.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",e.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",e.toneMapping!==jn?"#define TONE_MAPPING":"",e.toneMapping!==jn?Jt.tonemapping_pars_fragment:"",e.toneMapping!==jn?Y_("toneMapping",e.toneMapping):"",e.dithering?"#define DITHERING":"",e.opaque?"#define OPAQUE":"",Jt.colorspace_pars_fragment,q_("linearToOutputTexel",e.outputColorSpace),Z_(),e.useDepthPacking?"#define DEPTH_PACKING "+e.depthPacking:"",` +`].filter(Pr).join(` +`)),o=xc(o),o=Bu(o,e),o=zu(o,e),a=xc(a),a=Bu(a,e),a=zu(a,e),o=ku(o),a=ku(a),e.isRawShaderMaterial!==!0&&(w=`#version 300 es +`,m=[p,"#define attribute in","#define varying out","#define texture2D texture"].join(` +`)+` +`+m,f=["#define varying in",e.glslVersion===tc?"":"layout(location = 0) out highp vec4 pc_fragColor;",e.glslVersion===tc?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join(` +`)+` +`+f);let M=w+m+o,x=w+f+a,R=Nu(s,s.VERTEX_SHADER,M),T=Nu(s,s.FRAGMENT_SHADER,x);s.attachShader(_,R),s.attachShader(_,T),e.index0AttributeName!==void 0?s.bindAttribLocation(_,0,e.index0AttributeName):e.morphTargets===!0&&s.bindAttribLocation(_,0,"position"),s.linkProgram(_);function P(I){if(i.debug.checkShaderErrors){let F=s.getProgramInfoLog(_)||"",z=s.getShaderInfoLog(R)||"",k=s.getShaderInfoLog(T)||"",V=F.trim(),G=z.trim(),tt=k.trim(),W=!0,B=!0;if(s.getProgramParameter(_,s.LINK_STATUS)===!1)if(W=!1,typeof i.debug.onShaderError=="function")i.debug.onShaderError(s,_,R,T);else{let Z=Ou(s,R,"vertex"),Q=Ou(s,T,"fragment");console.error("THREE.WebGLProgram: Shader Error "+s.getError()+" - VALIDATE_STATUS "+s.getProgramParameter(_,s.VALIDATE_STATUS)+` + +Material Name: `+I.name+` +Material Type: `+I.type+` + +Program Info Log: `+V+` +`+Z+` +`+Q)}else V!==""?console.warn("THREE.WebGLProgram: Program Info Log:",V):(G===""||tt==="")&&(B=!1);B&&(I.diagnostics={runnable:W,programLog:V,vertexShader:{log:G,prefix:m},fragmentShader:{log:tt,prefix:f}})}s.deleteShader(R),s.deleteShader(T),D=new Ps(s,_),S=K_(s,_)}let D;this.getUniforms=function(){return D===void 0&&P(this),D};let S;this.getAttributes=function(){return S===void 0&&P(this),S};let v=e.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return v===!1&&(v=s.getProgramParameter(_,V_)),v},this.destroy=function(){n.releaseStatesOfProgram(this),s.deleteProgram(_),this.program=void 0},this.type=e.shaderType,this.name=e.shaderName,this.id=G_++,this.cacheKey=t,this.usedTimes=1,this.program=_,this.vertexShader=R,this.fragmentShader=T,this}var c0=0,yc=class{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(t){let e=t.vertexShader,n=t.fragmentShader,s=this._getShaderStage(e),r=this._getShaderStage(n),o=this._getShaderCacheForMaterial(t);return o.has(s)===!1&&(o.add(s),s.usedTimes++),o.has(r)===!1&&(o.add(r),r.usedTimes++),this}remove(t){let e=this.materialCache.get(t);for(let n of e)n.usedTimes--,n.usedTimes===0&&this.shaderCache.delete(n.code);return this.materialCache.delete(t),this}getVertexShaderID(t){return this._getShaderStage(t.vertexShader).id}getFragmentShaderID(t){return this._getShaderStage(t.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(t){let e=this.materialCache,n=e.get(t);return n===void 0&&(n=new Set,e.set(t,n)),n}_getShaderStage(t){let e=this.shaderCache,n=e.get(t);return n===void 0&&(n=new vc(t),e.set(t,n)),n}},vc=class{constructor(t){this.id=c0++,this.code=t,this.usedTimes=0}};function h0(i,t,e,n,s,r,o){let a=new ms,l=new yc,c=new Set,h=[],u=s.logarithmicDepthBuffer,d=s.vertexTextures,p=s.precision,g={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function _(S){return c.add(S),S===0?"uv":`uv${S}`}function m(S,v,I,F,z){let k=F.fog,V=z.geometry,G=S.isMeshStandardMaterial?F.environment:null,tt=(S.isMeshStandardMaterial?e:t).get(S.envMap||G),W=tt&&tt.mapping===wr?tt.image.height:null,B=g[S.type];S.precision!==null&&(p=s.getMaxPrecision(S.precision),p!==S.precision&&console.warn("THREE.WebGLProgram.getParameters:",S.precision,"not supported, using",p,"instead."));let Z=V.morphAttributes.position||V.morphAttributes.normal||V.morphAttributes.color,Q=Z!==void 0?Z.length:0,ut=0;V.morphAttributes.position!==void 0&&(ut=1),V.morphAttributes.normal!==void 0&&(ut=2),V.morphAttributes.color!==void 0&&(ut=3);let Ut,kt,$t,J;if(B){let ee=Un[B];Ut=ee.vertexShader,kt=ee.fragmentShader}else Ut=S.vertexShader,kt=S.fragmentShader,l.update(S),$t=l.getVertexShaderID(S),J=l.getFragmentShaderID(S);let rt=i.getRenderTarget(),bt=i.state.buffers.depth.getReversed(),Dt=z.isInstancedMesh===!0,Tt=z.isBatchedMesh===!0,Kt=!!S.map,ce=!!S.matcap,C=!!tt,st=!!S.aoMap,et=!!S.lightMap,j=!!S.bumpMap,$=!!S.normalMap,pt=!!S.displacementMap,ot=!!S.emissiveMap,mt=!!S.metalnessMap,Ht=!!S.roughnessMap,zt=S.anisotropy>0,E=S.clearcoat>0,y=S.dispersion>0,O=S.iridescence>0,q=S.sheen>0,it=S.transmission>0,Y=zt&&!!S.anisotropyMap,Pt=E&&!!S.clearcoatMap,ft=E&&!!S.clearcoatNormalMap,At=E&&!!S.clearcoatRoughnessMap,Rt=O&&!!S.iridescenceMap,at=O&&!!S.iridescenceThicknessMap,Mt=q&&!!S.sheenColorMap,Ot=q&&!!S.sheenRoughnessMap,It=!!S.specularMap,yt=!!S.specularColorMap,qt=!!S.specularIntensityMap,L=it&&!!S.transmissionMap,dt=it&&!!S.thicknessMap,gt=!!S.gradientMap,wt=!!S.alphaMap,lt=S.alphaTest>0,nt=!!S.alphaHash,Ct=!!S.extensions,Vt=jn;S.toneMapped&&(rt===null||rt.isXRRenderTarget===!0)&&(Vt=i.toneMapping);let he={shaderID:B,shaderType:S.type,shaderName:S.name,vertexShader:Ut,fragmentShader:kt,defines:S.defines,customVertexShaderID:$t,customFragmentShaderID:J,isRawShaderMaterial:S.isRawShaderMaterial===!0,glslVersion:S.glslVersion,precision:p,batching:Tt,batchingColor:Tt&&z._colorsTexture!==null,instancing:Dt,instancingColor:Dt&&z.instanceColor!==null,instancingMorph:Dt&&z.morphTexture!==null,supportsVertexTextures:d,outputColorSpace:rt===null?i.outputColorSpace:rt.isXRRenderTarget===!0?rt.texture.colorSpace:Yn,alphaToCoverage:!!S.alphaToCoverage,map:Kt,matcap:ce,envMap:C,envMapMode:C&&tt.mapping,envMapCubeUVHeight:W,aoMap:st,lightMap:et,bumpMap:j,normalMap:$,displacementMap:d&&pt,emissiveMap:ot,normalMapObjectSpace:$&&S.normalMapType===ru,normalMapTangentSpace:$&&S.normalMapType===jl,metalnessMap:mt,roughnessMap:Ht,anisotropy:zt,anisotropyMap:Y,clearcoat:E,clearcoatMap:Pt,clearcoatNormalMap:ft,clearcoatRoughnessMap:At,dispersion:y,iridescence:O,iridescenceMap:Rt,iridescenceThicknessMap:at,sheen:q,sheenColorMap:Mt,sheenRoughnessMap:Ot,specularMap:It,specularColorMap:yt,specularIntensityMap:qt,transmission:it,transmissionMap:L,thicknessMap:dt,gradientMap:gt,opaque:S.transparent===!1&&S.blending===Pi&&S.alphaToCoverage===!1,alphaMap:wt,alphaTest:lt,alphaHash:nt,combine:S.combine,mapUv:Kt&&_(S.map.channel),aoMapUv:st&&_(S.aoMap.channel),lightMapUv:et&&_(S.lightMap.channel),bumpMapUv:j&&_(S.bumpMap.channel),normalMapUv:$&&_(S.normalMap.channel),displacementMapUv:pt&&_(S.displacementMap.channel),emissiveMapUv:ot&&_(S.emissiveMap.channel),metalnessMapUv:mt&&_(S.metalnessMap.channel),roughnessMapUv:Ht&&_(S.roughnessMap.channel),anisotropyMapUv:Y&&_(S.anisotropyMap.channel),clearcoatMapUv:Pt&&_(S.clearcoatMap.channel),clearcoatNormalMapUv:ft&&_(S.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:At&&_(S.clearcoatRoughnessMap.channel),iridescenceMapUv:Rt&&_(S.iridescenceMap.channel),iridescenceThicknessMapUv:at&&_(S.iridescenceThicknessMap.channel),sheenColorMapUv:Mt&&_(S.sheenColorMap.channel),sheenRoughnessMapUv:Ot&&_(S.sheenRoughnessMap.channel),specularMapUv:It&&_(S.specularMap.channel),specularColorMapUv:yt&&_(S.specularColorMap.channel),specularIntensityMapUv:qt&&_(S.specularIntensityMap.channel),transmissionMapUv:L&&_(S.transmissionMap.channel),thicknessMapUv:dt&&_(S.thicknessMap.channel),alphaMapUv:wt&&_(S.alphaMap.channel),vertexTangents:!!V.attributes.tangent&&($||zt),vertexColors:S.vertexColors,vertexAlphas:S.vertexColors===!0&&!!V.attributes.color&&V.attributes.color.itemSize===4,pointsUvs:z.isPoints===!0&&!!V.attributes.uv&&(Kt||wt),fog:!!k,useFog:S.fog===!0,fogExp2:!!k&&k.isFogExp2,flatShading:S.flatShading===!0&&S.wireframe===!1,sizeAttenuation:S.sizeAttenuation===!0,logarithmicDepthBuffer:u,reversedDepthBuffer:bt,skinning:z.isSkinnedMesh===!0,morphTargets:V.morphAttributes.position!==void 0,morphNormals:V.morphAttributes.normal!==void 0,morphColors:V.morphAttributes.color!==void 0,morphTargetsCount:Q,morphTextureStride:ut,numDirLights:v.directional.length,numPointLights:v.point.length,numSpotLights:v.spot.length,numSpotLightMaps:v.spotLightMap.length,numRectAreaLights:v.rectArea.length,numHemiLights:v.hemi.length,numDirLightShadows:v.directionalShadowMap.length,numPointLightShadows:v.pointShadowMap.length,numSpotLightShadows:v.spotShadowMap.length,numSpotLightShadowsWithMaps:v.numSpotLightShadowsWithMaps,numLightProbes:v.numLightProbes,numClippingPlanes:o.numPlanes,numClipIntersection:o.numIntersection,dithering:S.dithering,shadowMapEnabled:i.shadowMap.enabled&&I.length>0,shadowMapType:i.shadowMap.type,toneMapping:Vt,decodeVideoTexture:Kt&&S.map.isVideoTexture===!0&&Qt.getTransfer(S.map.colorSpace)===ne,decodeVideoTextureEmissive:ot&&S.emissiveMap.isVideoTexture===!0&&Qt.getTransfer(S.emissiveMap.colorSpace)===ne,premultipliedAlpha:S.premultipliedAlpha,doubleSided:S.side===Ge,flipSided:S.side===Ve,useDepthPacking:S.depthPacking>=0,depthPacking:S.depthPacking||0,index0AttributeName:S.index0AttributeName,extensionClipCullDistance:Ct&&S.extensions.clipCullDistance===!0&&n.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(Ct&&S.extensions.multiDraw===!0||Tt)&&n.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:n.has("KHR_parallel_shader_compile"),customProgramCacheKey:S.customProgramCacheKey()};return he.vertexUv1s=c.has(1),he.vertexUv2s=c.has(2),he.vertexUv3s=c.has(3),c.clear(),he}function f(S){let v=[];if(S.shaderID?v.push(S.shaderID):(v.push(S.customVertexShaderID),v.push(S.customFragmentShaderID)),S.defines!==void 0)for(let I in S.defines)v.push(I),v.push(S.defines[I]);return S.isRawShaderMaterial===!1&&(w(v,S),M(v,S),v.push(i.outputColorSpace)),v.push(S.customProgramCacheKey),v.join()}function w(S,v){S.push(v.precision),S.push(v.outputColorSpace),S.push(v.envMapMode),S.push(v.envMapCubeUVHeight),S.push(v.mapUv),S.push(v.alphaMapUv),S.push(v.lightMapUv),S.push(v.aoMapUv),S.push(v.bumpMapUv),S.push(v.normalMapUv),S.push(v.displacementMapUv),S.push(v.emissiveMapUv),S.push(v.metalnessMapUv),S.push(v.roughnessMapUv),S.push(v.anisotropyMapUv),S.push(v.clearcoatMapUv),S.push(v.clearcoatNormalMapUv),S.push(v.clearcoatRoughnessMapUv),S.push(v.iridescenceMapUv),S.push(v.iridescenceThicknessMapUv),S.push(v.sheenColorMapUv),S.push(v.sheenRoughnessMapUv),S.push(v.specularMapUv),S.push(v.specularColorMapUv),S.push(v.specularIntensityMapUv),S.push(v.transmissionMapUv),S.push(v.thicknessMapUv),S.push(v.combine),S.push(v.fogExp2),S.push(v.sizeAttenuation),S.push(v.morphTargetsCount),S.push(v.morphAttributeCount),S.push(v.numDirLights),S.push(v.numPointLights),S.push(v.numSpotLights),S.push(v.numSpotLightMaps),S.push(v.numHemiLights),S.push(v.numRectAreaLights),S.push(v.numDirLightShadows),S.push(v.numPointLightShadows),S.push(v.numSpotLightShadows),S.push(v.numSpotLightShadowsWithMaps),S.push(v.numLightProbes),S.push(v.shadowMapType),S.push(v.toneMapping),S.push(v.numClippingPlanes),S.push(v.numClipIntersection),S.push(v.depthPacking)}function M(S,v){a.disableAll(),v.supportsVertexTextures&&a.enable(0),v.instancing&&a.enable(1),v.instancingColor&&a.enable(2),v.instancingMorph&&a.enable(3),v.matcap&&a.enable(4),v.envMap&&a.enable(5),v.normalMapObjectSpace&&a.enable(6),v.normalMapTangentSpace&&a.enable(7),v.clearcoat&&a.enable(8),v.iridescence&&a.enable(9),v.alphaTest&&a.enable(10),v.vertexColors&&a.enable(11),v.vertexAlphas&&a.enable(12),v.vertexUv1s&&a.enable(13),v.vertexUv2s&&a.enable(14),v.vertexUv3s&&a.enable(15),v.vertexTangents&&a.enable(16),v.anisotropy&&a.enable(17),v.alphaHash&&a.enable(18),v.batching&&a.enable(19),v.dispersion&&a.enable(20),v.batchingColor&&a.enable(21),v.gradientMap&&a.enable(22),S.push(a.mask),a.disableAll(),v.fog&&a.enable(0),v.useFog&&a.enable(1),v.flatShading&&a.enable(2),v.logarithmicDepthBuffer&&a.enable(3),v.reversedDepthBuffer&&a.enable(4),v.skinning&&a.enable(5),v.morphTargets&&a.enable(6),v.morphNormals&&a.enable(7),v.morphColors&&a.enable(8),v.premultipliedAlpha&&a.enable(9),v.shadowMapEnabled&&a.enable(10),v.doubleSided&&a.enable(11),v.flipSided&&a.enable(12),v.useDepthPacking&&a.enable(13),v.dithering&&a.enable(14),v.transmission&&a.enable(15),v.sheen&&a.enable(16),v.opaque&&a.enable(17),v.pointsUvs&&a.enable(18),v.decodeVideoTexture&&a.enable(19),v.decodeVideoTextureEmissive&&a.enable(20),v.alphaToCoverage&&a.enable(21),S.push(a.mask)}function x(S){let v=g[S.type],I;if(v){let F=Un[v];I=gu.clone(F.uniforms)}else I=S.uniforms;return I}function R(S,v){let I;for(let F=0,z=h.length;F0?n.push(f):p.transparent===!0?s.push(f):e.push(f)}function l(u,d,p,g,_,m){let f=o(u,d,p,g,_,m);p.transmission>0?n.unshift(f):p.transparent===!0?s.unshift(f):e.unshift(f)}function c(u,d){e.length>1&&e.sort(u||d0),n.length>1&&n.sort(d||Vu),s.length>1&&s.sort(d||Vu)}function h(){for(let u=t,d=i.length;u=r.length?(o=new Gu,r.push(o)):o=r[s],o}function e(){i=new WeakMap}return{get:t,dispose:e}}function p0(){let i={};return{get:function(t){if(i[t.id]!==void 0)return i[t.id];let e;switch(t.type){case"DirectionalLight":e={direction:new A,color:new Gt};break;case"SpotLight":e={position:new A,direction:new A,color:new Gt,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":e={position:new A,color:new Gt,distance:0,decay:0};break;case"HemisphereLight":e={direction:new A,skyColor:new Gt,groundColor:new Gt};break;case"RectAreaLight":e={color:new Gt,position:new A,halfWidth:new A,halfHeight:new A};break}return i[t.id]=e,e}}}function m0(){let i={};return{get:function(t){if(i[t.id]!==void 0)return i[t.id];let e;switch(t.type){case"DirectionalLight":e={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new ht};break;case"SpotLight":e={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new ht};break;case"PointLight":e={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new ht,shadowCameraNear:1,shadowCameraFar:1e3};break}return i[t.id]=e,e}}}var g0=0;function _0(i,t){return(t.castShadow?2:0)-(i.castShadow?2:0)+(t.map?1:0)-(i.map?1:0)}function x0(i){let t=new p0,e=m0(),n={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let c=0;c<9;c++)n.probe.push(new A);let s=new A,r=new oe,o=new oe;function a(c){let h=0,u=0,d=0;for(let S=0;S<9;S++)n.probe[S].set(0,0,0);let p=0,g=0,_=0,m=0,f=0,w=0,M=0,x=0,R=0,T=0,P=0;c.sort(_0);for(let S=0,v=c.length;S0&&(i.has("OES_texture_float_linear")===!0?(n.rectAreaLTC1=xt.LTC_FLOAT_1,n.rectAreaLTC2=xt.LTC_FLOAT_2):(n.rectAreaLTC1=xt.LTC_HALF_1,n.rectAreaLTC2=xt.LTC_HALF_2)),n.ambient[0]=h,n.ambient[1]=u,n.ambient[2]=d;let D=n.hash;(D.directionalLength!==p||D.pointLength!==g||D.spotLength!==_||D.rectAreaLength!==m||D.hemiLength!==f||D.numDirectionalShadows!==w||D.numPointShadows!==M||D.numSpotShadows!==x||D.numSpotMaps!==R||D.numLightProbes!==P)&&(n.directional.length=p,n.spot.length=_,n.rectArea.length=m,n.point.length=g,n.hemi.length=f,n.directionalShadow.length=w,n.directionalShadowMap.length=w,n.pointShadow.length=M,n.pointShadowMap.length=M,n.spotShadow.length=x,n.spotShadowMap.length=x,n.directionalShadowMatrix.length=w,n.pointShadowMatrix.length=M,n.spotLightMatrix.length=x+R-T,n.spotLightMap.length=R,n.numSpotLightShadowsWithMaps=T,n.numLightProbes=P,D.directionalLength=p,D.pointLength=g,D.spotLength=_,D.rectAreaLength=m,D.hemiLength=f,D.numDirectionalShadows=w,D.numPointShadows=M,D.numSpotShadows=x,D.numSpotMaps=R,D.numLightProbes=P,n.version=g0++)}function l(c,h){let u=0,d=0,p=0,g=0,_=0,m=h.matrixWorldInverse;for(let f=0,w=c.length;f=o.length?(a=new Wu(i),o.push(a)):a=o[r],a}function n(){t=new WeakMap}return{get:e,dispose:n}}var v0=`void main() { + gl_Position = vec4( position, 1.0 ); +}`,M0=`uniform sampler2D shadow_pass; +uniform vec2 resolution; +uniform float radius; +#include +void main() { + const float samples = float( VSM_SAMPLES ); + float mean = 0.0; + float squared_mean = 0.0; + float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 ); + float uvStart = samples <= 1.0 ? 0.0 : - 1.0; + for ( float i = 0.0; i < samples; i ++ ) { + float uvOffset = uvStart + i * uvStride; + #ifdef HORIZONTAL_PASS + vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) ); + mean += distribution.x; + squared_mean += distribution.y * distribution.y + distribution.x * distribution.x; + #else + float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) ); + mean += depth; + squared_mean += depth * depth; + #endif + } + mean = mean / samples; + squared_mean = squared_mean / samples; + float std_dev = sqrt( squared_mean - mean * mean ); + gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) ); +}`;function S0(i,t,e){let n=new _s,s=new ht,r=new ht,o=new ve,a=new Po({depthPacking:su}),l=new Io,c={},h=e.maxTextureSize,u={[qn]:Ve,[Ve]:qn,[Ge]:Ge},d=new Sn({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new ht},radius:{value:4}},vertexShader:v0,fragmentShader:M0}),p=d.clone();p.defines.HORIZONTAL_PASS=1;let g=new ue;g.setAttribute("position",new Fe(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));let _=new _t(g,d),m=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=Bl;let f=this.type;this.render=function(T,P,D){if(m.enabled===!1||m.autoUpdate===!1&&m.needsUpdate===!1||T.length===0)return;let S=i.getRenderTarget(),v=i.getActiveCubeFace(),I=i.getActiveMipmapLevel(),F=i.state;F.setBlending(Kn),F.buffers.depth.getReversed()===!0?F.buffers.color.setClear(0,0,0,0):F.buffers.color.setClear(1,1,1,1),F.buffers.depth.setTest(!0),F.setScissorTest(!1);let z=f!==Dn&&this.type===Dn,k=f===Dn&&this.type!==Dn;for(let V=0,G=T.length;Vh||s.y>h)&&(s.x>h&&(r.x=Math.floor(h/B.x),s.x=r.x*B.x,W.mapSize.x=r.x),s.y>h&&(r.y=Math.floor(h/B.y),s.y=r.y*B.y,W.mapSize.y=r.y)),W.map===null||z===!0||k===!0){let Q=this.type!==Dn?{minFilter:un,magFilter:un}:{};W.map!==null&&W.map.dispose(),W.map=new Cn(s.x,s.y,Q),W.map.texture.name=tt.name+".shadowMap",W.camera.updateProjectionMatrix()}i.setRenderTarget(W.map),i.clear();let Z=W.getViewportCount();for(let Q=0;Q0||P.map&&P.alphaTest>0||P.alphaToCoverage===!0){let F=v.uuid,z=P.uuid,k=c[F];k===void 0&&(k={},c[F]=k);let V=k[z];V===void 0&&(V=v.clone(),k[z]=V,P.addEventListener("dispose",R)),v=V}if(v.visible=P.visible,v.wireframe=P.wireframe,S===Dn?v.side=P.shadowSide!==null?P.shadowSide:P.side:v.side=P.shadowSide!==null?P.shadowSide:u[P.side],v.alphaMap=P.alphaMap,v.alphaTest=P.alphaToCoverage===!0?.5:P.alphaTest,v.map=P.map,v.clipShadows=P.clipShadows,v.clippingPlanes=P.clippingPlanes,v.clipIntersection=P.clipIntersection,v.displacementMap=P.displacementMap,v.displacementScale=P.displacementScale,v.displacementBias=P.displacementBias,v.wireframeLinewidth=P.wireframeLinewidth,v.linewidth=P.linewidth,D.isPointLight===!0&&v.isMeshDistanceMaterial===!0){let F=i.properties.get(v);F.light=D}return v}function x(T,P,D,S,v){if(T.visible===!1)return;if(T.layers.test(P.layers)&&(T.isMesh||T.isLine||T.isPoints)&&(T.castShadow||T.receiveShadow&&v===Dn)&&(!T.frustumCulled||n.intersectsObject(T))){T.modelViewMatrix.multiplyMatrices(D.matrixWorldInverse,T.matrixWorld);let z=t.update(T),k=T.material;if(Array.isArray(k)){let V=z.groups;for(let G=0,tt=V.length;G=1):W.indexOf("OpenGL ES")!==-1&&(tt=parseFloat(/^OpenGL ES (\d)/.exec(W)[1]),G=tt>=2);let B=null,Z={},Q=i.getParameter(i.SCISSOR_BOX),ut=i.getParameter(i.VIEWPORT),Ut=new ve().fromArray(Q),kt=new ve().fromArray(ut);function $t(L,dt,gt,wt){let lt=new Uint8Array(4),nt=i.createTexture();i.bindTexture(L,nt),i.texParameteri(L,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(L,i.TEXTURE_MAG_FILTER,i.NEAREST);for(let Ct=0;Ct"u"?!1:/OculusBrowser/g.test(navigator.userAgent),c=new ht,h=new WeakMap,u,d=new WeakMap,p=!1;try{p=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function g(E,y){return p?new OffscreenCanvas(E,y):Js("canvas")}function _(E,y,O){let q=1,it=zt(E);if((it.width>O||it.height>O)&&(q=O/Math.max(it.width,it.height)),q<1)if(typeof HTMLImageElement<"u"&&E instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&E instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&E instanceof ImageBitmap||typeof VideoFrame<"u"&&E instanceof VideoFrame){let Y=Math.floor(q*it.width),Pt=Math.floor(q*it.height);u===void 0&&(u=g(Y,Pt));let ft=y?g(Y,Pt):u;return ft.width=Y,ft.height=Pt,ft.getContext("2d").drawImage(E,0,0,Y,Pt),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+it.width+"x"+it.height+") to ("+Y+"x"+Pt+")."),ft}else return"data"in E&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+it.width+"x"+it.height+")."),E;return E}function m(E){return E.generateMipmaps}function f(E){i.generateMipmap(E)}function w(E){return E.isWebGLCubeRenderTarget?i.TEXTURE_CUBE_MAP:E.isWebGL3DRenderTarget?i.TEXTURE_3D:E.isWebGLArrayRenderTarget||E.isCompressedArrayTexture?i.TEXTURE_2D_ARRAY:i.TEXTURE_2D}function M(E,y,O,q,it=!1){if(E!==null){if(i[E]!==void 0)return i[E];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+E+"'")}let Y=y;if(y===i.RED&&(O===i.FLOAT&&(Y=i.R32F),O===i.HALF_FLOAT&&(Y=i.R16F),O===i.UNSIGNED_BYTE&&(Y=i.R8)),y===i.RED_INTEGER&&(O===i.UNSIGNED_BYTE&&(Y=i.R8UI),O===i.UNSIGNED_SHORT&&(Y=i.R16UI),O===i.UNSIGNED_INT&&(Y=i.R32UI),O===i.BYTE&&(Y=i.R8I),O===i.SHORT&&(Y=i.R16I),O===i.INT&&(Y=i.R32I)),y===i.RG&&(O===i.FLOAT&&(Y=i.RG32F),O===i.HALF_FLOAT&&(Y=i.RG16F),O===i.UNSIGNED_BYTE&&(Y=i.RG8)),y===i.RG_INTEGER&&(O===i.UNSIGNED_BYTE&&(Y=i.RG8UI),O===i.UNSIGNED_SHORT&&(Y=i.RG16UI),O===i.UNSIGNED_INT&&(Y=i.RG32UI),O===i.BYTE&&(Y=i.RG8I),O===i.SHORT&&(Y=i.RG16I),O===i.INT&&(Y=i.RG32I)),y===i.RGB_INTEGER&&(O===i.UNSIGNED_BYTE&&(Y=i.RGB8UI),O===i.UNSIGNED_SHORT&&(Y=i.RGB16UI),O===i.UNSIGNED_INT&&(Y=i.RGB32UI),O===i.BYTE&&(Y=i.RGB8I),O===i.SHORT&&(Y=i.RGB16I),O===i.INT&&(Y=i.RGB32I)),y===i.RGBA_INTEGER&&(O===i.UNSIGNED_BYTE&&(Y=i.RGBA8UI),O===i.UNSIGNED_SHORT&&(Y=i.RGBA16UI),O===i.UNSIGNED_INT&&(Y=i.RGBA32UI),O===i.BYTE&&(Y=i.RGBA8I),O===i.SHORT&&(Y=i.RGBA16I),O===i.INT&&(Y=i.RGBA32I)),y===i.RGB&&(O===i.UNSIGNED_INT_5_9_9_9_REV&&(Y=i.RGB9_E5),O===i.UNSIGNED_INT_10F_11F_11F_REV&&(Y=i.R11F_G11F_B10F)),y===i.RGBA){let Pt=it?Ys:Qt.getTransfer(q);O===i.FLOAT&&(Y=i.RGBA32F),O===i.HALF_FLOAT&&(Y=i.RGBA16F),O===i.UNSIGNED_BYTE&&(Y=Pt===ne?i.SRGB8_ALPHA8:i.RGBA8),O===i.UNSIGNED_SHORT_4_4_4_4&&(Y=i.RGBA4),O===i.UNSIGNED_SHORT_5_5_5_1&&(Y=i.RGB5_A1)}return(Y===i.R16F||Y===i.R32F||Y===i.RG16F||Y===i.RG32F||Y===i.RGBA16F||Y===i.RGBA32F)&&t.get("EXT_color_buffer_float"),Y}function x(E,y){let O;return E?y===null||y===yi||y===Ts?O=i.DEPTH24_STENCIL8:y===Ln?O=i.DEPTH32F_STENCIL8:y===ws&&(O=i.DEPTH24_STENCIL8,console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):y===null||y===yi||y===Ts?O=i.DEPTH_COMPONENT24:y===Ln?O=i.DEPTH_COMPONENT32F:y===ws&&(O=i.DEPTH_COMPONENT16),O}function R(E,y){return m(E)===!0||E.isFramebufferTexture&&E.minFilter!==un&&E.minFilter!==Mn?Math.log2(Math.max(y.width,y.height))+1:E.mipmaps!==void 0&&E.mipmaps.length>0?E.mipmaps.length:E.isCompressedTexture&&Array.isArray(E.image)?y.mipmaps.length:1}function T(E){let y=E.target;y.removeEventListener("dispose",T),D(y),y.isVideoTexture&&h.delete(y)}function P(E){let y=E.target;y.removeEventListener("dispose",P),v(y)}function D(E){let y=n.get(E);if(y.__webglInit===void 0)return;let O=E.source,q=d.get(O);if(q){let it=q[y.__cacheKey];it.usedTimes--,it.usedTimes===0&&S(E),Object.keys(q).length===0&&d.delete(O)}n.remove(E)}function S(E){let y=n.get(E);i.deleteTexture(y.__webglTexture);let O=E.source,q=d.get(O);delete q[y.__cacheKey],o.memory.textures--}function v(E){let y=n.get(E);if(E.depthTexture&&(E.depthTexture.dispose(),n.remove(E.depthTexture)),E.isWebGLCubeRenderTarget)for(let q=0;q<6;q++){if(Array.isArray(y.__webglFramebuffer[q]))for(let it=0;it=s.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+E+" texture units while this GPU supports only "+s.maxTextures),I+=1,E}function k(E){let y=[];return y.push(E.wrapS),y.push(E.wrapT),y.push(E.wrapR||0),y.push(E.magFilter),y.push(E.minFilter),y.push(E.anisotropy),y.push(E.internalFormat),y.push(E.format),y.push(E.type),y.push(E.generateMipmaps),y.push(E.premultiplyAlpha),y.push(E.flipY),y.push(E.unpackAlignment),y.push(E.colorSpace),y.join()}function V(E,y){let O=n.get(E);if(E.isVideoTexture&&mt(E),E.isRenderTargetTexture===!1&&E.isExternalTexture!==!0&&E.version>0&&O.__version!==E.version){let q=E.image;if(q===null)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else if(q.complete===!1)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");else{J(O,E,y);return}}else E.isExternalTexture&&(O.__webglTexture=E.sourceTexture?E.sourceTexture:null);e.bindTexture(i.TEXTURE_2D,O.__webglTexture,i.TEXTURE0+y)}function G(E,y){let O=n.get(E);if(E.isRenderTargetTexture===!1&&E.version>0&&O.__version!==E.version){J(O,E,y);return}e.bindTexture(i.TEXTURE_2D_ARRAY,O.__webglTexture,i.TEXTURE0+y)}function tt(E,y){let O=n.get(E);if(E.isRenderTargetTexture===!1&&E.version>0&&O.__version!==E.version){J(O,E,y);return}e.bindTexture(i.TEXTURE_3D,O.__webglTexture,i.TEXTURE0+y)}function W(E,y){let O=n.get(E);if(E.version>0&&O.__version!==E.version){rt(O,E,y);return}e.bindTexture(i.TEXTURE_CUBE_MAP,O.__webglTexture,i.TEXTURE0+y)}let B={[hs]:i.REPEAT,[li]:i.CLAMP_TO_EDGE,[mo]:i.MIRRORED_REPEAT},Z={[un]:i.NEAREST,[nu]:i.NEAREST_MIPMAP_NEAREST,[Er]:i.NEAREST_MIPMAP_LINEAR,[Mn]:i.LINEAR,[Qo]:i.LINEAR_MIPMAP_NEAREST,[xi]:i.LINEAR_MIPMAP_LINEAR},Q={[ou]:i.NEVER,[du]:i.ALWAYS,[au]:i.LESS,[Ql]:i.LEQUAL,[lu]:i.EQUAL,[uu]:i.GEQUAL,[cu]:i.GREATER,[hu]:i.NOTEQUAL};function ut(E,y){if(y.type===Ln&&t.has("OES_texture_float_linear")===!1&&(y.magFilter===Mn||y.magFilter===Qo||y.magFilter===Er||y.magFilter===xi||y.minFilter===Mn||y.minFilter===Qo||y.minFilter===Er||y.minFilter===xi)&&console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),i.texParameteri(E,i.TEXTURE_WRAP_S,B[y.wrapS]),i.texParameteri(E,i.TEXTURE_WRAP_T,B[y.wrapT]),(E===i.TEXTURE_3D||E===i.TEXTURE_2D_ARRAY)&&i.texParameteri(E,i.TEXTURE_WRAP_R,B[y.wrapR]),i.texParameteri(E,i.TEXTURE_MAG_FILTER,Z[y.magFilter]),i.texParameteri(E,i.TEXTURE_MIN_FILTER,Z[y.minFilter]),y.compareFunction&&(i.texParameteri(E,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE),i.texParameteri(E,i.TEXTURE_COMPARE_FUNC,Q[y.compareFunction])),t.has("EXT_texture_filter_anisotropic")===!0){if(y.magFilter===un||y.minFilter!==Er&&y.minFilter!==xi||y.type===Ln&&t.has("OES_texture_float_linear")===!1)return;if(y.anisotropy>1||n.get(y).__currentAnisotropy){let O=t.get("EXT_texture_filter_anisotropic");i.texParameterf(E,O.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(y.anisotropy,s.getMaxAnisotropy())),n.get(y).__currentAnisotropy=y.anisotropy}}}function Ut(E,y){let O=!1;E.__webglInit===void 0&&(E.__webglInit=!0,y.addEventListener("dispose",T));let q=y.source,it=d.get(q);it===void 0&&(it={},d.set(q,it));let Y=k(y);if(Y!==E.__cacheKey){it[Y]===void 0&&(it[Y]={texture:i.createTexture(),usedTimes:0},o.memory.textures++,O=!0),it[Y].usedTimes++;let Pt=it[E.__cacheKey];Pt!==void 0&&(it[E.__cacheKey].usedTimes--,Pt.usedTimes===0&&S(y)),E.__cacheKey=Y,E.__webglTexture=it[Y].texture}return O}function kt(E,y,O){return Math.floor(Math.floor(E/O)/y)}function $t(E,y,O,q){let Y=E.updateRanges;if(Y.length===0)e.texSubImage2D(i.TEXTURE_2D,0,0,0,y.width,y.height,O,q,y.data);else{Y.sort((at,Mt)=>at.start-Mt.start);let Pt=0;for(let at=1;at0){L&&dt&&e.texStorage2D(i.TEXTURE_2D,wt,It,qt[0].width,qt[0].height);for(let lt=0,nt=qt.length;lt0){let Ct=lc(yt.width,yt.height,y.format,y.type);for(let Vt of y.layerUpdates){let he=yt.data.subarray(Vt*Ct/yt.data.BYTES_PER_ELEMENT,(Vt+1)*Ct/yt.data.BYTES_PER_ELEMENT);e.compressedTexSubImage3D(i.TEXTURE_2D_ARRAY,lt,0,0,Vt,yt.width,yt.height,1,Mt,he)}y.clearLayerUpdates()}else e.compressedTexSubImage3D(i.TEXTURE_2D_ARRAY,lt,0,0,0,yt.width,yt.height,at.depth,Mt,yt.data)}else e.compressedTexImage3D(i.TEXTURE_2D_ARRAY,lt,It,yt.width,yt.height,at.depth,0,yt.data,0,0);else console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else L?gt&&e.texSubImage3D(i.TEXTURE_2D_ARRAY,lt,0,0,0,yt.width,yt.height,at.depth,Mt,Ot,yt.data):e.texImage3D(i.TEXTURE_2D_ARRAY,lt,It,yt.width,yt.height,at.depth,0,Mt,Ot,yt.data)}else{L&&dt&&e.texStorage2D(i.TEXTURE_2D,wt,It,qt[0].width,qt[0].height);for(let lt=0,nt=qt.length;lt0){let lt=lc(at.width,at.height,y.format,y.type);for(let nt of y.layerUpdates){let Ct=at.data.subarray(nt*lt/at.data.BYTES_PER_ELEMENT,(nt+1)*lt/at.data.BYTES_PER_ELEMENT);e.texSubImage3D(i.TEXTURE_2D_ARRAY,0,0,0,nt,at.width,at.height,1,Mt,Ot,Ct)}y.clearLayerUpdates()}else e.texSubImage3D(i.TEXTURE_2D_ARRAY,0,0,0,0,at.width,at.height,at.depth,Mt,Ot,at.data)}else e.texImage3D(i.TEXTURE_2D_ARRAY,0,It,at.width,at.height,at.depth,0,Mt,Ot,at.data);else if(y.isData3DTexture)L?(dt&&e.texStorage3D(i.TEXTURE_3D,wt,It,at.width,at.height,at.depth),gt&&e.texSubImage3D(i.TEXTURE_3D,0,0,0,0,at.width,at.height,at.depth,Mt,Ot,at.data)):e.texImage3D(i.TEXTURE_3D,0,It,at.width,at.height,at.depth,0,Mt,Ot,at.data);else if(y.isFramebufferTexture){if(dt)if(L)e.texStorage2D(i.TEXTURE_2D,wt,It,at.width,at.height);else{let lt=at.width,nt=at.height;for(let Ct=0;Ct>=1,nt>>=1}}else if(qt.length>0){if(L&&dt){let lt=zt(qt[0]);e.texStorage2D(i.TEXTURE_2D,wt,It,lt.width,lt.height)}for(let lt=0,nt=qt.length;lt0&&wt++;let nt=zt(Mt[0]);e.texStorage2D(i.TEXTURE_CUBE_MAP,wt,qt,nt.width,nt.height)}for(let nt=0;nt<6;nt++)if(at){L?gt&&e.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+nt,0,0,0,Mt[nt].width,Mt[nt].height,It,yt,Mt[nt].data):e.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+nt,0,qt,Mt[nt].width,Mt[nt].height,0,It,yt,Mt[nt].data);for(let Ct=0;Ct>Y),Ot=Math.max(1,y.height>>Y);it===i.TEXTURE_3D||it===i.TEXTURE_2D_ARRAY?e.texImage3D(it,Y,At,Mt,Ot,y.depth,0,Pt,ft,null):e.texImage2D(it,Y,At,Mt,Ot,0,Pt,ft,null)}e.bindFramebuffer(i.FRAMEBUFFER,E),ot(y)?a.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER,q,it,at.__webglTexture,0,pt(y)):(it===i.TEXTURE_2D||it>=i.TEXTURE_CUBE_MAP_POSITIVE_X&&it<=i.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&i.framebufferTexture2D(i.FRAMEBUFFER,q,it,at.__webglTexture,Y),e.bindFramebuffer(i.FRAMEBUFFER,null)}function Dt(E,y,O){if(i.bindRenderbuffer(i.RENDERBUFFER,E),y.depthBuffer){let q=y.depthTexture,it=q&&q.isDepthTexture?q.type:null,Y=x(y.stencilBuffer,it),Pt=y.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,ft=pt(y);ot(y)?a.renderbufferStorageMultisampleEXT(i.RENDERBUFFER,ft,Y,y.width,y.height):O?i.renderbufferStorageMultisample(i.RENDERBUFFER,ft,Y,y.width,y.height):i.renderbufferStorage(i.RENDERBUFFER,Y,y.width,y.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,Pt,i.RENDERBUFFER,E)}else{let q=y.textures;for(let it=0;it{delete y.__boundDepthTexture,delete y.__depthDisposeCallback,q.removeEventListener("dispose",it)};q.addEventListener("dispose",it),y.__depthDisposeCallback=it}y.__boundDepthTexture=q}if(E.depthTexture&&!y.__autoAllocateDepthBuffer){if(O)throw new Error("target.depthTexture not supported in Cube render targets");let q=E.texture.mipmaps;q&&q.length>0?Tt(y.__webglFramebuffer[0],E):Tt(y.__webglFramebuffer,E)}else if(O){y.__webglDepthbuffer=[];for(let q=0;q<6;q++)if(e.bindFramebuffer(i.FRAMEBUFFER,y.__webglFramebuffer[q]),y.__webglDepthbuffer[q]===void 0)y.__webglDepthbuffer[q]=i.createRenderbuffer(),Dt(y.__webglDepthbuffer[q],E,!1);else{let it=E.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,Y=y.__webglDepthbuffer[q];i.bindRenderbuffer(i.RENDERBUFFER,Y),i.framebufferRenderbuffer(i.FRAMEBUFFER,it,i.RENDERBUFFER,Y)}}else{let q=E.texture.mipmaps;if(q&&q.length>0?e.bindFramebuffer(i.FRAMEBUFFER,y.__webglFramebuffer[0]):e.bindFramebuffer(i.FRAMEBUFFER,y.__webglFramebuffer),y.__webglDepthbuffer===void 0)y.__webglDepthbuffer=i.createRenderbuffer(),Dt(y.__webglDepthbuffer,E,!1);else{let it=E.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,Y=y.__webglDepthbuffer;i.bindRenderbuffer(i.RENDERBUFFER,Y),i.framebufferRenderbuffer(i.FRAMEBUFFER,it,i.RENDERBUFFER,Y)}}e.bindFramebuffer(i.FRAMEBUFFER,null)}function ce(E,y,O){let q=n.get(E);y!==void 0&&bt(q.__webglFramebuffer,E,E.texture,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,0),O!==void 0&&Kt(E)}function C(E){let y=E.texture,O=n.get(E),q=n.get(y);E.addEventListener("dispose",P);let it=E.textures,Y=E.isWebGLCubeRenderTarget===!0,Pt=it.length>1;if(Pt||(q.__webglTexture===void 0&&(q.__webglTexture=i.createTexture()),q.__version=y.version,o.memory.textures++),Y){O.__webglFramebuffer=[];for(let ft=0;ft<6;ft++)if(y.mipmaps&&y.mipmaps.length>0){O.__webglFramebuffer[ft]=[];for(let At=0;At0){O.__webglFramebuffer=[];for(let ft=0;ft0&&ot(E)===!1){O.__webglMultisampledFramebuffer=i.createFramebuffer(),O.__webglColorRenderbuffer=[],e.bindFramebuffer(i.FRAMEBUFFER,O.__webglMultisampledFramebuffer);for(let ft=0;ft0)for(let At=0;At0)for(let At=0;At0){if(ot(E)===!1){let y=E.textures,O=E.width,q=E.height,it=i.COLOR_BUFFER_BIT,Y=E.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,Pt=n.get(E),ft=y.length>1;if(ft)for(let Rt=0;Rt0?e.bindFramebuffer(i.DRAW_FRAMEBUFFER,Pt.__webglFramebuffer[0]):e.bindFramebuffer(i.DRAW_FRAMEBUFFER,Pt.__webglFramebuffer);for(let Rt=0;Rt0&&t.has("WEBGL_multisampled_render_to_texture")===!0&&y.__useRenderToTexture!==!1}function mt(E){let y=o.render.frame;h.get(E)!==y&&(h.set(E,y),E.update())}function Ht(E,y){let O=E.colorSpace,q=E.format,it=E.type;return E.isCompressedTexture===!0||E.isVideoTexture===!0||O!==Yn&&O!==Qn&&(Qt.getTransfer(O)===ne?(q!==dn||it!==En)&&console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",O)),y}function zt(E){return typeof HTMLImageElement<"u"&&E instanceof HTMLImageElement?(c.width=E.naturalWidth||E.width,c.height=E.naturalHeight||E.height):typeof VideoFrame<"u"&&E instanceof VideoFrame?(c.width=E.displayWidth,c.height=E.displayHeight):(c.width=E.width,c.height=E.height),c}this.allocateTextureUnit=z,this.resetTextureUnits=F,this.setTexture2D=V,this.setTexture2DArray=G,this.setTexture3D=tt,this.setTextureCube=W,this.rebindTextures=ce,this.setupRenderTarget=C,this.updateRenderTargetMipmap=st,this.updateMultisampleRenderTarget=$,this.setupDepthRenderbuffer=Kt,this.setupFrameBufferTexture=bt,this.useMultisampledRTT=ot}function T0(i,t){function e(n,s=Qn){let r,o=Qt.getTransfer(s);if(n===En)return i.UNSIGNED_BYTE;if(n===ea)return i.UNSIGNED_SHORT_4_4_4_4;if(n===na)return i.UNSIGNED_SHORT_5_5_5_1;if(n===ql)return i.UNSIGNED_INT_5_9_9_9_REV;if(n===Yl)return i.UNSIGNED_INT_10F_11F_11F_REV;if(n===Wl)return i.BYTE;if(n===Xl)return i.SHORT;if(n===ws)return i.UNSIGNED_SHORT;if(n===ta)return i.INT;if(n===yi)return i.UNSIGNED_INT;if(n===Ln)return i.FLOAT;if(n===Es)return i.HALF_FLOAT;if(n===Zl)return i.ALPHA;if(n===Jl)return i.RGB;if(n===dn)return i.RGBA;if(n===us)return i.DEPTH_COMPONENT;if(n===As)return i.DEPTH_STENCIL;if(n===$l)return i.RED;if(n===ia)return i.RED_INTEGER;if(n===Kl)return i.RG;if(n===sa)return i.RG_INTEGER;if(n===ra)return i.RGBA_INTEGER;if(n===Tr||n===Ar||n===Rr||n===Cr)if(o===ne)if(r=t.get("WEBGL_compressed_texture_s3tc_srgb"),r!==null){if(n===Tr)return r.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(n===Ar)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(n===Rr)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(n===Cr)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(r=t.get("WEBGL_compressed_texture_s3tc"),r!==null){if(n===Tr)return r.COMPRESSED_RGB_S3TC_DXT1_EXT;if(n===Ar)return r.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(n===Rr)return r.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(n===Cr)return r.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(n===oa||n===aa||n===la||n===ca)if(r=t.get("WEBGL_compressed_texture_pvrtc"),r!==null){if(n===oa)return r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(n===aa)return r.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(n===la)return r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(n===ca)return r.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(n===ha||n===ua||n===da)if(r=t.get("WEBGL_compressed_texture_etc"),r!==null){if(n===ha||n===ua)return o===ne?r.COMPRESSED_SRGB8_ETC2:r.COMPRESSED_RGB8_ETC2;if(n===da)return o===ne?r.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:r.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(n===fa||n===pa||n===ma||n===ga||n===_a||n===xa||n===ya||n===va||n===Ma||n===Sa||n===ba||n===wa||n===Ea||n===Ta)if(r=t.get("WEBGL_compressed_texture_astc"),r!==null){if(n===fa)return o===ne?r.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:r.COMPRESSED_RGBA_ASTC_4x4_KHR;if(n===pa)return o===ne?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:r.COMPRESSED_RGBA_ASTC_5x4_KHR;if(n===ma)return o===ne?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:r.COMPRESSED_RGBA_ASTC_5x5_KHR;if(n===ga)return o===ne?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:r.COMPRESSED_RGBA_ASTC_6x5_KHR;if(n===_a)return o===ne?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:r.COMPRESSED_RGBA_ASTC_6x6_KHR;if(n===xa)return o===ne?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:r.COMPRESSED_RGBA_ASTC_8x5_KHR;if(n===ya)return o===ne?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:r.COMPRESSED_RGBA_ASTC_8x6_KHR;if(n===va)return o===ne?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:r.COMPRESSED_RGBA_ASTC_8x8_KHR;if(n===Ma)return o===ne?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:r.COMPRESSED_RGBA_ASTC_10x5_KHR;if(n===Sa)return o===ne?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:r.COMPRESSED_RGBA_ASTC_10x6_KHR;if(n===ba)return o===ne?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:r.COMPRESSED_RGBA_ASTC_10x8_KHR;if(n===wa)return o===ne?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:r.COMPRESSED_RGBA_ASTC_10x10_KHR;if(n===Ea)return o===ne?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:r.COMPRESSED_RGBA_ASTC_12x10_KHR;if(n===Ta)return o===ne?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:r.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(n===Aa||n===Ra||n===Ca)if(r=t.get("EXT_texture_compression_bptc"),r!==null){if(n===Aa)return o===ne?r.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:r.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(n===Ra)return r.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(n===Ca)return r.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(n===Pa||n===Ia||n===Da||n===La)if(r=t.get("EXT_texture_compression_rgtc"),r!==null){if(n===Pa)return r.COMPRESSED_RED_RGTC1_EXT;if(n===Ia)return r.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(n===Da)return r.COMPRESSED_RED_GREEN_RGTC2_EXT;if(n===La)return r.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return n===Ts?i.UNSIGNED_INT_24_8:i[n]!==void 0?i[n]:null}return{convert:e}}var A0=` +void main() { + + gl_Position = vec4( position, 1.0 ); + +}`,R0=` +uniform sampler2DArray depthColor; +uniform float depthWidth; +uniform float depthHeight; + +void main() { + + vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight ); + + if ( coord.x >= 1.0 ) { + + gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r; + + } else { + + gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r; + + } + +}`,Mc=class{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(t,e){if(this.texture===null){let n=new or(t.texture);(t.depthNear!==e.depthNear||t.depthFar!==e.depthFar)&&(this.depthNear=t.depthNear,this.depthFar=t.depthFar),this.texture=n}}getMesh(t){if(this.texture!==null&&this.mesh===null){let e=t.cameras[0].viewport,n=new Sn({vertexShader:A0,fragmentShader:R0,uniforms:{depthColor:{value:this.texture},depthWidth:{value:e.z},depthHeight:{value:e.w}}});this.mesh=new _t(new In(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}},Sc=class extends Rn{constructor(t,e){super();let n=this,s=null,r=1,o=null,a="local-floor",l=1,c=null,h=null,u=null,d=null,p=null,g=null,_=typeof XRWebGLBinding<"u",m=new Mc,f={},w=e.getContextAttributes(),M=null,x=null,R=[],T=[],P=new ht,D=null,S=new Ne;S.viewport=new ve;let v=new Ne;v.viewport=new ve;let I=[S,v],F=new Ho,z=null,k=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(J){let rt=R[J];return rt===void 0&&(rt=new gs,R[J]=rt),rt.getTargetRaySpace()},this.getControllerGrip=function(J){let rt=R[J];return rt===void 0&&(rt=new gs,R[J]=rt),rt.getGripSpace()},this.getHand=function(J){let rt=R[J];return rt===void 0&&(rt=new gs,R[J]=rt),rt.getHandSpace()};function V(J){let rt=T.indexOf(J.inputSource);if(rt===-1)return;let bt=R[rt];bt!==void 0&&(bt.update(J.inputSource,J.frame,c||o),bt.dispatchEvent({type:J.type,data:J.inputSource}))}function G(){s.removeEventListener("select",V),s.removeEventListener("selectstart",V),s.removeEventListener("selectend",V),s.removeEventListener("squeeze",V),s.removeEventListener("squeezestart",V),s.removeEventListener("squeezeend",V),s.removeEventListener("end",G),s.removeEventListener("inputsourceschange",tt);for(let J=0;J=0&&(T[Dt]=null,R[Dt].disconnect(bt))}for(let rt=0;rt=T.length){T.push(bt),Dt=Kt;break}else if(T[Kt]===null){T[Kt]=bt,Dt=Kt;break}if(Dt===-1)break}let Tt=R[Dt];Tt&&Tt.connect(bt)}}let W=new A,B=new A;function Z(J,rt,bt){W.setFromMatrixPosition(rt.matrixWorld),B.setFromMatrixPosition(bt.matrixWorld);let Dt=W.distanceTo(B),Tt=rt.projectionMatrix.elements,Kt=bt.projectionMatrix.elements,ce=Tt[14]/(Tt[10]-1),C=Tt[14]/(Tt[10]+1),st=(Tt[9]+1)/Tt[5],et=(Tt[9]-1)/Tt[5],j=(Tt[8]-1)/Tt[0],$=(Kt[8]+1)/Kt[0],pt=ce*j,ot=ce*$,mt=Dt/(-j+$),Ht=mt*-j;if(rt.matrixWorld.decompose(J.position,J.quaternion,J.scale),J.translateX(Ht),J.translateZ(mt),J.matrixWorld.compose(J.position,J.quaternion,J.scale),J.matrixWorldInverse.copy(J.matrixWorld).invert(),Tt[10]===-1)J.projectionMatrix.copy(rt.projectionMatrix),J.projectionMatrixInverse.copy(rt.projectionMatrixInverse);else{let zt=ce+mt,E=C+mt,y=pt-Ht,O=ot+(Dt-Ht),q=st*C/E*zt,it=et*C/E*zt;J.projectionMatrix.makePerspective(y,O,q,it,zt,E),J.projectionMatrixInverse.copy(J.projectionMatrix).invert()}}function Q(J,rt){rt===null?J.matrixWorld.copy(J.matrix):J.matrixWorld.multiplyMatrices(rt.matrixWorld,J.matrix),J.matrixWorldInverse.copy(J.matrixWorld).invert()}this.updateCamera=function(J){if(s===null)return;let rt=J.near,bt=J.far;m.texture!==null&&(m.depthNear>0&&(rt=m.depthNear),m.depthFar>0&&(bt=m.depthFar)),F.near=v.near=S.near=rt,F.far=v.far=S.far=bt,(z!==F.near||k!==F.far)&&(s.updateRenderState({depthNear:F.near,depthFar:F.far}),z=F.near,k=F.far),F.layers.mask=J.layers.mask|6,S.layers.mask=F.layers.mask&3,v.layers.mask=F.layers.mask&5;let Dt=J.parent,Tt=F.cameras;Q(F,Dt);for(let Kt=0;Kt0&&(m.alphaTest.value=f.alphaTest);let w=t.get(f),M=w.envMap,x=w.envMapRotation;M&&(m.envMap.value=M,Hi.copy(x),Hi.x*=-1,Hi.y*=-1,Hi.z*=-1,M.isCubeTexture&&M.isRenderTargetTexture===!1&&(Hi.y*=-1,Hi.z*=-1),m.envMapRotation.value.setFromMatrix4(C0.makeRotationFromEuler(Hi)),m.flipEnvMap.value=M.isCubeTexture&&M.isRenderTargetTexture===!1?-1:1,m.reflectivity.value=f.reflectivity,m.ior.value=f.ior,m.refractionRatio.value=f.refractionRatio),f.lightMap&&(m.lightMap.value=f.lightMap,m.lightMapIntensity.value=f.lightMapIntensity,e(f.lightMap,m.lightMapTransform)),f.aoMap&&(m.aoMap.value=f.aoMap,m.aoMapIntensity.value=f.aoMapIntensity,e(f.aoMap,m.aoMapTransform))}function o(m,f){m.diffuse.value.copy(f.color),m.opacity.value=f.opacity,f.map&&(m.map.value=f.map,e(f.map,m.mapTransform))}function a(m,f){m.dashSize.value=f.dashSize,m.totalSize.value=f.dashSize+f.gapSize,m.scale.value=f.scale}function l(m,f,w,M){m.diffuse.value.copy(f.color),m.opacity.value=f.opacity,m.size.value=f.size*w,m.scale.value=M*.5,f.map&&(m.map.value=f.map,e(f.map,m.uvTransform)),f.alphaMap&&(m.alphaMap.value=f.alphaMap,e(f.alphaMap,m.alphaMapTransform)),f.alphaTest>0&&(m.alphaTest.value=f.alphaTest)}function c(m,f){m.diffuse.value.copy(f.color),m.opacity.value=f.opacity,m.rotation.value=f.rotation,f.map&&(m.map.value=f.map,e(f.map,m.mapTransform)),f.alphaMap&&(m.alphaMap.value=f.alphaMap,e(f.alphaMap,m.alphaMapTransform)),f.alphaTest>0&&(m.alphaTest.value=f.alphaTest)}function h(m,f){m.specular.value.copy(f.specular),m.shininess.value=Math.max(f.shininess,1e-4)}function u(m,f){f.gradientMap&&(m.gradientMap.value=f.gradientMap)}function d(m,f){m.metalness.value=f.metalness,f.metalnessMap&&(m.metalnessMap.value=f.metalnessMap,e(f.metalnessMap,m.metalnessMapTransform)),m.roughness.value=f.roughness,f.roughnessMap&&(m.roughnessMap.value=f.roughnessMap,e(f.roughnessMap,m.roughnessMapTransform)),f.envMap&&(m.envMapIntensity.value=f.envMapIntensity)}function p(m,f,w){m.ior.value=f.ior,f.sheen>0&&(m.sheenColor.value.copy(f.sheenColor).multiplyScalar(f.sheen),m.sheenRoughness.value=f.sheenRoughness,f.sheenColorMap&&(m.sheenColorMap.value=f.sheenColorMap,e(f.sheenColorMap,m.sheenColorMapTransform)),f.sheenRoughnessMap&&(m.sheenRoughnessMap.value=f.sheenRoughnessMap,e(f.sheenRoughnessMap,m.sheenRoughnessMapTransform))),f.clearcoat>0&&(m.clearcoat.value=f.clearcoat,m.clearcoatRoughness.value=f.clearcoatRoughness,f.clearcoatMap&&(m.clearcoatMap.value=f.clearcoatMap,e(f.clearcoatMap,m.clearcoatMapTransform)),f.clearcoatRoughnessMap&&(m.clearcoatRoughnessMap.value=f.clearcoatRoughnessMap,e(f.clearcoatRoughnessMap,m.clearcoatRoughnessMapTransform)),f.clearcoatNormalMap&&(m.clearcoatNormalMap.value=f.clearcoatNormalMap,e(f.clearcoatNormalMap,m.clearcoatNormalMapTransform),m.clearcoatNormalScale.value.copy(f.clearcoatNormalScale),f.side===Ve&&m.clearcoatNormalScale.value.negate())),f.dispersion>0&&(m.dispersion.value=f.dispersion),f.iridescence>0&&(m.iridescence.value=f.iridescence,m.iridescenceIOR.value=f.iridescenceIOR,m.iridescenceThicknessMinimum.value=f.iridescenceThicknessRange[0],m.iridescenceThicknessMaximum.value=f.iridescenceThicknessRange[1],f.iridescenceMap&&(m.iridescenceMap.value=f.iridescenceMap,e(f.iridescenceMap,m.iridescenceMapTransform)),f.iridescenceThicknessMap&&(m.iridescenceThicknessMap.value=f.iridescenceThicknessMap,e(f.iridescenceThicknessMap,m.iridescenceThicknessMapTransform))),f.transmission>0&&(m.transmission.value=f.transmission,m.transmissionSamplerMap.value=w.texture,m.transmissionSamplerSize.value.set(w.width,w.height),f.transmissionMap&&(m.transmissionMap.value=f.transmissionMap,e(f.transmissionMap,m.transmissionMapTransform)),m.thickness.value=f.thickness,f.thicknessMap&&(m.thicknessMap.value=f.thicknessMap,e(f.thicknessMap,m.thicknessMapTransform)),m.attenuationDistance.value=f.attenuationDistance,m.attenuationColor.value.copy(f.attenuationColor)),f.anisotropy>0&&(m.anisotropyVector.value.set(f.anisotropy*Math.cos(f.anisotropyRotation),f.anisotropy*Math.sin(f.anisotropyRotation)),f.anisotropyMap&&(m.anisotropyMap.value=f.anisotropyMap,e(f.anisotropyMap,m.anisotropyMapTransform))),m.specularIntensity.value=f.specularIntensity,m.specularColor.value.copy(f.specularColor),f.specularColorMap&&(m.specularColorMap.value=f.specularColorMap,e(f.specularColorMap,m.specularColorMapTransform)),f.specularIntensityMap&&(m.specularIntensityMap.value=f.specularIntensityMap,e(f.specularIntensityMap,m.specularIntensityMapTransform))}function g(m,f){f.matcap&&(m.matcap.value=f.matcap)}function _(m,f){let w=t.get(f).light;m.referencePosition.value.setFromMatrixPosition(w.matrixWorld),m.nearDistance.value=w.shadow.camera.near,m.farDistance.value=w.shadow.camera.far}return{refreshFogUniforms:n,refreshMaterialUniforms:s}}function I0(i,t,e,n){let s={},r={},o=[],a=i.getParameter(i.MAX_UNIFORM_BUFFER_BINDINGS);function l(w,M){let x=M.program;n.uniformBlockBinding(w,x)}function c(w,M){let x=s[w.id];x===void 0&&(g(w),x=h(w),s[w.id]=x,w.addEventListener("dispose",m));let R=M.program;n.updateUBOMapping(w,R);let T=t.render.frame;r[w.id]!==T&&(d(w),r[w.id]=T)}function h(w){let M=u();w.__bindingPointIndex=M;let x=i.createBuffer(),R=w.__size,T=w.usage;return i.bindBuffer(i.UNIFORM_BUFFER,x),i.bufferData(i.UNIFORM_BUFFER,R,T),i.bindBuffer(i.UNIFORM_BUFFER,null),i.bindBufferBase(i.UNIFORM_BUFFER,M,x),x}function u(){for(let w=0;w0&&(x+=R-T),w.__size=x,w.__cache={},this}function _(w){let M={boundary:0,storage:0};return typeof w=="number"||typeof w=="boolean"?(M.boundary=4,M.storage=4):w.isVector2?(M.boundary=8,M.storage=8):w.isVector3||w.isColor?(M.boundary=16,M.storage=12):w.isVector4?(M.boundary=16,M.storage=16):w.isMatrix3?(M.boundary=48,M.storage=48):w.isMatrix4?(M.boundary=64,M.storage=64):w.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",w),M}function m(w){let M=w.target;M.removeEventListener("dispose",m);let x=o.indexOf(M.__bindingPointIndex);o.splice(x,1),i.deleteBuffer(s[M.id]),delete s[M.id],delete r[M.id]}function f(){for(let w in s)i.deleteBuffer(s[w]);o=[],s={},r={}}return{bind:l,update:c,dispose:f}}var Ba=class{constructor(t={}){let{canvas:e=fu(),context:n=null,depth:s=!0,stencil:r=!1,alpha:o=!1,antialias:a=!1,premultipliedAlpha:l=!0,preserveDrawingBuffer:c=!1,powerPreference:h="default",failIfMajorPerformanceCaveat:u=!1,reversedDepthBuffer:d=!1}=t;this.isWebGLRenderer=!0;let p;if(n!==null){if(typeof WebGLRenderingContext<"u"&&n instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");p=n.getContextAttributes().alpha}else p=o;let g=new Uint32Array(4),_=new Int32Array(4),m=null,f=null,w=[],M=[];this.domElement=e,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=jn,this.toneMappingExposure=1,this.transmissionResolutionScale=1;let x=this,R=!1;this._outputColorSpace=De;let T=0,P=0,D=null,S=-1,v=null,I=new ve,F=new ve,z=null,k=new Gt(0),V=0,G=e.width,tt=e.height,W=1,B=null,Z=null,Q=new ve(0,0,G,tt),ut=new ve(0,0,G,tt),Ut=!1,kt=new _s,$t=!1,J=!1,rt=new oe,bt=new A,Dt=new ve,Tt={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0},Kt=!1;function ce(){return D===null?W:1}let C=n;function st(b,U){return e.getContext(b,U)}try{let b={alpha:!0,depth:s,stencil:r,antialias:a,premultipliedAlpha:l,preserveDrawingBuffer:c,powerPreference:h,failIfMajorPerformanceCaveat:u};if("setAttribute"in e&&e.setAttribute("data-engine",`three.js r${"180"}`),e.addEventListener("webglcontextlost",gt,!1),e.addEventListener("webglcontextrestored",wt,!1),e.addEventListener("webglcontextcreationerror",lt,!1),C===null){let U="webgl2";if(C=st(U,b),C===null)throw st(U)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(b){throw console.error("THREE.WebGLRenderer: "+b.message),b}let et,j,$,pt,ot,mt,Ht,zt,E,y,O,q,it,Y,Pt,ft,At,Rt,at,Mt,Ot,It,yt,qt;function L(){et=new Jg(C),et.init(),It=new T0(C,et),j=new Vg(C,et,t,It),$=new w0(C,et),j.reversedDepthBuffer&&d&&$.buffers.depth.setReversed(!0),pt=new jg(C),ot=new u0,mt=new E0(C,et,$,ot,j,It,pt),Ht=new Wg(x),zt=new Zg(x),E=new sp(C),yt=new kg(C,E),y=new $g(C,E,pt,yt),O=new t_(C,y,E,pt),at=new Qg(C,j,mt),ft=new Gg(ot),q=new h0(x,Ht,zt,et,j,yt,ft),it=new P0(x,ot),Y=new f0,Pt=new y0(et),Rt=new zg(x,Ht,zt,$,O,p,l),At=new S0(x,O,j),qt=new I0(C,pt,j,$),Mt=new Hg(C,et,pt),Ot=new Kg(C,et,pt),pt.programs=q.programs,x.capabilities=j,x.extensions=et,x.properties=ot,x.renderLists=Y,x.shadowMap=At,x.state=$,x.info=pt}L();let dt=new Sc(x,C);this.xr=dt,this.getContext=function(){return C},this.getContextAttributes=function(){return C.getContextAttributes()},this.forceContextLoss=function(){let b=et.get("WEBGL_lose_context");b&&b.loseContext()},this.forceContextRestore=function(){let b=et.get("WEBGL_lose_context");b&&b.restoreContext()},this.getPixelRatio=function(){return W},this.setPixelRatio=function(b){b!==void 0&&(W=b,this.setSize(G,tt,!1))},this.getSize=function(b){return b.set(G,tt)},this.setSize=function(b,U,H=!0){if(dt.isPresenting){console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting.");return}G=b,tt=U,e.width=Math.floor(b*W),e.height=Math.floor(U*W),H===!0&&(e.style.width=b+"px",e.style.height=U+"px"),this.setViewport(0,0,b,U)},this.getDrawingBufferSize=function(b){return b.set(G*W,tt*W).floor()},this.setDrawingBufferSize=function(b,U,H){G=b,tt=U,W=H,e.width=Math.floor(b*H),e.height=Math.floor(U*H),this.setViewport(0,0,b,U)},this.getCurrentViewport=function(b){return b.copy(I)},this.getViewport=function(b){return b.copy(Q)},this.setViewport=function(b,U,H,X){b.isVector4?Q.set(b.x,b.y,b.z,b.w):Q.set(b,U,H,X),$.viewport(I.copy(Q).multiplyScalar(W).round())},this.getScissor=function(b){return b.copy(ut)},this.setScissor=function(b,U,H,X){b.isVector4?ut.set(b.x,b.y,b.z,b.w):ut.set(b,U,H,X),$.scissor(F.copy(ut).multiplyScalar(W).round())},this.getScissorTest=function(){return Ut},this.setScissorTest=function(b){$.setScissorTest(Ut=b)},this.setOpaqueSort=function(b){B=b},this.setTransparentSort=function(b){Z=b},this.getClearColor=function(b){return b.copy(Rt.getClearColor())},this.setClearColor=function(){Rt.setClearColor(...arguments)},this.getClearAlpha=function(){return Rt.getClearAlpha()},this.setClearAlpha=function(){Rt.setClearAlpha(...arguments)},this.clear=function(b=!0,U=!0,H=!0){let X=0;if(b){let N=!1;if(D!==null){let ct=D.texture.format;N=ct===ra||ct===sa||ct===ia}if(N){let ct=D.texture.type,vt=ct===En||ct===yi||ct===ws||ct===Ts||ct===ea||ct===na,Et=Rt.getClearColor(),St=Rt.getClearAlpha(),Ft=Et.r,Bt=Et.g,Lt=Et.b;vt?(g[0]=Ft,g[1]=Bt,g[2]=Lt,g[3]=St,C.clearBufferuiv(C.COLOR,0,g)):(_[0]=Ft,_[1]=Bt,_[2]=Lt,_[3]=St,C.clearBufferiv(C.COLOR,0,_))}else X|=C.COLOR_BUFFER_BIT}U&&(X|=C.DEPTH_BUFFER_BIT),H&&(X|=C.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),C.clear(X)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){e.removeEventListener("webglcontextlost",gt,!1),e.removeEventListener("webglcontextrestored",wt,!1),e.removeEventListener("webglcontextcreationerror",lt,!1),Rt.dispose(),Y.dispose(),Pt.dispose(),ot.dispose(),Ht.dispose(),zt.dispose(),O.dispose(),yt.dispose(),qt.dispose(),q.dispose(),dt.dispose(),dt.removeEventListener("sessionstart",An),dt.removeEventListener("sessionend",qc),Si.stop()};function gt(b){b.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),R=!0}function wt(){console.log("THREE.WebGLRenderer: Context Restored."),R=!1;let b=pt.autoReset,U=At.enabled,H=At.autoUpdate,X=At.needsUpdate,N=At.type;L(),pt.autoReset=b,At.enabled=U,At.autoUpdate=H,At.needsUpdate=X,At.type=N}function lt(b){console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ",b.statusMessage)}function nt(b){let U=b.target;U.removeEventListener("dispose",nt),Ct(U)}function Ct(b){Vt(b),ot.remove(b)}function Vt(b){let U=ot.get(b).programs;U!==void 0&&(U.forEach(function(H){q.releaseProgram(H)}),b.isShaderMaterial&&q.releaseShaderCache(b))}this.renderBufferDirect=function(b,U,H,X,N,ct){U===null&&(U=Tt);let vt=N.isMesh&&N.matrixWorld.determinant()<0,Et=Id(b,U,H,X,N);$.setMaterial(X,vt);let St=H.index,Ft=1;if(X.wireframe===!0){if(St=y.getWireframeAttribute(H),St===void 0)return;Ft=2}let Bt=H.drawRange,Lt=H.attributes.position,jt=Bt.start*Ft,ie=(Bt.start+Bt.count)*Ft;ct!==null&&(jt=Math.max(jt,ct.start*Ft),ie=Math.min(ie,(ct.start+ct.count)*Ft)),St!==null?(jt=Math.max(jt,0),ie=Math.min(ie,St.count)):Lt!=null&&(jt=Math.max(jt,0),ie=Math.min(ie,Lt.count));let Me=ie-jt;if(Me<0||Me===1/0)return;yt.setup(N,X,Et,H,St);let de,re=Mt;if(St!==null&&(de=E.get(St),re=Ot,re.setIndex(de)),N.isMesh)X.wireframe===!0?($.setLineWidth(X.wireframeLinewidth*ce()),re.setMode(C.LINES)):re.setMode(C.TRIANGLES);else if(N.isLine){let Nt=X.linewidth;Nt===void 0&&(Nt=1),$.setLineWidth(Nt*ce()),N.isLineSegments?re.setMode(C.LINES):N.isLineLoop?re.setMode(C.LINE_LOOP):re.setMode(C.LINE_STRIP)}else N.isPoints?re.setMode(C.POINTS):N.isSprite&&re.setMode(C.TRIANGLES);if(N.isBatchedMesh)if(N._multiDrawInstances!==null)fs("THREE.WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),re.renderMultiDrawInstances(N._multiDrawStarts,N._multiDrawCounts,N._multiDrawCount,N._multiDrawInstances);else if(et.get("WEBGL_multi_draw"))re.renderMultiDraw(N._multiDrawStarts,N._multiDrawCounts,N._multiDrawCount);else{let Nt=N._multiDrawStarts,ge=N._multiDrawCounts,te=N._multiDrawCount,$e=St?E.get(St).bytesPerElement:1,Ji=ot.get(X).currentProgram.getUniforms();for(let Ke=0;Ke{function ct(){if(X.forEach(function(vt){ot.get(vt).currentProgram.isReady()&&X.delete(vt)}),X.size===0){N(b);return}setTimeout(ct,10)}et.get("KHR_parallel_shader_compile")!==null?ct():setTimeout(ct,10)})};let ee=null;function zn(b){ee&&ee(b)}function An(){Si.stop()}function qc(){Si.start()}let Si=new Xu;Si.setAnimationLoop(zn),typeof self<"u"&&Si.setContext(self),this.setAnimationLoop=function(b){ee=b,dt.setAnimationLoop(b),b===null?Si.stop():Si.start()},dt.addEventListener("sessionstart",An),dt.addEventListener("sessionend",qc),this.render=function(b,U){if(U!==void 0&&U.isCamera!==!0){console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(R===!0)return;if(b.matrixWorldAutoUpdate===!0&&b.updateMatrixWorld(),U.parent===null&&U.matrixWorldAutoUpdate===!0&&U.updateMatrixWorld(),dt.enabled===!0&&dt.isPresenting===!0&&(dt.cameraAutoUpdate===!0&&dt.updateCamera(U),U=dt.getCamera()),b.isScene===!0&&b.onBeforeRender(x,b,U,D),f=Pt.get(b,M.length),f.init(U),M.push(f),rt.multiplyMatrices(U.projectionMatrix,U.matrixWorldInverse),kt.setFromProjectionMatrix(rt,yn,U.reversedDepth),J=this.localClippingEnabled,$t=ft.init(this.clippingPlanes,J),m=Y.get(b,w.length),m.init(),w.push(m),dt.enabled===!0&&dt.isPresenting===!0){let ct=x.xr.getDepthSensingMesh();ct!==null&&Ka(ct,U,-1/0,x.sortObjects)}Ka(b,U,0,x.sortObjects),m.finish(),x.sortObjects===!0&&m.sort(B,Z),Kt=dt.enabled===!1||dt.isPresenting===!1||dt.hasDepthSensing()===!1,Kt&&Rt.addToRenderList(m,b),this.info.render.frame++,$t===!0&&ft.beginShadows();let H=f.state.shadowsArray;At.render(H,b,U),$t===!0&&ft.endShadows(),this.info.autoReset===!0&&this.info.reset();let X=m.opaque,N=m.transmissive;if(f.setupLights(),U.isArrayCamera){let ct=U.cameras;if(N.length>0)for(let vt=0,Et=ct.length;vt0&&Zc(X,N,b,U),Kt&&Rt.render(b),Yc(m,b,U);D!==null&&P===0&&(mt.updateMultisampleRenderTarget(D),mt.updateRenderTargetMipmap(D)),b.isScene===!0&&b.onAfterRender(x,b,U),yt.resetDefaultState(),S=-1,v=null,M.pop(),M.length>0?(f=M[M.length-1],$t===!0&&ft.setGlobalState(x.clippingPlanes,f.state.camera)):f=null,w.pop(),w.length>0?m=w[w.length-1]:m=null};function Ka(b,U,H,X){if(b.visible===!1)return;if(b.layers.test(U.layers)){if(b.isGroup)H=b.renderOrder;else if(b.isLOD)b.autoUpdate===!0&&b.update(U);else if(b.isLight)f.pushLight(b),b.castShadow&&f.pushShadow(b);else if(b.isSprite){if(!b.frustumCulled||kt.intersectsSprite(b)){X&&Dt.setFromMatrixPosition(b.matrixWorld).applyMatrix4(rt);let vt=O.update(b),Et=b.material;Et.visible&&m.push(b,vt,Et,H,Dt.z,null)}}else if((b.isMesh||b.isLine||b.isPoints)&&(!b.frustumCulled||kt.intersectsObject(b))){let vt=O.update(b),Et=b.material;if(X&&(b.boundingSphere!==void 0?(b.boundingSphere===null&&b.computeBoundingSphere(),Dt.copy(b.boundingSphere.center)):(vt.boundingSphere===null&&vt.computeBoundingSphere(),Dt.copy(vt.boundingSphere.center)),Dt.applyMatrix4(b.matrixWorld).applyMatrix4(rt)),Array.isArray(Et)){let St=vt.groups;for(let Ft=0,Bt=St.length;Ft0&&kr(N,U,H),ct.length>0&&kr(ct,U,H),vt.length>0&&kr(vt,U,H),$.buffers.depth.setTest(!0),$.buffers.depth.setMask(!0),$.buffers.color.setMask(!0),$.setPolygonOffset(!1)}function Zc(b,U,H,X){if((H.isScene===!0?H.overrideMaterial:null)!==null)return;f.state.transmissionRenderTarget[X.id]===void 0&&(f.state.transmissionRenderTarget[X.id]=new Cn(1,1,{generateMipmaps:!0,type:et.has("EXT_color_buffer_half_float")||et.has("EXT_color_buffer_float")?Es:En,minFilter:xi,samples:4,stencilBuffer:r,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:Qt.workingColorSpace}));let ct=f.state.transmissionRenderTarget[X.id],vt=X.viewport||I;ct.setSize(vt.z*x.transmissionResolutionScale,vt.w*x.transmissionResolutionScale);let Et=x.getRenderTarget(),St=x.getActiveCubeFace(),Ft=x.getActiveMipmapLevel();x.setRenderTarget(ct),x.getClearColor(k),V=x.getClearAlpha(),V<1&&x.setClearColor(16777215,.5),x.clear(),Kt&&Rt.render(H);let Bt=x.toneMapping;x.toneMapping=jn;let Lt=X.viewport;if(X.viewport!==void 0&&(X.viewport=void 0),f.setupLightsView(X),$t===!0&&ft.setGlobalState(x.clippingPlanes,X),kr(b,H,X),mt.updateMultisampleRenderTarget(ct),mt.updateRenderTargetMipmap(ct),et.has("WEBGL_multisampled_render_to_texture")===!1){let jt=!1;for(let ie=0,Me=U.length;ie0),Lt=!!H.morphAttributes.position,jt=!!H.morphAttributes.normal,ie=!!H.morphAttributes.color,Me=jn;X.toneMapped&&(D===null||D.isXRRenderTarget===!0)&&(Me=x.toneMapping);let de=H.morphAttributes.position||H.morphAttributes.normal||H.morphAttributes.color,re=de!==void 0?de.length:0,Nt=ot.get(X),ge=f.state.lights;if($t===!0&&(J===!0||b!==v)){let ke=b===v&&X.id===S;ft.setState(X,b,ke)}let te=!1;X.version===Nt.__version?(Nt.needsLights&&Nt.lightsStateVersion!==ge.state.version||Nt.outputColorSpace!==Et||N.isBatchedMesh&&Nt.batching===!1||!N.isBatchedMesh&&Nt.batching===!0||N.isBatchedMesh&&Nt.batchingColor===!0&&N.colorTexture===null||N.isBatchedMesh&&Nt.batchingColor===!1&&N.colorTexture!==null||N.isInstancedMesh&&Nt.instancing===!1||!N.isInstancedMesh&&Nt.instancing===!0||N.isSkinnedMesh&&Nt.skinning===!1||!N.isSkinnedMesh&&Nt.skinning===!0||N.isInstancedMesh&&Nt.instancingColor===!0&&N.instanceColor===null||N.isInstancedMesh&&Nt.instancingColor===!1&&N.instanceColor!==null||N.isInstancedMesh&&Nt.instancingMorph===!0&&N.morphTexture===null||N.isInstancedMesh&&Nt.instancingMorph===!1&&N.morphTexture!==null||Nt.envMap!==St||X.fog===!0&&Nt.fog!==ct||Nt.numClippingPlanes!==void 0&&(Nt.numClippingPlanes!==ft.numPlanes||Nt.numIntersection!==ft.numIntersection)||Nt.vertexAlphas!==Ft||Nt.vertexTangents!==Bt||Nt.morphTargets!==Lt||Nt.morphNormals!==jt||Nt.morphColors!==ie||Nt.toneMapping!==Me||Nt.morphTargetsCount!==re)&&(te=!0):(te=!0,Nt.__version=X.version);let $e=Nt.currentProgram;te===!0&&($e=Hr(X,U,N));let Ji=!1,Ke=!1,Ns=!1,_e=$e.getUniforms(),an=Nt.uniforms;if($.useProgram($e.program)&&(Ji=!0,Ke=!0,Ns=!0),X.id!==S&&(S=X.id,Ke=!0),Ji||v!==b){$.buffers.depth.getReversed()&&b.reversedDepth!==!0&&(b._reversedDepth=!0,b.updateProjectionMatrix()),_e.setValue(C,"projectionMatrix",b.projectionMatrix),_e.setValue(C,"viewMatrix",b.matrixWorldInverse);let qe=_e.map.cameraPosition;qe!==void 0&&qe.setValue(C,bt.setFromMatrixPosition(b.matrixWorld)),j.logarithmicDepthBuffer&&_e.setValue(C,"logDepthBufFC",2/(Math.log(b.far+1)/Math.LN2)),(X.isMeshPhongMaterial||X.isMeshToonMaterial||X.isMeshLambertMaterial||X.isMeshBasicMaterial||X.isMeshStandardMaterial||X.isShaderMaterial)&&_e.setValue(C,"isOrthographic",b.isOrthographicCamera===!0),v!==b&&(v=b,Ke=!0,Ns=!0)}if(N.isSkinnedMesh){_e.setOptional(C,N,"bindMatrix"),_e.setOptional(C,N,"bindMatrixInverse");let ke=N.skeleton;ke&&(ke.boneTexture===null&&ke.computeBoneTexture(),_e.setValue(C,"boneTexture",ke.boneTexture,mt))}N.isBatchedMesh&&(_e.setOptional(C,N,"batchingTexture"),_e.setValue(C,"batchingTexture",N._matricesTexture,mt),_e.setOptional(C,N,"batchingIdTexture"),_e.setValue(C,"batchingIdTexture",N._indirectTexture,mt),_e.setOptional(C,N,"batchingColorTexture"),N._colorsTexture!==null&&_e.setValue(C,"batchingColorTexture",N._colorsTexture,mt));let ln=H.morphAttributes;if((ln.position!==void 0||ln.normal!==void 0||ln.color!==void 0)&&at.update(N,H,$e),(Ke||Nt.receiveShadow!==N.receiveShadow)&&(Nt.receiveShadow=N.receiveShadow,_e.setValue(C,"receiveShadow",N.receiveShadow)),X.isMeshGouraudMaterial&&X.envMap!==null&&(an.envMap.value=St,an.flipEnvMap.value=St.isCubeTexture&&St.isRenderTargetTexture===!1?-1:1),X.isMeshStandardMaterial&&X.envMap===null&&U.environment!==null&&(an.envMapIntensity.value=U.environmentIntensity),Ke&&(_e.setValue(C,"toneMappingExposure",x.toneMappingExposure),Nt.needsLights&&Dd(an,Ns),ct&&X.fog===!0&&it.refreshFogUniforms(an,ct),it.refreshMaterialUniforms(an,X,W,tt,f.state.transmissionRenderTarget[b.id]),Ps.upload(C,$c(Nt),an,mt)),X.isShaderMaterial&&X.uniformsNeedUpdate===!0&&(Ps.upload(C,$c(Nt),an,mt),X.uniformsNeedUpdate=!1),X.isSpriteMaterial&&_e.setValue(C,"center",N.center),_e.setValue(C,"modelViewMatrix",N.modelViewMatrix),_e.setValue(C,"normalMatrix",N.normalMatrix),_e.setValue(C,"modelMatrix",N.matrixWorld),X.isShaderMaterial||X.isRawShaderMaterial){let ke=X.uniformsGroups;for(let qe=0,ja=ke.length;qe0&&mt.useMultisampledRTT(b)===!1?N=ot.get(b).__webglMultisampledFramebuffer:Array.isArray(Bt)?N=Bt[H]:N=Bt,I.copy(b.viewport),F.copy(b.scissor),z=b.scissorTest}else I.copy(Q).multiplyScalar(W).floor(),F.copy(ut).multiplyScalar(W).floor(),z=Ut;if(H!==0&&(N=Ud),$.bindFramebuffer(C.FRAMEBUFFER,N)&&X&&$.drawBuffers(b,N),$.viewport(I),$.scissor(F),$.setScissorTest(z),ct){let St=ot.get(b.texture);C.framebufferTexture2D(C.FRAMEBUFFER,C.COLOR_ATTACHMENT0,C.TEXTURE_CUBE_MAP_POSITIVE_X+U,St.__webglTexture,H)}else if(vt){let St=U;for(let Ft=0;Ft=0&&U<=b.width-X&&H>=0&&H<=b.height-N&&(b.textures.length>1&&C.readBuffer(C.COLOR_ATTACHMENT0+Et),C.readPixels(U,H,X,N,It.convert(Bt),It.convert(Lt),ct))}finally{let Ft=D!==null?ot.get(D).__webglFramebuffer:null;$.bindFramebuffer(C.FRAMEBUFFER,Ft)}}},this.readRenderTargetPixelsAsync=async function(b,U,H,X,N,ct,vt,Et=0){if(!(b&&b.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let St=ot.get(b).__webglFramebuffer;if(b.isWebGLCubeRenderTarget&&vt!==void 0&&(St=St[vt]),St)if(U>=0&&U<=b.width-X&&H>=0&&H<=b.height-N){$.bindFramebuffer(C.FRAMEBUFFER,St);let Ft=b.textures[Et],Bt=Ft.format,Lt=Ft.type;if(!j.textureFormatReadable(Bt))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!j.textureTypeReadable(Lt))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");let jt=C.createBuffer();C.bindBuffer(C.PIXEL_PACK_BUFFER,jt),C.bufferData(C.PIXEL_PACK_BUFFER,ct.byteLength,C.STREAM_READ),b.textures.length>1&&C.readBuffer(C.COLOR_ATTACHMENT0+Et),C.readPixels(U,H,X,N,It.convert(Bt),It.convert(Lt),0);let ie=D!==null?ot.get(D).__webglFramebuffer:null;$.bindFramebuffer(C.FRAMEBUFFER,ie);let Me=C.fenceSync(C.SYNC_GPU_COMMANDS_COMPLETE,0);return C.flush(),await pu(C,Me,4),C.bindBuffer(C.PIXEL_PACK_BUFFER,jt),C.getBufferSubData(C.PIXEL_PACK_BUFFER,0,ct),C.deleteBuffer(jt),C.deleteSync(Me),ct}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(b,U=null,H=0){let X=Math.pow(2,-H),N=Math.floor(b.image.width*X),ct=Math.floor(b.image.height*X),vt=U!==null?U.x:0,Et=U!==null?U.y:0;mt.setTexture2D(b,0),C.copyTexSubImage2D(C.TEXTURE_2D,H,0,0,vt,Et,N,ct),$.unbindTexture()};let Nd=C.createFramebuffer(),Fd=C.createFramebuffer();this.copyTextureToTexture=function(b,U,H=null,X=null,N=0,ct=null){ct===null&&(N!==0?(fs("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),ct=N,N=0):ct=0);let vt,Et,St,Ft,Bt,Lt,jt,ie,Me,de=b.isCompressedTexture?b.mipmaps[ct]:b.image;if(H!==null)vt=H.max.x-H.min.x,Et=H.max.y-H.min.y,St=H.isBox3?H.max.z-H.min.z:1,Ft=H.min.x,Bt=H.min.y,Lt=H.isBox3?H.min.z:0;else{let ln=Math.pow(2,-N);vt=Math.floor(de.width*ln),Et=Math.floor(de.height*ln),b.isDataArrayTexture?St=de.depth:b.isData3DTexture?St=Math.floor(de.depth*ln):St=1,Ft=0,Bt=0,Lt=0}X!==null?(jt=X.x,ie=X.y,Me=X.z):(jt=0,ie=0,Me=0);let re=It.convert(U.format),Nt=It.convert(U.type),ge;U.isData3DTexture?(mt.setTexture3D(U,0),ge=C.TEXTURE_3D):U.isDataArrayTexture||U.isCompressedArrayTexture?(mt.setTexture2DArray(U,0),ge=C.TEXTURE_2D_ARRAY):(mt.setTexture2D(U,0),ge=C.TEXTURE_2D),C.pixelStorei(C.UNPACK_FLIP_Y_WEBGL,U.flipY),C.pixelStorei(C.UNPACK_PREMULTIPLY_ALPHA_WEBGL,U.premultiplyAlpha),C.pixelStorei(C.UNPACK_ALIGNMENT,U.unpackAlignment);let te=C.getParameter(C.UNPACK_ROW_LENGTH),$e=C.getParameter(C.UNPACK_IMAGE_HEIGHT),Ji=C.getParameter(C.UNPACK_SKIP_PIXELS),Ke=C.getParameter(C.UNPACK_SKIP_ROWS),Ns=C.getParameter(C.UNPACK_SKIP_IMAGES);C.pixelStorei(C.UNPACK_ROW_LENGTH,de.width),C.pixelStorei(C.UNPACK_IMAGE_HEIGHT,de.height),C.pixelStorei(C.UNPACK_SKIP_PIXELS,Ft),C.pixelStorei(C.UNPACK_SKIP_ROWS,Bt),C.pixelStorei(C.UNPACK_SKIP_IMAGES,Lt);let _e=b.isDataArrayTexture||b.isData3DTexture,an=U.isDataArrayTexture||U.isData3DTexture;if(b.isDepthTexture){let ln=ot.get(b),ke=ot.get(U),qe=ot.get(ln.__renderTarget),ja=ot.get(ke.__renderTarget);$.bindFramebuffer(C.READ_FRAMEBUFFER,qe.__webglFramebuffer),$.bindFramebuffer(C.DRAW_FRAMEBUFFER,ja.__webglFramebuffer);for(let bi=0;biMath.PI&&(n-=Ze),s<-Math.PI?s+=Ze:s>Math.PI&&(s-=Ze),n<=s?this._spherical.theta=Math.max(n,Math.min(s,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(n+s)/2?Math.max(n,this._spherical.theta):Math.min(s,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let r=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{let o=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),r=o!=this._spherical.radius}if(Re.setFromSpherical(this._spherical),Re.applyQuaternion(this._quatInverse),e.copy(this.target).add(Re),this.object.lookAt(this.target),this.enableDamping===!0?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let o=null;if(this.object.isPerspectiveCamera){let a=Re.length();o=this._clampDistance(a*this._scale);let l=a-o;this.object.position.addScaledVector(this._dollyDirection,l),this.object.updateMatrixWorld(),r=!!l}else if(this.object.isOrthographicCamera){let a=new A(this._mouse.x,this._mouse.y,0);a.unproject(this.object);let l=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),r=l!==this.object.zoom;let c=new A(this._mouse.x,this._mouse.y,0);c.unproject(this.object),this.object.position.sub(c).add(a),this.object.updateMatrixWorld(),o=Re.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;o!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(o).add(this.object.position):(ka.origin.copy(this.object.position),ka.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(ka.direction))wc||8*(1-this._lastQuaternion.dot(this.object.quaternion))>wc||this._lastTargetPosition.distanceToSquared(this.target)>wc?(this.dispatchEvent($u),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(t){return t!==null?Ze/60*this.autoRotateSpeed*t:Ze/60/60*this.autoRotateSpeed}_getZoomScale(t){let e=Math.abs(t*.01);return Math.pow(.95,this.zoomSpeed*e)}_rotateLeft(t){this._sphericalDelta.theta-=t}_rotateUp(t){this._sphericalDelta.phi-=t}_panLeft(t,e){Re.setFromMatrixColumn(e,0),Re.multiplyScalar(-t),this._panOffset.add(Re)}_panUp(t,e){this.screenSpacePanning===!0?Re.setFromMatrixColumn(e,1):(Re.setFromMatrixColumn(e,0),Re.crossVectors(this.object.up,Re)),Re.multiplyScalar(t),this._panOffset.add(Re)}_pan(t,e){let n=this.domElement;if(this.object.isPerspectiveCamera){let s=this.object.position;Re.copy(s).sub(this.target);let r=Re.length();r*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*t*r/n.clientHeight,this.object.matrix),this._panUp(2*e*r/n.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(t*(this.object.right-this.object.left)/this.object.zoom/n.clientWidth,this.object.matrix),this._panUp(e*(this.object.top-this.object.bottom)/this.object.zoom/n.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(t){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=t:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(t){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=t:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(t,e){if(!this.zoomToCursor)return;this._performCursorZoom=!0;let n=this.domElement.getBoundingClientRect(),s=t-n.left,r=e-n.top,o=n.width,a=n.height;this._mouse.x=s/o*2-1,this._mouse.y=-(r/a)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(t){return Math.max(this.minDistance,Math.min(this.maxDistance,t))}_handleMouseDownRotate(t){this._rotateStart.set(t.clientX,t.clientY)}_handleMouseDownDolly(t){this._updateZoomParameters(t.clientX,t.clientX),this._dollyStart.set(t.clientX,t.clientY)}_handleMouseDownPan(t){this._panStart.set(t.clientX,t.clientY)}_handleMouseMoveRotate(t){this._rotateEnd.set(t.clientX,t.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);let e=this.domElement;this._rotateLeft(Ze*this._rotateDelta.x/e.clientHeight),this._rotateUp(Ze*this._rotateDelta.y/e.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(t){this._dollyEnd.set(t.clientX,t.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(t){this._panEnd.set(t.clientX,t.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(t){this._updateZoomParameters(t.clientX,t.clientY),t.deltaY<0?this._dollyIn(this._getZoomScale(t.deltaY)):t.deltaY>0&&this._dollyOut(this._getZoomScale(t.deltaY)),this.update()}_handleKeyDown(t){let e=!1;switch(t.code){case this.keys.UP:t.ctrlKey||t.metaKey||t.shiftKey?this.enableRotate&&this._rotateUp(Ze*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),e=!0;break;case this.keys.BOTTOM:t.ctrlKey||t.metaKey||t.shiftKey?this.enableRotate&&this._rotateUp(-Ze*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),e=!0;break;case this.keys.LEFT:t.ctrlKey||t.metaKey||t.shiftKey?this.enableRotate&&this._rotateLeft(Ze*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),e=!0;break;case this.keys.RIGHT:t.ctrlKey||t.metaKey||t.shiftKey?this.enableRotate&&this._rotateLeft(-Ze*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),e=!0;break}e&&(t.preventDefault(),this.update())}_handleTouchStartRotate(t){if(this._pointers.length===1)this._rotateStart.set(t.pageX,t.pageY);else{let e=this._getSecondPointerPosition(t),n=.5*(t.pageX+e.x),s=.5*(t.pageY+e.y);this._rotateStart.set(n,s)}}_handleTouchStartPan(t){if(this._pointers.length===1)this._panStart.set(t.pageX,t.pageY);else{let e=this._getSecondPointerPosition(t),n=.5*(t.pageX+e.x),s=.5*(t.pageY+e.y);this._panStart.set(n,s)}}_handleTouchStartDolly(t){let e=this._getSecondPointerPosition(t),n=t.pageX-e.x,s=t.pageY-e.y,r=Math.sqrt(n*n+s*s);this._dollyStart.set(0,r)}_handleTouchStartDollyPan(t){this.enableZoom&&this._handleTouchStartDolly(t),this.enablePan&&this._handleTouchStartPan(t)}_handleTouchStartDollyRotate(t){this.enableZoom&&this._handleTouchStartDolly(t),this.enableRotate&&this._handleTouchStartRotate(t)}_handleTouchMoveRotate(t){if(this._pointers.length==1)this._rotateEnd.set(t.pageX,t.pageY);else{let n=this._getSecondPointerPosition(t),s=.5*(t.pageX+n.x),r=.5*(t.pageY+n.y);this._rotateEnd.set(s,r)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);let e=this.domElement;this._rotateLeft(Ze*this._rotateDelta.x/e.clientHeight),this._rotateUp(Ze*this._rotateDelta.y/e.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(t){if(this._pointers.length===1)this._panEnd.set(t.pageX,t.pageY);else{let e=this._getSecondPointerPosition(t),n=.5*(t.pageX+e.x),s=.5*(t.pageY+e.y);this._panEnd.set(n,s)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(t){let e=this._getSecondPointerPosition(t),n=t.pageX-e.x,s=t.pageY-e.y,r=Math.sqrt(n*n+s*s);this._dollyEnd.set(0,r),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);let o=(t.pageX+e.x)*.5,a=(t.pageY+e.y)*.5;this._updateZoomParameters(o,a)}_handleTouchMoveDollyPan(t){this.enableZoom&&this._handleTouchMoveDolly(t),this.enablePan&&this._handleTouchMovePan(t)}_handleTouchMoveDollyRotate(t){this.enableZoom&&this._handleTouchMoveDolly(t),this.enableRotate&&this._handleTouchMoveRotate(t)}_addPointer(t){this._pointers.push(t.pointerId)}_removePointer(t){delete this._pointerPositions[t.pointerId];for(let e=0;e.9&&(o.visible=!1)),this.axis==="Y"&&(me.setFromEuler(Va.set(0,0,Math.PI/2)),o.quaternion.copy(n).multiply(me),Math.abs(ae.copy(Xi).applyQuaternion(n).dot(this.eye))>.9&&(o.visible=!1)),this.axis==="Z"&&(me.setFromEuler(Va.set(0,Math.PI/2,0)),o.quaternion.copy(n).multiply(me),Math.abs(ae.copy(Ur).applyQuaternion(n).dot(this.eye))>.9&&(o.visible=!1)),this.axis==="XYZE"&&(me.setFromEuler(Va.set(0,Math.PI/2,0)),ae.copy(this.rotationAxis),o.quaternion.setFromRotationMatrix(sd.lookAt(id,ae,Xi)),o.quaternion.multiply(me),o.visible=this.dragging),this.axis==="E"&&(o.visible=!1)):o.name==="START"?(o.position.copy(this.worldPositionStart),o.visible=this.dragging):o.name==="END"?(o.position.copy(this.worldPosition),o.visible=this.dragging):o.name==="DELTA"?(o.position.copy(this.worldPositionStart),o.quaternion.copy(this.worldQuaternionStart),ze.set(1e-10,1e-10,1e-10).add(this.worldPositionStart).sub(this.worldPosition).multiplyScalar(-1),ze.applyQuaternion(this.worldQuaternionStart.clone().invert()),o.scale.copy(ze),o.visible=this.dragging):(o.quaternion.copy(n),this.dragging?o.position.copy(this.worldPositionStart):o.position.copy(this.worldPosition),this.axis&&(o.visible=this.axis.search(o.name)!==-1));continue}o.quaternion.copy(n),this.mode==="translate"||this.mode==="scale"?(o.name==="X"&&Math.abs(ae.copy(Lr).applyQuaternion(n).dot(this.eye))>.99&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="Y"&&Math.abs(ae.copy(Xi).applyQuaternion(n).dot(this.eye))>.99&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="Z"&&Math.abs(ae.copy(Ur).applyQuaternion(n).dot(this.eye))>.99&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="XY"&&Math.abs(ae.copy(Ur).applyQuaternion(n).dot(this.eye))<.2&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="YZ"&&Math.abs(ae.copy(Lr).applyQuaternion(n).dot(this.eye))<.2&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="XZ"&&Math.abs(ae.copy(Xi).applyQuaternion(n).dot(this.eye))<.2&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1)):this.mode==="rotate"&&(Ga.copy(n),ae.copy(this.eye).applyQuaternion(me.copy(n).invert()),o.name.search("E")!==-1&&o.quaternion.setFromRotationMatrix(sd.lookAt(this.eye,id,Xi)),o.name==="X"&&(me.setFromAxisAngle(Lr,Math.atan2(-ae.y,ae.z)),me.multiplyQuaternions(Ga,me),o.quaternion.copy(me)),o.name==="Y"&&(me.setFromAxisAngle(Xi,Math.atan2(ae.x,ae.z)),me.multiplyQuaternions(Ga,me),o.quaternion.copy(me)),o.name==="Z"&&(me.setFromAxisAngle(Ur,Math.atan2(ae.y,ae.x)),me.multiplyQuaternions(Ga,me),o.quaternion.copy(me))),o.visible=o.visible&&(o.name.indexOf("X")===-1||this.showX),o.visible=o.visible&&(o.name.indexOf("Y")===-1||this.showY),o.visible=o.visible&&(o.name.indexOf("Z")===-1||this.showZ),o.visible=o.visible&&(o.name.indexOf("E")===-1||this.showX&&this.showY&&this.showZ),o.material._color=o.material._color||o.material.color.clone(),o.material._opacity=o.material._opacity||o.material.opacity,o.material.color.copy(o.material._color),o.material.opacity=o.material._opacity,this.enabled&&this.axis&&(o.name===this.axis?(o.material.color.copy(this.materialLib.active.color),o.material.opacity=1):this.axis.split("").some(function(l){return o.name===l})&&(o.material.color.copy(this.materialLib.active.color),o.material.opacity=1))}super.updateMatrixWorld(t)}},Pc=class extends _t{constructor(){super(new In(1e5,1e5,2,2),new en({visible:!1,wireframe:!0,side:Ge,transparent:!0,opacity:.1,toneMapped:!1})),this.isTransformControlsPlane=!0,this.type="TransformControlsPlane"}updateMatrixWorld(t){let e=this.space;switch(this.position.copy(this.worldPosition),this.mode==="scale"&&(e="local"),Wa.copy(Lr).applyQuaternion(e==="local"?this.worldQuaternion:Xa),Ir.copy(Xi).applyQuaternion(e==="local"?this.worldQuaternion:Xa),Dr.copy(Ur).applyQuaternion(e==="local"?this.worldQuaternion:Xa),ae.copy(Ir),this.mode){case"translate":case"scale":switch(this.axis){case"X":ae.copy(this.eye).cross(Wa),Nn.copy(Wa).cross(ae);break;case"Y":ae.copy(this.eye).cross(Ir),Nn.copy(Ir).cross(ae);break;case"Z":ae.copy(this.eye).cross(Dr),Nn.copy(Dr).cross(ae);break;case"XY":Nn.copy(Dr);break;case"YZ":Nn.copy(Wa);break;case"XZ":ae.copy(Dr),Nn.copy(Ir);break;case"XYZ":case"E":Nn.set(0,0,0);break}break;case"rotate":default:Nn.set(0,0,0)}Nn.length()===0?this.quaternion.copy(this.cameraQuaternion):(rd.lookAt(ze.set(0,0,0),Nn,ae),this.quaternion.setFromRotationMatrix(rd)),super.updateMatrixWorld(t)}};function od(i,t=67108864){if(!i||!Number.isSafeInteger(i.bytes)||i.bytes<0||i.bytes>t||typeof i.sha256!="string"||!/^[a-f0-9]{64}$/.test(i.sha256))throw new Error("Asset size or digest descriptor mismatch")}async function K0(i,t){if(od(t),i.length!==t.bytes)throw new Error("Asset size mismatch");if(Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",i)),n=>n.toString(16).padStart(2,"0")).join("")!==t.sha256)throw new Error("Asset checksum mismatch")}var ad="dvidia-robot-simulation-lab.static.hf.space",j0="us.aws.cdn.hf.co",Q0=new Set([408,429,502,503,504]),tx=Object.freeze({"geometry.bin.gz":{bytes:3574720,sha256:"51365a5a661d8062e28c66abc6bdb843ee410811f84b49d62c5878c265b3631f"},"native-assets.bin.gz":{bytes:7318481,sha256:"9c960598f9b2c0c7459a8bdfc8a544513b4c6ffaff2c8787fa49f728774eb9e7"},"mujoco.wasm.gz":{bytes:2543112,sha256:"ad01772e00939bf6300a953b396d38aa9ec03c05fcda46c3c8d940d56f772b3b"}});function ex(i,t){if(i.protocol!=="https:"||i.host!==ad||i.search||i.hash||!t)return null;let e=i.pathname.split("/").pop(),n=tx[e];return!n||i.pathname!=="/workstation/v01/"+e||t.bytes!==n.bytes||t.sha256!==n.sha256?null:new URL("https://research.dvidia.org/runtime/workstation/"+n.sha256+"/"+e)}var rn=class extends Error{constructor(t,e=!1){super(t),this.name="ResourceDownloadError",this.retryable=e}};function nx(i,t){let e={maxBytes:t?.bytes??67108864,idleTimeoutMs:3e4,timeoutMs:12e4,maxAttempts:3,retryDelayMs:250,...i};for(let[n,s,r]of[["maxBytes",67108864,0],["idleTimeoutMs",12e4,1],["timeoutMs",12e4,1],["maxAttempts",3,1],["retryDelayMs",2e3,0]])if(!Number.isSafeInteger(e[n])||e[n]s)throw new Error(`Invalid resource transport option: ${n}`);if(t&&e.maxBytes{e=()=>r(t.reason),t.addEventListener("abort",e,{once:!0})});try{return await Promise.race([i,n])}finally{t.removeEventListener("abort",e)}}async function ix(i,t,e,n){if(!i)throw new rn("The server returned an empty resource");let s=i.getReader(),r=[],o=0,a=!1;try{for(;;){let h;try{h=await ld(s.read(),e)}catch(u){throw e.aborted?e.reason:new rn(`Body download interrupted: ${u.message||"network error"}`,!0)}if(h.done){a=!0;break}if(o+=h.value.byteLength,o>t)throw new rn("Resource is too large");r.push(h.value),h.value.byteLength&&n(o)}}finally{a||s.cancel().catch(()=>{}),s.releaseLock()}let l=new Uint8Array(o),c=0;for(let h of r)l.set(h,c),c+=h.byteLength;return l}async function cd(i,t,e={}){t&&od(t);let n=nx(e,t),s=new URL(i);if(!["http:","https:"].includes(s.protocol)||s.username||s.password)throw new Error("Invalid resource URL");let r=s.protocol==="https:"&&s.host===ad,o=ex(s,t),a=performance.now()+n.timeoutMs,l=s.pathname.split("/").pop()||"resource",c=t?.bytes??null,h=(d,p,g=0)=>n.onProgress?.({path:s.pathname,phase:d,attempt:p,receivedBytes:g,totalBytes:c}),u=()=>new rn("Total download deadline exceeded");for(let d=1;d<=n.maxAttempts;d+=1){let p=a-performance.now();if(p<=0)throw new Error(`Could not download ${l}: total download deadline exceeded`);let g=new AbortController,_=o!==null&&d===1,m=_?o:s,f=setTimeout(()=>g.abort(u()),p),w,M=()=>{clearTimeout(w),w=setTimeout(()=>g.abort(new rn("Download stalled without receiving data",!0)),n.idleTimeoutMs)};try{c=t?.bytes??null,h("downloading",d),M();let x;try{x=await ld(fetch(m,{credentials:"omit",referrerPolicy:"no-referrer",redirect:_?"manual":r?"follow":"error",signal:g.signal,...d>1?{cache:"reload"}:{}}),g.signal)}catch(S){throw g.signal.aborted?g.signal.reason:new rn(`Network request failed: ${S.message||"network error"}`,!0)}if(M(),_&&(x.type==="opaqueredirect"||x.redirected||x.status>=300&&x.status<400))throw x.body?.cancel().catch(()=>{}),new rn("The pinned workstation mirror may not redirect");let R=new URL(x.url);if(_?R.href!==m.href:R.origin!==s.origin&&!(r&&R.protocol==="https:"&&R.host===j0))throw x.body?.cancel().catch(()=>{}),new rn("Resource redirected outside the permitted workstation host");if(!x.ok)throw x.body?.cancel().catch(()=>{}),new rn(`HTTP ${x.status}`,Q0.has(x.status)||_&&[404,410].includes(x.status));if(Number(x.headers.get("content-length"))>n.maxBytes)throw x.body?.cancel().catch(()=>{}),new rn("Resource is too large");let T=x.headers.get("content-length"),P=x.headers.get("content-encoding");!t&&(!P||P==="identity")&&/^\d+$/.test(T??"")&&Number.isSafeInteger(Number(T))&&Number(T)<=n.maxBytes&&(c=Number(T),h("downloading",d));let D=await ix(x.body,t?.bytes??n.maxBytes,g.signal,S=>{M(),h("downloading",d,S)});return t&&await K0(D,t),h("complete",d,D.byteLength),D}catch(x){if(!(x instanceof rn&&x.retryable&&dsetTimeout(P,T))}finally{clearTimeout(f),clearTimeout(w)}}}var K=i=>document.getElementById(i),le=(i,t)=>{if(!i)throw new Error(t)},Vc=(i,t,e)=>Math.min(e,Math.max(t,i)),sx=64*1024*1024,vd=performance.now(),rx=new Date().toISOString(),ti={commands:[],samples:[],commands_dropped:0,samples_dropped:0},Xt,Ee,Nc,Mi,fn,We,Ce,Pe,Fn,Fc,Yi=[],Oc=[],pn,Bc,Ds,zc,Xe,Md=!1,Sd=!1,mn=!1,Bn=!1,Ic=!1,ox=0,Ja=0,Dc=0,hd=-1/0,ud=-1/0,Gc=-1/0,Ls=null,Zi=null,bd=!1,Br=!1,kc=!1,dd=null,wd=null,Je,Fr,fd=0,qi=null,Lc=null,pd=!1,$a=!1,md=new Map,Uc=-1/0;function Ed(i){if(Bn||mn)return;let t=i.path?.split("/").pop(),e={"geometry.bin.gz":"Scene geometry","native-assets.bin.gz":"Robot meshes","mujoco.wasm.gz":"Physics engine","mujoco.wasm":"Physics engine"};if(!e[t])return;if(md.set(t,i),i.phase==="retrying"){K("loading-message").textContent=`${e[t]}: download interrupted. Retrying (${i.attempt+1}/3)…`,Uc=performance.now();return}if(performance.now()-Uc<250)return;Uc=performance.now();let n=[...md.values()],s=n.reduce((o,a)=>o+a.receivedBytes,0),r=n.reduce((o,a)=>o+(a.totalBytes||0),0);K("loading-message").textContent=`Downloading simulator files · ${(s/1e6).toFixed(1)}`+(r?` / ${(r/1e6).toFixed(1)}`:"")+" MB"}function Tn(i,t){return le((Array.isArray(i)||ArrayBuffer.isView(i))&&i.length===t&&Array.from(i).every(Number.isFinite),"The simulation supplied an invalid vector."),i}function ax(i){return le(typeof i=="string"&&/^[a-zA-Z0-9_.-]+(?:\/[a-zA-Z0-9_.-]+)*$/.test(i)&&!i.split("/").some(t=>t==="."||t===".."),"Invalid local resource path."),i}async function lx(i,t){le(i,"The server returned an empty resource.");let e=i.getReader(),n=[],s=0;try{for(;;){let{done:a,value:l}=await e.read();if(a)break;if(s+=l.byteLength,s>t)throw await e.cancel(),new Error("Resource exceeds the workstation byte limit.");n.push(l)}}finally{e.releaseLock()}let r=new Uint8Array(s),o=0;for(let a of n)r.set(a,o),o+=a.length;return r.buffer}async function Wc(i,t,e){let n=new URL(ax(i),location.href);return(await cd(n,e,{maxBytes:t,onProgress:Ed})).buffer}async function Td(i){return globalThis.crypto?.subtle?Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",i)),t=>t.toString(16).padStart(2,"0")).join(""):null}async function gd(i){return JSON.parse(new TextDecoder().decode(await Wc(i,4*1024*1024)))}async function cx(i){le(i&&i.compression==="gzip"&&i.href===Xt.geometry_url&&[i.bytes,i.compressed_bytes].every(r=>Number.isInteger(r)&&r>0&&r<=sx),"Invalid compiled geometry descriptor."),le(typeof DecompressionStream=="function","This browser needs gzip stream support.");let t=i.compressed_sha256===void 0?void 0:{bytes:i.compressed_bytes,sha256:i.compressed_sha256},e=await Wc(i.href,i.compressed_bytes,t);le(e.byteLength===i.compressed_bytes,"The geometry download is incomplete.");let n=await lx(new Blob([e]).stream().pipeThrough(new DecompressionStream("gzip")),i.bytes);le(n.byteLength===i.bytes,"The decoded geometry has an unexpected size.");let s=await Td(n);return le(s===null||s===i.sha256,"The compiled geometry checksum does not match."),n}function hx(i){le(Ee.schema==="dvidia.live-workstation-model/v1"&&Array.isArray(Ee.bodies)&&Ee.bodies.length>0&&Ee.bodies.length<=128,"Unsupported native model geometry."),Ee.bodies.forEach((n,s)=>le(n.id===s&&typeof n.name=="string","Invalid body identity.")),le(Array.isArray(Ee.meshes)&&Ee.meshes.length<=128&&Array.isArray(Ee.geoms)&&Ee.geoms.length<=512,"Invalid geometry inventory.");let t=new Set,e=new DataView(i);for(let n of Ee.meshes){let{vertex_count:s,index_count:r,position_byte_offset:o,index_byte_offset:a}=n;le(Number.isInteger(n.id)&&!t.has(n.id)&&[s,r,o,a].every(Number.isInteger)&&s>0&&r>=0&&r%3===0&&o>=0&&a>=0&&o%4===0&&a%4===0&&o+s*12<=i.byteLength&&a+r*4<=i.byteLength,"Invalid native mesh range."),t.add(n.id);for(let l=0;l=0&&n.body_ide*2));case"sphere":return new bn(i.size[0],28,20);case"ellipsoid":{let e=new bn(1,48,32);return e.scale(...i.size),e}case"capsule":{let e=new ar(i.size[0],2*i.size[1],8,24);return e.rotateX(Math.PI/2),e}case"cylinder":{let e=new we(i.size[0],i.size[0],i.size[1]*2,36);return e.rotateX(Math.PI/2),e}case"plane":return new In(12,12)}}function xd(i){let t=document.createElement("canvas");t.width=512,t.height=512;let e=t.getContext("2d"),n=2718,s=()=>(n=Math.imul(n,1664525)+1013904223>>>0,n/4294967296);if(e.fillStyle=i==="wood"?"#cdb794":"#d6d6ce",e.fillRect(0,0,512,512),i==="wood"){for(let o=0;o<512;o++){let a=.018+s()*.075;e.strokeStyle="rgba(89,60,35,"+a+")",e.lineWidth=.4+s()*1.4,e.beginPath(),e.moveTo(0,o);for(let l=0;l<=512;l+=16)e.lineTo(l,o+Math.sin(l*.016+o*.045)*(1+s()*2));e.stroke()}for(let o of[126,256,386])e.fillStyle="rgba(70,53,32,.13)",e.fillRect(0,o,512,1),e.fillStyle="rgba(255,255,235,.2)",e.fillRect(0,o+1,512,1)}else for(let o=0;o<512;o+=4)for(let a=0;a<512;a+=4)e.fillStyle="rgba("+(s()>.5?"255,255,255,":"40,43,42,")+(.025+s()*.085)+")",e.fillRect(a,o,2,3);let r=new xs(t);return r.colorSpace=De,r.wrapS=r.wrapT=hs,r.anisotropy=Math.min(8,fn.capabilities.getMaxAnisotropy()),i!=="wood"&&r.repeat.set(3,2),r}function dx(i,t){let e=document.createElement("canvas");e.width=1024,e.height=256;let n=e.getContext("2d");n.clearRect(0,0,1024,256),n.fillStyle="#526657",n.font="500 43px sans-serif",n.fillText(i,40,113),n.fillStyle="#75816a",n.font="25px monospace",n.fillText(t,41,167);let s=new xs(e);return s.colorSpace=De,s}function fx(i,t){let e=Nc.shoes.find(B=>B.id===Xt.shoe_asset_ids[0]),n=e?.geometry.find(B=>B.name==="upper");if(!n)return;let s=B=>new $n({color:B,roughness:.92,metalness:0}),r=(B,Z,Q=0)=>{let ut=new _t(B,Z);return ut.position.z=Q,ut.castShadow=!0,ut.receiveShadow=!0,i.add(ut),ut},o=new vs;o.moveTo(-.131,-.03),o.bezierCurveTo(-.139,-.023,-.139,.027,-.129,.035),o.bezierCurveTo(-.106,.046,-.065,.044,-.035,.041),o.bezierCurveTo(.007,.044,.045,.048,.085,.047),o.bezierCurveTo(.122,.046,.137,.029,.136,.003),o.bezierCurveTo(.136,-.026,.125,-.044,.101,-.045),o.bezierCurveTo(.05,-.047,.017,-.041,-.03,-.037),o.bezierCurveTo(-.071,-.038,-.113,-.043,-.131,-.03);let a=(B,Z)=>new _r(o,{depth:B,bevelEnabled:!0,bevelThickness:Z,bevelSize:Z,bevelSegments:3,steps:1,curveSegments:18});r(a(.003,.001),s(4872022),.001),r(a(.011,.002),s(15262931),.006);let l=s(10792868),c=o.getPoints(90).map(B=>new A(B.x,B.y,.0155));r(new fi(new Jn(c,!0),100,6e-4,4,!0),l);let h=n.position_m[1],u=.019,d=B=>{let Z=u,Q=1e-4;for(let ut of e.geometry.filter(Ut=>Ut.type==="ellipsoid")){let Ut=(B-ut.position_m[0])/ut.size_m[0];if(Math.abs(Ut)<=1){let kt=Math.sqrt(1-Ut*Ut);Q=Math.max(Q,ut.size_m[1]*kt),Z=Math.max(Z,ut.position_m[2]+ut.size_m[2]*kt)}}return{height:Z,width:Q}},p=(B,Z)=>{let Q=d(B),ut=Math.sqrt(Math.max(0,1-((Z-h)/Q.width)**2));return u+(Q.height-u)*Math.pow(ut,.72)},g=(B,Z)=>((B+.079)/.027)**2+((Z-h)/.017)**2<1,_=[],m=[],f=[],w=[],M=96,x=48,R=new Gt(3362138),T=new Gt(7438969),P=new Gt(12897730);for(let B=0;B<=M;B++){let Z=-.127+.262*B/M,Q=d(Z);for(let ut=0;ut<=x;ut++){let Ut=Math.PI*ut/x,kt=h+Q.width*Math.cos(Ut),$t=u+(Q.height-u)*Math.pow(Math.sin(Ut),.72);_.push(Z,kt,$t),m.push(B/M,ut/x);let J=Z<-.046?T:Z>.064?P:R;w.push(J.r,J.g,J.b)}}let D=(B,Z,Q)=>{let ut=(_[B*3]+_[Z*3]+_[Q*3])/3,Ut=(_[B*3+1]+_[Z*3+1]+_[Q*3+1])/3;g(ut,Ut)||f.push(B,Z,Q)};for(let B=0;B{Ic=!1,!Bn&&(fn.render(We,Ce),K("canvas").dataset.renderCount=String(++ox))}))}function Ya(i){if(!Ce)return;let t=new A(...Xt.camera.target),e=Math.max(1,.95/Ce.aspect),n={perspective:new A(...Xt.camera.position).sub(t),top:new A(.001,-.001,1.8),front:new A(0,-1.85,.38)};Ce.position.copy(t).add((n[i]||n.perspective).clone().multiplyScalar(e)),Pe.target.copy(t),Pe.update(),document.querySelectorAll("[data-camera]").forEach(s=>s.setAttribute("aria-pressed",String(s.dataset.camera===i))),on()}function mx(i){le(K("canvas").getContext("webgl2"),"WebGL2 is unavailable in this browser."),fn=new Ba({canvas:K("canvas"),antialias:!0,powerPreference:"high-performance"}),fn.setPixelRatio(Math.min(devicePixelRatio||1,2)),fn.outputColorSpace=De,fn.toneMapping=$o,fn.toneMappingExposure=1.05,fn.shadowMap.enabled=!0,fn.shadowMap.type=Vo,We=new nr,We.background=new Gt(15329758),We.fog=new er(15329758,4,11),Ce=new Ne(37,1,.01,20),Ce.up.set(0,0,1),Pe=new Ha(Ce,K("canvas")),Pe.minDistance=.25,Pe.maxDistance=4.5,Pe.maxPolarAngle=Math.PI*.48,Pe.screenSpacePanning=!0,Pe.addEventListener("change",on),We.add(new Mr(16775401,11646373,2.3));let t=new Ss(16773590,2.7);t.position.set(-1.1,-1.3,3.5),t.target.position.set(.2,0,0),t.castShadow=!0,t.shadow.mapSize.set(2048,2048),t.shadow.camera.left=-1.4,t.shadow.camera.right=1.4,t.shadow.camera.top=1.4,t.shadow.camera.bottom=-1.4,t.shadow.camera.near=.1,t.shadow.camera.far=7,t.shadow.normalBias=8e-4,t.shadow.bias=-8e-5,t.shadow.radius=4,We.add(t,t.target);let e=new Ss(14477813,.9);e.position.set(1,1,2),We.add(e),Yi=Ee.bodies.map(()=>{let u=new vn;return We.add(u),u});let n=new Map,s=new DataView(i),r=xd("wood"),o=xd("fabric");for(let u of Ee.meshes){let d=new Float32Array(u.vertex_count*3),p=new Uint32Array(u.index_count);for(let _=0;_0&&u.group<=2&&!g){let _=new $n({color:new Gt().setRGB(...u.rgba.slice(0,3),Yn),metalness:.05,roughness:.66,transparent:u.rgba[3]<1,opacity:u.rgba[3]});if(p===Xt.environment_geoms.table||p===Xt.environment_geoms.rack)_.color.set(15326401),_.map=r,_.roughness=.78,_.metalness=0;else if(p===Xt.environment_geoms.floor)_.color.set(14278353),_.roughness=1,_.metalness=0;else if(g)_.color.set(p.includes("sole")?15526103:p.includes("heel")?7899013:3362142),_.roughness=.97,_.metalness=0,p.includes("sole")||(_.map=o);else if(!p.startsWith("workstation_")&&u.type==="mesh"){let f=(u.rgba[0]+u.rgba[1]+u.rgba[2])/3;_.color.set(f>.35?14934487:2243660),_.roughness=.5,_.metalness=.15}let m=new _t(d,_);m.position.fromArray(u.position),_d(u.quaternion_wxyz,m.quaternion),m.castShadow=u.type!=="plane",m.receiveShadow=!0,Yi[u.body_id].add(m),a++}if(u.collision&&u.type!=="plane"){let _=new _t(d,new en({color:g?14919277:6593937,wireframe:!0,transparent:!0,opacity:.38,depthWrite:!1}));_.position.fromArray(u.position),_d(u.quaternion_wxyz,_.quaternion),_.visible=!1,_.renderOrder=3,Yi[u.body_id].add(_),Oc.push(_)}}let l=Ee.bodies.findIndex(u=>u.name===Xt.shoe_body_names[0]);le(l>=0,"The native shoe is missing."),zc=Yi[l],px(zc,o),pn=new vn,We.add(pn);let c=new _t(new bn(.008,20,14),new en({color:7774068,transparent:!0,opacity:.7,depthTest:!1}));c.renderOrder=10,pn.add(c),Bc=new _t(new bn(.0035,16,12),new en({color:14608858})),We.add(Bc),Ds=new Oe(new ue().setFromPoints([new A,new A]),new xr({color:8493937,dashSize:.008,gapSize:.005,transparent:!0,opacity:.6})),We.add(Ds),Fn=new qa(Ce,K("canvas")),Fn.setMode("translate"),Fn.setSpace("world"),Fn.setSize(.65),Fn.attach(pn),Fc=Fn.getHelper(),We.add(Fc),Fn.addEventListener("dragging-changed",u=>{bd=u.value,Pe.enabled=!u.value,u.value||Us(),on()}),Fn.addEventListener("objectChange",()=>{if(Br||!mn)return;let u=Rd(pn.position.toArray());$a=!1,K("target-error").textContent="",pn.position.fromArray(u),Xc(u,!0),Cd(u),on()}),Fn.addEventListener("change",on),new ResizeObserver(()=>{let u=K("stage").getBoundingClientRect();if(u.width<1||u.height<1)return;let d=Ce.aspect;Ce.aspect=u.width/u.height,Ce.position.sub(Pe.target).multiplyScalar(Math.max(1,.95/Ce.aspect)/Math.max(1,.95/d)).add(Pe.target),Ce.updateProjectionMatrix(),fn.setSize(u.width,u.height,!1),on()}).observe(K("stage"));let h=K("stage").getBoundingClientRect();Ce.aspect=h.width/h.height,Ce.updateProjectionMatrix(),fn.setSize(h.width,h.height,!1),Ya("perspective"),K("canvas").addEventListener("webglcontextlost",u=>{u.preventDefault(),Or(new Error("WebGL was interrupted. Reload the workstation to restart."))}),K("stage").dataset.visualGeoms=String(a),K("stage").dataset.collisionGeoms=String(Oc.length),Md=!0}function Ad(i,t,e,n){i.length===e&&(i.shift(),ti[n]++),i.push(t)}function zr(i){!mn||Bn||(Mi.postMessage(i),Ad(ti.commands,{wall_ms:performance.now()-vd,sim_time:Xe?.sim_time??null,...i},2e3,"commands_dropped"))}function Rd(i){return i.map((t,e)=>Vc(t,...Je[e]))}function Xc(i,t=!1){for(let[e,n]of["x","y","z"].entries()){let s=K("target-"+n);(t||!$a&&document.activeElement!==s)&&(s.value=String(Math.round(i[e]*1e3)))}K("height").value=String(Math.round(i[2]*1e3)),K("height-value").textContent=(i[2]*1e3).toFixed(0)+" mm"}function Nr(i,t=!0){Tn(i,3);let e=Rd(i);$a=!1,Br=!0,pn.position.fromArray(e),Br=!1,Xc(e,!0),K("target-error").textContent="",t&&Cd(e),on()}function Cd(i){Ls=i.slice();let t=Math.max(0,34-(performance.now()-Gc));Zi||(Zi=setTimeout(Us,t))}function Us(){clearTimeout(Zi),Zi=null,Ls&&(zr({type:"target",position:Ls}),Ls=null,Gc=performance.now())}function Hc(i,t=!0){let e=Vc(i,...Fr);K("gripper").value=String(e*1e3),K("gripper-value").textContent=(e*1e3).toFixed(1)+" mm",document.querySelector(".gripper-diagram").style.setProperty("--jaw-visual",7+e/Fr[1]*18+"px"),t&&zr({type:"gripper",jaw:e})}function Za(i){!mn||kc||(kc=!0,K("pause").disabled=!0,zr({type:"pause",paused:i}))}function On(i,t=1){return Number.isFinite(i)?i.toFixed(t):"—"}function gx(i){if(Bn)return;let t=i.paused===!0,e=t?"paused":"running";K("session").dataset.state!==e&&(K("session").dataset.state=e,K("session-label").textContent=t?"Simulation paused":"Simulation running"),K("pause").setAttribute("aria-pressed",String(t)),K("pause-label").textContent=t?"Resume":"Pause",K("pause-icon").setAttribute("d",t?"M6 4 16 10 6 16Z":"M7 5v10M13 5v10"),K("live-status").textContent=t?"Physics paused · camera stays active":"Live native physics",dd!==t&&(K("announcer").textContent=t?"Simulation paused.":"Simulation running.",dd=t),kc=!1,K("pause").disabled=!mn}function Pd(i){let t=i.body_pos,e=i.body_quat;Tn(t,Yi.length*3),Tn(e,Yi.length*4),Tn(i.tcp_position,3),Tn(i.target_position,3),le(Number.isFinite(i.sim_time)&&i.sim_time>=0,"Invalid native simulation time."),(!Lc||i.target_position.some((o,a)=>Math.abs(o-Lc[a])>1e-9))&&(Lc=i.target_position.slice(),qi=null),i.tracking_error_m>.005?(qi===null||i.sim_time=4;n&&!pd&&(K("announcer").textContent="The tool has not reached within five millimeters of this target after four simulated seconds. Try a closer target."),pd=n,Yi.forEach((o,a)=>{o.position.fromArray(t,a*3);let l=a*4,c=Math.hypot(...e.slice(l,l+4));le(Math.abs(c-1)<.002,"Invalid native body rotation."),o.quaternion.set(e[l+1],e[l+2],e[l+3],e[l])}),Bc.position.fromArray(i.tcp_position),!bd&&Ls===null&&performance.now()-Gc>150&&(Br=!0,pn.position.fromArray(i.target_position),Br=!1,Xc(i.target_position));let s=Ds.geometry.attributes.position;s.setXYZ(0,...i.tcp_position),s.setXYZ(1,...pn.position.toArray()),s.needsUpdate=!0,Ds.computeLineDistances(),Ds.geometry.computeBoundingSphere(),fd++,K("stage").dataset.stateCount=String(Ja),K("stage").dataset.simTime=String(i.sim_time),K("stage").dataset.renderedPoses=String(fd);let r=performance.now();if(r-ud>=100&&(Ad(ti.samples,{wall_ms:r-vd,sim_time:i.sim_time,paused:i.paused,tcp_position:i.tcp_position,target_position:i.target_position,body_pos:i.body_pos,body_quat:i.body_quat,qpos:i.qpos,qvel:i.qvel,ctrl:i.ctrl,actuator_force:i.actuator_force,jaw_target_m:i.jaw,jaw_actual_m:i.actual_jaw,jaw_commanded_m:i.commanded_jaw,contacts:i.contacts,contact_normal_force_total_n:i.contact_normal_force_total_n,contact_normal_force_max_n:i.contact_normal_force_max_n,tracking_error_m:i.tracking_error_m,metrics:i.metrics,warnings:i.warnings},3e3,"samples_dropped"),ud=r),gx(i),r-hd>=150){let o=i.sim_time,a=Math.floor(o/60);K("sim-time").textContent=String(a).padStart(2,"0")+":"+(o%60).toFixed(2).padStart(5,"0"),K("tracking-error").textContent=On(i.tracking_error_m*1e3),K("contacts").textContent=Number.isInteger(i.contacts)?String(i.contacts):"—";let l=i.metrics||{};K("step-p95").textContent=On(l.step_ms_p95,2),K("rtf").textContent=On(l.rtf,2),K("control-p95").textContent=On(l.control_ms_p95,2)+" ms",K("lag").textContent=On(l.lag_ms,0)+" ms",K("actual-jaw").textContent=On(i.actual_jaw*1e3,1)+" mm",K("contact-force").textContent=On(i.contact_normal_force_total_n,2)+" N",K("state-count").textContent=String(Ja),K("receipt-count").textContent=String(ti.samples.length),K("engine-version").textContent=i.engine||"MuJoCo WASM";let c=(i.warnings||[]).map(String).join(" · ");K("warning").hidden=!c,K("warning").textContent=c,K("tool-state").lastChild.textContent=n?" Target not reached":i.tracking_error_m>.005?" Approaching":" Tracking",K("tool-state").dataset.state=n?"limited":"tracking",K("tool-state").title=n?"Target error remains above 5 mm after 4 simulated seconds. Workspace bounds do not guarantee reachability.":"Measured native tool position compared with the requested target.",hd=r}on()}function yd(){!Md||!Sd||mn||Bn||(mn=!0,document.querySelectorAll("button,input").forEach(i=>{i.disabled=!1}),Nr(Xt.initial_target_xyz,!1),Hc(Xe?.jaw??Xt.home_ctrl[Xt.gripper_actuator_ids[0]],!1),K("loading").hidden=!0,K("stage").dataset.ready="true",Xe&&Pd(Xe),document.hidden&&Za(!0))}function _x(){Us();let i={schema:"dvidia.live-workstation-session/v1",opened_at:rx,exported_at:new Date().toISOString(),source:{manifest_sha256:wd,compiled_model_sha256:Xt.compiled_model_sha256,geometry_sha256:Ee.geometry_binary.sha256,native_version:Xt.native_version,robot:Xt.robot,shoe_asset_ids:Xt.shoe_asset_ids},scope:"Local browser interaction with privileged native simulator state. No learned policy, physical robot control, or grasp qualification.",controller:Xt.controller,bounds_xyz:Xt.bounds_xyz,timestep:Xt.timestep,control_dt:Xt.control_dt,interaction_limits:Xt.interaction_limits,recording:{sample_wall_interval_ms:100,sample_limit:3e3,command_limit:2e3,received_states:Ja,samples_dropped:ti.samples_dropped,commands_dropped:ti.commands_dropped,note:"Bounded recent samples and commands; wall timestamps continue across reset. Simulation time restarts on reset. UI samples may omit intervening physics steps."},latest_metrics:Xe?.metrics??null,commands:ti.commands,samples:ti.samples},t=URL.createObjectURL(new Blob([JSON.stringify(i,null,2)+` +`],{type:"application/json"})),e=document.createElement("a");e.href=t,e.download="dvidia-workstation-session-"+new Date().toISOString().replace(/[:.]/g,"-")+".json",document.body.append(e),e.click(),e.remove(),setTimeout(()=>URL.revokeObjectURL(t),3e4),K("announcer").textContent="Session receipt downloaded. Measurements remain on your device."}function xx(){for(let i of["x","y","z"])K("target-"+i).addEventListener("input",()=>{$a=!0,K("target-error").textContent="Coordinates edited. Apply target to send."});document.querySelectorAll("[data-camera]").forEach(i=>i.addEventListener("click",()=>Ya(i.dataset.camera))),K("home-camera").addEventListener("click",()=>Ya("perspective")),K("focus-shoe").addEventListener("click",()=>{Pe.target.copy(zc.position).add(new A(0,0,.05)),Ce.position.copy(Pe.target).add(new A(.48,-.65,.42).multiplyScalar(Math.max(1,.7/Ce.aspect))),Pe.update(),document.querySelectorAll("[data-camera]").forEach(i=>i.setAttribute("aria-pressed","false")),on()}),K("gizmo").addEventListener("click",()=>{let i=K("gizmo").getAttribute("aria-pressed")!=="true";K("gizmo").setAttribute("aria-pressed",String(i)),Fc.visible=i,Fn.enabled=i,pn.visible=i,Ds.visible=i,on()}),K("collision").addEventListener("click",()=>{let i=K("collision").getAttribute("aria-pressed")!=="true";K("collision").setAttribute("aria-pressed",String(i)),Oc.forEach(t=>{t.visible=i}),K("scene-caption").textContent=i?"Native collision wireframes over visual geometry.":"One arm. One object. Interactive local simulation.",on()}),K("target-form").addEventListener("submit",i=>{i.preventDefault();let t=["x","y","z"].map(e=>K("target-"+e).valueAsNumber/1e3);if(!t.every((e,n)=>Number.isFinite(e)&&e>=Je[n][0]-1e-9&&e<=Je[n][1]+1e-9)){K("target-error").textContent="Use coordinates inside the displayed workspace bounds.";return}Nr(t),Us()}),K("reset-target").addEventListener("click",()=>{Xe&&(Nr(Xe.tcp_position),Us(),Xe.tcp_position.some((i,t)=>iJe[t][1])&&(K("target-error").textContent="The current tool is outside the command volume; target moved to the nearest allowed position."))}),K("height").addEventListener("input",()=>Nr([pn.position.x,pn.position.y,K("height").valueAsNumber/1e3])),K("height").addEventListener("change",Us),K("gripper").addEventListener("input",()=>Hc(K("gripper").valueAsNumber/1e3)),K("pause").addEventListener("click",()=>Za(!Xe?.paused)),K("reset").addEventListener("click",()=>{clearTimeout(Zi),Zi=null,Ls=null,zr({type:"reset"}),Nr(Xt.initial_target_xyz,!1),Hc(Xt.home_ctrl[Xt.gripper_actuator_ids[0]],!1),K("announcer").textContent="Reset requested. The original arm and shoe state will be restored."}),K("push").addEventListener("click",()=>{let i=Math.min(.12,Xt.interaction_limits.push_impulse_norm_max_ns);zr({type:"push",body:Xt.shoe_body_names[0],impulse:[0,i,0]}),K("announcer").textContent=Xe?.paused?"Nudge queued. Resume the simulation to apply it.":"Nudge requested: "+i.toFixed(2)+" newton seconds toward positive Y."}),K("receipt").addEventListener("click",_x),K("canvas").addEventListener("keydown",i=>{if(mn){if(["h","H","Home"].includes(i.key))i.preventDefault(),Ya("perspective");else if(i.key===" ")i.preventDefault(),Za(!Xe?.paused);else if(["+","=","-","_"].includes(i.key)){i.preventDefault();let t=Ce.position.clone().sub(Pe.target);t.setLength(Vc(t.length()*(["+","="].includes(i.key)?.9:1/.9),Pe.minDistance,Pe.maxDistance)),Ce.position.copy(Pe.target).add(t),Pe.update(),on()}}}),document.addEventListener("visibilitychange",()=>{document.hidden&&mn&&!Xe?.paused&&Za(!0),document.hidden||on()}),window.addEventListener("pagehide",()=>Mi?.terminate())}function Or(i){Bn||(Bn=!0,mn=!1,Mi?.terminate(),clearTimeout(Zi),K("session").dataset.state="error",K("session-label").textContent="Simulation unavailable",K("loading").hidden=!1,K("loading").classList.add("error"),K("loading-title").textContent="The workstation could not continue",K("loading-message").textContent=i?.message||String(i),K("stage").dataset.ready="error",K("live-status").textContent="Physics stopped",document.querySelectorAll("button,input").forEach(t=>{t.disabled=!0}),K("retry-download").hidden=!1,K("retry-download").disabled=!1,ti.samples.length&&(K("receipt").disabled=!1),K("announcer").textContent=K("loading-message").textContent)}async function yx(){le(["http:","https:"].includes(location.protocol),"Serve the exported workstation over local HTTP or HTTPS."),le(typeof Worker=="function","This browser does not support local physics workers.");let i=await Wc("workstation.json",4*1024*1024);Xt=JSON.parse(new TextDecoder().decode(i)),wd=await Td(i),le(Xt.schema==="dvidia.live-workstation/v1"&&Xt.physical_robot_ready===!1&&Xt.learned_policy===!1,"Unsupported workstation manifest."),le(Array.isArray(Xt.bounds_xyz)&&Xt.bounds_xyz.length===3,"Missing target workspace bounds."),Je=Xt.bounds_xyz.map(n=>(Tn(n,2),le(n[1]>n[0],"Invalid workspace bounds."),n)),Fr=Tn(Xt.controller.gripper_range_m,2),Tn(Xt.initial_target_xyz,3),Tn(Xt.camera.position,3),Tn(Xt.camera.target,3),le(Number.isFinite(Xt.interaction_limits.push_impulse_norm_max_ns)&&Xt.interaction_limits.push_impulse_norm_max_ns>0,"Missing physical disturbance limit.");for(let[n,s]of["x","y","z"].entries())K("target-"+s).min=String(Je[n][0]*1e3),K("target-"+s).max=String(Je[n][1]*1e3),K("target-"+s).title=Math.round(Je[n][0]*1e3)+" to "+Math.round(Je[n][1]*1e3)+" mm";K("height").min=String(Je[2][0]*1e3),K("height").max=String(Je[2][1]*1e3),K("height-min").textContent=Math.round(Je[2][0]*1e3)+" mm",K("height-max").textContent=Math.round(Je[2][1]*1e3)+" mm",K("gripper").min=String(Fr[0]*1e3),K("gripper").max=String(Fr[1]*1e3),K("physics-step").textContent=On(Xt.timestep*1e3,0)+" ms",Mi=new Worker("./workstation_worker.bundle.js",{type:"module"}),Mi.addEventListener("error",n=>Or(new Error(n.message||"The local physics worker stopped unexpectedly."))),Mi.addEventListener("message",n=>{try{let s=n.data;if(s.type==="error"){Or(new Error(s.message));return}if(s.type==="ready"||s.type==="state"){if(!s.state)return;Xe=s.state,Ja++,Dc=performance.now(),s.type==="ready"&&(Sd=!0),mn?Pd(Xe):yd(),Mi.postMessage({type:"ack"})}else s.type==="progress"&&(s.download?Ed(s.download):Bn||(K("loading-message").textContent=String(s.message||"Preparing the native physics engine.")))}catch(s){Or(s)}}),Mi.postMessage({type:"init",manifest_url:new URL("workstation.json",location.href).href}),[Ee,Nc]=await Promise.all([gd(Xt.model_url),gd("catalog.json")]);let t=await cx(Ee.geometry_binary);hx(t),mx(t),xx();let e=Nc.shoes.find(n=>n.id===Xt.shoe_asset_ids[0]);le(e,"The shoe is missing from the asset catalog."),K("object-name").textContent=e.name,K("object-mass").textContent=On(e.properties.mass_kg.value*1e3,0)+" g",K("object-friction").textContent=On(e.properties.sliding_friction.value,2)+" μ",yd(),setInterval(()=>{!mn||Bn||Xe?.paused||document.hidden||Dc&&performance.now()-Dc>2e3&&(K("live-status").textContent="Waiting for physics updates",K("session").dataset.state="loading",K("session-label").textContent="Waiting for physics")},1e3)}K("retry-download").addEventListener("click",()=>location.reload());yx().catch(Or); diff --git a/src/dvidia_training/workstation.html b/src/dvidia_training/workstation.html new file mode 100644 index 0000000..0f7e0ea --- /dev/null +++ b/src/dvidia_training/workstation.html @@ -0,0 +1,207 @@ + + + + + + +PiPER shoe workstation · DVIDIA + + + + + + +
DVIDIARobotics research
WORKSTATION / 0.1Read the research
+
+
DVIDIA robotics · Interactive experiment

PiPER shoe workstation

Move the arm, adjust the gripper, and explore contact in a live physics simulation.

Opening simulation
+
+
+
+
PiPER /Shoe workstation
+
Interactive physicsOne arm. One object. Interactive local simulation.
Drag the target axes to move the tool.
Drag empty space to orbit · Scroll to zoom · H home
XYZ · up
Preparing your workstation

Loading the arm geometry and local physics engine.

+ +
+
A simulated arm and rigid shoe. Material properties are assumed; no physical robot is connected.
+
What is simulated?

A native six-axis PiPER arm, its coupled gripper, a finite table and rack, and one free rigid shoe. Gravity, inertia, collisions and friction run locally in MuJoCo. A bounded position controller moves the tool toward your target with a fixed orientation; targets are commands, not guaranteed reachable poses.

The shoe is original coarse geometry with unmeasured mass and friction assumptions. The arm retains its pinned upstream geometry. Fabric, laces and wood grain are visual details; they do not add deformation or tactile sensing. Contact forces and positions are privileged simulator observations. This scene does not establish a learned shoe skill or physical robot transfer.

Exact scene and controller manifest · Asset properties and provenance · Runtime licenses

Brand and font notices

The DVIDIA mark and wordmark reproduce the existing DVIDIA website identity. The code license does not grant trademark rights. The embedded, unmodified IBM Plex Sans font retains its separate SIL Open Font License.

Copyright © 2017 IBM Corp. with Reserved Font Name "Plex"
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+
+This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded, 
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
+
+
+ +
+
DVIDIA · Open tools for physical intelligenceInteractive physics research prototype hello@dvidia.org
+
+ +
+ + + diff --git a/src/dvidia_training/workstation.js b/src/dvidia_training/workstation.js new file mode 100644 index 0000000..428e620 --- /dev/null +++ b/src/dvidia_training/workstation.js @@ -0,0 +1,767 @@ +/* DVIDIA live workstation. MIT. Rendering follows native worker body poses. */ +import * as THREE from 'three'; +import {OrbitControls} from 'three/addons/controls/OrbitControls.js'; +import {TransformControls} from 'three/addons/controls/TransformControls.js'; +import {resourceBytes} from './workstation_assets.js'; + +const $ = id => document.getElementById(id); +const assert = (condition, message) => { if (!condition) throw new Error(message); }; +const clamp = (x, lo, hi) => Math.min(hi, Math.max(lo, x)); +const MAX_BYTES = 64 * 1024 * 1024; +const sessionStart = performance.now(); +const openedAt = new Date().toISOString(); +const receipt = {commands: [], samples: [], commands_dropped: 0, samples_dropped: 0}; +let manifest, model, catalog, worker, renderer, world, camera, orbit, transform, transformHelper; +let bodies = [], collisionMeshes = [], target, actualTool, targetLine, shoeBody; +let latest, sceneReady = false, workerReady = false, ready = false, failed = false; +let scheduled = false, renderCount = 0, stateCount = 0, lastStateAt = 0, lastMetricsAt = -Infinity; +let lastSampleAt = -Infinity, lastSentTargetAt = -Infinity, pendingTarget = null, targetTimer = null; +let manipulating = false, settingTarget = false, awaitingPause = false, lastPause = null; +let manifestDigest = null, sceneBounds, jawRange, renderedPoses = 0; +let trackingErrorSince = null, reportedTarget = null, trackingLimited = false; +let targetDraftDirty = false; +const downloads = new Map(); +let lastDownloadPaint = -Infinity; + +function downloadProgress(info) { + if (failed || ready) return; + const name = info.path?.split('/').pop(); + const names = {'geometry.bin.gz': 'Scene geometry', 'native-assets.bin.gz': 'Robot meshes', + 'mujoco.wasm.gz': 'Physics engine', 'mujoco.wasm': 'Physics engine'}; + if (!names[name]) return; + downloads.set(name, info); + if (info.phase === 'retrying') { + $('loading-message').textContent = `${names[name]}: download interrupted. Retrying (${info.attempt + 1}/3)…`; + lastDownloadPaint = performance.now(); + return; + } + if (performance.now() - lastDownloadPaint < 250) return; + lastDownloadPaint = performance.now(); + const records = [...downloads.values()]; + const received = records.reduce((n, row) => n + row.receivedBytes, 0); + const total = records.reduce((n, row) => n + (row.totalBytes || 0), 0); + $('loading-message').textContent = `Downloading simulator files · ${(received / 1e6).toFixed(1)}` + + (total ? ` / ${(total / 1e6).toFixed(1)}` : '') + ' MB'; +} + +function vec(value, count) { + assert((Array.isArray(value) || ArrayBuffer.isView(value)) && value.length === count + && Array.from(value).every(Number.isFinite), 'The simulation supplied an invalid vector.'); + return value; +} +function relative(path) { + assert(typeof path === 'string' && /^[a-zA-Z0-9_.-]+(?:\/[a-zA-Z0-9_.-]+)*$/.test(path) + && !path.split('/').some(part => part === '.' || part === '..'), 'Invalid local resource path.'); + return path; +} +async function bounded(stream, limit) { + assert(stream, 'The server returned an empty resource.'); + const reader = stream.getReader(), chunks = []; + let length = 0; + try { + for (;;) { + const {done, value} = await reader.read(); + if (done) break; + length += value.byteLength; + if (length > limit) { await reader.cancel(); throw new Error('Resource exceeds the workstation byte limit.'); } + chunks.push(value); + } + } finally { reader.releaseLock(); } + const output = new Uint8Array(length); + let offset = 0; + for (const chunk of chunks) { output.set(chunk, offset); offset += chunk.length; } + return output.buffer; +} +async function fetchBytes(path, limit, expected) { + const url = new URL(relative(path), location.href); + return (await resourceBytes(url, expected, {maxBytes: limit, onProgress: downloadProgress})).buffer; +} +async function digest(bytes) { + if (!globalThis.crypto?.subtle) return null; + return Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)), n => n.toString(16).padStart(2, '0')).join(''); +} +async function loadJSON(path) { + return JSON.parse(new TextDecoder().decode(await fetchBytes(path, 4 * 1024 * 1024))); +} +async function loadGeometry(meta) { + assert(meta && meta.compression === 'gzip' && meta.href === manifest.geometry_url + && [meta.bytes, meta.compressed_bytes].every(x => Number.isInteger(x) && x > 0 && x <= MAX_BYTES), + 'Invalid compiled geometry descriptor.'); + assert(typeof DecompressionStream === 'function', 'This browser needs gzip stream support.'); + const expected = meta.compressed_sha256 === undefined ? undefined + : {bytes: meta.compressed_bytes, sha256: meta.compressed_sha256}; + const packed = await fetchBytes(meta.href, meta.compressed_bytes, expected); + assert(packed.byteLength === meta.compressed_bytes, 'The geometry download is incomplete.'); + const bytes = await bounded(new Blob([packed]).stream().pipeThrough(new DecompressionStream('gzip')), meta.bytes); + assert(bytes.byteLength === meta.bytes, 'The decoded geometry has an unexpected size.'); + const checksum = await digest(bytes); + assert(checksum === null || checksum === meta.sha256, 'The compiled geometry checksum does not match.'); + return bytes; +} +function validateGeometry(bytes) { + assert(model.schema === 'dvidia.live-workstation-model/v1' && Array.isArray(model.bodies) + && model.bodies.length > 0 && model.bodies.length <= 128, 'Unsupported native model geometry.'); + model.bodies.forEach((body, index) => assert(body.id === index && typeof body.name === 'string', 'Invalid body identity.')); + assert(Array.isArray(model.meshes) && model.meshes.length <= 128 && Array.isArray(model.geoms) + && model.geoms.length <= 512, 'Invalid geometry inventory.'); + const ids = new Set(), view = new DataView(bytes); + for (const mesh of model.meshes) { + const {vertex_count: n, index_count: m, position_byte_offset: v, index_byte_offset: f} = mesh; + assert(Number.isInteger(mesh.id) && !ids.has(mesh.id) && [n, m, v, f].every(Number.isInteger) + && n > 0 && m >= 0 && m % 3 === 0 && v >= 0 && f >= 0 && v % 4 === 0 && f % 4 === 0 + && v + n * 12 <= bytes.byteLength && f + m * 4 <= bytes.byteLength, 'Invalid native mesh range.'); + ids.add(mesh.id); + for (let i = 0; i < n * 3; i++) assert(Number.isFinite(view.getFloat32(v + i * 4, true)), 'Nonfinite native mesh.'); + for (let i = 0; i < m; i++) assert(view.getUint32(f + i * 4, true) < n, 'Mesh index outside vertices.'); + } + for (const geom of model.geoms) { + assert(Number.isInteger(geom.body_id) && geom.body_id >= 0 && geom.body_id < model.bodies.length + && ['mesh', 'box', 'sphere', 'ellipsoid', 'capsule', 'cylinder', 'plane'].includes(geom.type), 'Invalid native geometry.'); + for (const [key, n] of [['position', 3], ['quaternion_wxyz', 4], ['size', 3], ['rgba', 4]]) vec(geom[key], n); + assert(geom.type !== 'mesh' || ids.has(geom.mesh_id), 'Missing native mesh.'); + } +} +function nativeQuaternion(q, output) { output.set(q[1], q[2], q[3], q[0]); } +function primitive(geom, meshes) { + switch (geom.type) { + case 'mesh': return meshes.get(geom.mesh_id); + case 'box': return new THREE.BoxGeometry(...geom.size.map(n => n * 2)); + case 'sphere': return new THREE.SphereGeometry(geom.size[0], 28, 20); + case 'ellipsoid': { const shape = new THREE.SphereGeometry(1, 48, 32); shape.scale(...geom.size); return shape; } + case 'capsule': { const shape = new THREE.CapsuleGeometry(geom.size[0], 2 * geom.size[1], 8, 24); shape.rotateX(Math.PI / 2); return shape; } + case 'cylinder': { const shape = new THREE.CylinderGeometry(geom.size[0], geom.size[0], geom.size[1] * 2, 36); shape.rotateX(Math.PI / 2); return shape; } + case 'plane': return new THREE.PlaneGeometry(12, 12); + } +} +function texture(kind) { + const canvas = document.createElement('canvas'); + canvas.width = 512; canvas.height = 512; + const ctx = canvas.getContext('2d'); + let seed = 2718; + const random = () => { seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0; return seed / 4294967296; }; + ctx.fillStyle = kind === 'wood' ? '#cdb794' : '#d6d6ce'; ctx.fillRect(0, 0, 512, 512); + if (kind === 'wood') { + for (let y = 0; y < 512; y++) { + const alpha = .018 + random() * .075; + ctx.strokeStyle = 'rgba(89,60,35,' + alpha + ')'; ctx.lineWidth = .4 + random() * 1.4; + ctx.beginPath(); ctx.moveTo(0, y); + for (let x = 0; x <= 512; x += 16) ctx.lineTo(x, y + Math.sin(x * .016 + y * .045) * (1 + random() * 2)); + ctx.stroke(); + } + for (const y of [126, 256, 386]) { + ctx.fillStyle = 'rgba(70,53,32,.13)'; ctx.fillRect(0, y, 512, 1); + ctx.fillStyle = 'rgba(255,255,235,.2)'; ctx.fillRect(0, y + 1, 512, 1); + } + } else { + for (let y = 0; y < 512; y += 4) for (let x = 0; x < 512; x += 4) { + ctx.fillStyle = 'rgba(' + (random() > .5 ? '255,255,255,' : '40,43,42,') + (.025 + random() * .085) + ')'; + ctx.fillRect(x, y, 2, 3); + } + } + const map = new THREE.CanvasTexture(canvas); + map.colorSpace = THREE.SRGBColorSpace; map.wrapS = map.wrapT = THREE.RepeatWrapping; + map.anisotropy = Math.min(8, renderer.capabilities.getMaxAnisotropy()); + if (kind !== 'wood') map.repeat.set(3, 2); + return map; +} +function labelTexture(text, detail) { + const canvas = document.createElement('canvas'); canvas.width = 1024; canvas.height = 256; + const ctx = canvas.getContext('2d'); ctx.clearRect(0, 0, 1024, 256); + ctx.fillStyle = '#526657'; ctx.font = '500 43px sans-serif'; ctx.fillText(text, 40, 113); + ctx.fillStyle = '#75816a'; ctx.font = '25px monospace'; ctx.fillText(detail, 41, 167); + const map = new THREE.CanvasTexture(canvas); map.colorSpace = THREE.SRGBColorSpace; return map; +} +function dressShoe(shoe, fabric) { + // Original visual mesh stays within the catalog shoe's 280 x 100 x 90 mm + // bounds. Native box/ellipsoid collision, inertia and dynamics are unchanged. + const asset = catalog.shoes.find(item => item.id === manifest.shoe_asset_ids[0]); + const upper = asset?.geometry.find(item => item.name === 'upper'); + if (!upper) return; + const material = color => new THREE.MeshStandardMaterial({color, roughness: .92, metalness: 0}); + const add = (geometry, surface, z = 0) => { + const mesh = new THREE.Mesh(geometry, surface); mesh.position.z = z; + mesh.castShadow = true; mesh.receiveShadow = true; shoe.add(mesh); return mesh; + }; + const outline = new THREE.Shape(); + outline.moveTo(-.131, -.03); + outline.bezierCurveTo(-.139, -.023, -.139, .027, -.129, .035); + outline.bezierCurveTo(-.106, .046, -.065, .044, -.035, .041); + outline.bezierCurveTo(.007, .044, .045, .048, .085, .047); + outline.bezierCurveTo(.122, .046, .137, .029, .136, .003); + outline.bezierCurveTo(.136, -.026, .125, -.044, .101, -.045); + outline.bezierCurveTo(.05, -.047, .017, -.041, -.03, -.037); + outline.bezierCurveTo(-.071, -.038, -.113, -.043, -.131, -.03); + const extrude = (depth, bevel) => new THREE.ExtrudeGeometry(outline, { + depth, bevelEnabled: true, bevelThickness: bevel, bevelSize: bevel, + bevelSegments: 3, steps: 1, curveSegments: 18 + }); + add(extrude(.003, .001), material(0x4a5756), .001); + add(extrude(.011, .002), material(0xe8e4d3), .006); + const thread = material(0xa4afa4); + const rim = outline.getPoints(90).map(point => new THREE.Vector3(point.x, point.y, .0155)); + add(new THREE.TubeGeometry(new THREE.CatmullRomCurve3(rim, true), 100, .0006, 4, true), thread); + // Loft an upper over the two authored ellipsoid profiles, with an actual + // open visual collar instead of drawing a black decal on a closed surface. + const cy = upper.position_m[1], base = .019; + const profile = x => { + let height = base, width = .0001; + for (const component of asset.geometry.filter(item => item.type === 'ellipsoid')) { + const u = (x - component.position_m[0]) / component.size_m[0]; + if (Math.abs(u) <= 1) { + const k = Math.sqrt(1 - u * u); + width = Math.max(width, component.size_m[1] * k); + height = Math.max(height, component.position_m[2] + component.size_m[2] * k); + } + } + return {height, width}; + }; + const roof = (x, y) => { + const p = profile(x), cross = Math.sqrt(Math.max(0, 1 - ((y - cy) / p.width) ** 2)); + return base + (p.height - base) * Math.pow(cross, .72); + }; + const hole = (x, y) => ((x + .079) / .027) ** 2 + ((y - cy) / .017) ** 2 < 1; + const position = [], uv = [], index = [], colors = []; + const nx = 96, ny = 48; + const navy = new THREE.Color(0x334d5a), heel = new THREE.Color(0x718279), toe = new THREE.Color(0xc4cdc2); + for (let i = 0; i <= nx; i++) { + const x = -.127 + .262 * i / nx, p = profile(x); + for (let j = 0; j <= ny; j++) { + const angle = Math.PI * j / ny, y = cy + p.width * Math.cos(angle); + const z = base + (p.height - base) * Math.pow(Math.sin(angle), .72); + position.push(x, y, z); uv.push(i / nx, j / ny); + const color = x < -.046 ? heel : x > .064 ? toe : navy; + colors.push(color.r, color.g, color.b); + } + } + const includeTriangle = (a, b, c) => { + const x = (position[a * 3] + position[b * 3] + position[c * 3]) / 3; + const y = (position[a * 3 + 1] + position[b * 3 + 1] + position[c * 3 + 1]) / 3; + if (!hole(x, y)) index.push(a, b, c); + }; + for (let i = 0; i < nx; i++) for (let j = 0; j < ny; j++) { + const a = i * (ny + 1) + j, b = a + ny + 1; + includeTriangle(a, b, a + 1); includeTriangle(b, b + 1, a + 1); + } + const upperGeometry = new THREE.BufferGeometry(); + upperGeometry.setAttribute('position', new THREE.Float32BufferAttribute(position, 3)); + upperGeometry.setAttribute('uv', new THREE.Float32BufferAttribute(uv, 2)); + upperGeometry.setAttribute('color', new THREE.Float32BufferAttribute(colors, 3)); + upperGeometry.setIndex(index); upperGeometry.computeVertexNormals(); + add(upperGeometry, new THREE.MeshStandardMaterial({map: fabric, vertexColors: true, roughness: .95, side: THREE.DoubleSide})); + const collar = []; + for (let i = 0; i <= 64; i++) { + const angle = i / 64 * Math.PI * 2, x = -.079 + .027 * Math.cos(angle), y = cy + .017 * Math.sin(angle); + collar.push(new THREE.Vector3(x, y, roof(x, y) + .0003)); + } + add(new THREE.TubeGeometry(new THREE.CatmullRomCurve3(collar, true), 80, .0022, 6, true), material(0x9daaa0)); + const inner = new THREE.SphereGeometry(1, 30, 20); inner.scale(.026, .016, .012); + const lining = add(inner, material(0x243532)); lining.position.set(-.079, cy, .047); + const tongue = [], tongueUV = [], tongueIndices = []; + for (let i = 0; i <= 14; i++) for (let j = 0; j <= 6; j++) { + const x = -.047 + i * .006, y = cy - .016 + j * .032 / 6; + tongue.push(x, y, Math.min(.087, roof(x, y) + .0006)); tongueUV.push(i / 14, j / 6); + } + for (let i = 0; i < 14; i++) for (let j = 0; j < 6; j++) { + const a = i * 7 + j, b = a + 7; tongueIndices.push(a, b, a + 1, b, b + 1, a + 1); + } + const tongueGeometry = new THREE.BufferGeometry(); + tongueGeometry.setAttribute('position', new THREE.Float32BufferAttribute(tongue, 3)); + tongueGeometry.setAttribute('uv', new THREE.Float32BufferAttribute(tongueUV, 2)); + tongueGeometry.setIndex(tongueIndices); tongueGeometry.computeVertexNormals(); + add(tongueGeometry, new THREE.MeshStandardMaterial({map: fabric, color: 0x7d8e85, roughness: 1, side: THREE.DoubleSide})); + const laces = material(0xeae7d5), eyeletMaterial = new THREE.MeshStandardMaterial({color: 0x8e9d92, metalness: .25, roughness: .6}); + for (let row = 0; row < 5; row++) { + const x = -.038 + row * .015, width = .020; + for (const side of [-1, 1]) { + const y = cy + side * width; + const eyelet = add(new THREE.TorusGeometry(.0023, .00055, 5, 12), eyeletMaterial); + eyelet.position.set(x, y, roof(x, y) + .001); + } + const points = [ + new THREE.Vector3(x, cy - width, roof(x, cy - width) + .0015), + new THREE.Vector3(x + .004, cy, Math.min(.088, roof(x + .004, cy) + .0013)), + new THREE.Vector3(x + .005, cy + width, roof(x + .005, cy + width) + .0015) + ]; + add(new THREE.TubeGeometry(new THREE.CatmullRomCurve3(points), 14, .0012, 5, false), laces); + } + for (const x of [-.046, .064]) { + const p = profile(x), panel = []; + for (let i = 0; i <= 32; i++) { + const angle = i / 32 * Math.PI, y = cy + p.width * Math.cos(angle); + panel.push(new THREE.Vector3(x, y, roof(x, y) + .0005)); + } + add(new THREE.TubeGeometry(new THREE.CatmullRomCurve3(panel), 36, .00055, 4, false), thread); + } +} +function authoredDetails(shoe, fabric) { + dressShoe(shoe, fabric); + // Original screen-printed worktop markings; physical surface remains the native box. + const print = new THREE.Mesh(new THREE.PlaneGeometry(.32, .08), + new THREE.MeshBasicMaterial({map: labelTexture('D V I D I A', 'MANIPULATION / STATION 01'), transparent: true, depthWrite: false})); + print.position.set(-.18, -.34, .0008); world.add(print); + const ruler = new THREE.Group(); + const rulerMat = new THREE.LineBasicMaterial({color: 0x8c896e, transparent: true, opacity: .6}); + const points = []; + for (let i = 0; i <= 30; i++) { + const x = .15 + i * .018; + points.push(new THREE.Vector3(x, -.405, .0008), new THREE.Vector3(x, -.405 + (i % 5 === 0 ? .016 : .007), .0008)); + } + ruler.add(new THREE.LineSegments(new THREE.BufferGeometry().setFromPoints(points), rulerMat)); world.add(ruler); + const trayOutline = new THREE.LineLoop(new THREE.BufferGeometry().setFromPoints([ + new THREE.Vector3(.19, .255, .113), new THREE.Vector3(.55, .255, .113), + new THREE.Vector3(.55, .401, .113), new THREE.Vector3(.19, .401, .113) + ]), new THREE.LineBasicMaterial({color: 0x8c795e, transparent: true, opacity: .4})); + world.add(trayOutline); +} +function requestRender() { + if (scheduled || !renderer || failed || document.hidden) return; + scheduled = true; + requestAnimationFrame(() => { + scheduled = false; + if (failed) return; + renderer.render(world, camera); + $('canvas').dataset.renderCount = String(++renderCount); + }); +} +function cameraPreset(name) { + if (!camera) return; + const center = new THREE.Vector3(...manifest.camera.target); + const portrait = Math.max(1, .95 / camera.aspect); + const offsets = { + perspective: new THREE.Vector3(...manifest.camera.position).sub(center), + top: new THREE.Vector3(.001, -.001, 1.8), + front: new THREE.Vector3(0, -1.85, .38) + }; + camera.position.copy(center).add((offsets[name] || offsets.perspective).clone().multiplyScalar(portrait)); + orbit.target.copy(center); orbit.update(); + document.querySelectorAll('[data-camera]').forEach(button => button.setAttribute('aria-pressed', String(button.dataset.camera === name))); + requestRender(); +} +function setupGeometry(bytes) { + assert($('canvas').getContext('webgl2'), 'WebGL2 is unavailable in this browser.'); + renderer = new THREE.WebGLRenderer({canvas: $('canvas'), antialias: true, powerPreference: 'high-performance'}); + renderer.setPixelRatio(Math.min(devicePixelRatio || 1, 2)); + renderer.outputColorSpace = THREE.SRGBColorSpace; + renderer.toneMapping = THREE.ACESFilmicToneMapping; renderer.toneMappingExposure = 1.05; + renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap; + world = new THREE.Scene(); world.background = new THREE.Color(0xe9e9de); + world.fog = new THREE.Fog(0xe9e9de, 4, 11); + camera = new THREE.PerspectiveCamera(37, 1, .01, 20); camera.up.set(0, 0, 1); + orbit = new OrbitControls(camera, $('canvas')); + orbit.minDistance = .25; orbit.maxDistance = 4.5; orbit.maxPolarAngle = Math.PI * .48; + orbit.screenSpacePanning = true; orbit.addEventListener('change', requestRender); + world.add(new THREE.HemisphereLight(0xfff8e9, 0xb1b5a5, 2.3)); + const sun = new THREE.DirectionalLight(0xfff1d6, 2.7); + sun.position.set(-1.1, -1.3, 3.5); sun.target.position.set(.2, 0, 0); + sun.castShadow = true; sun.shadow.mapSize.set(2048, 2048); + sun.shadow.camera.left = -1.4; sun.shadow.camera.right = 1.4; + sun.shadow.camera.top = 1.4; sun.shadow.camera.bottom = -1.4; + sun.shadow.camera.near = .1; sun.shadow.camera.far = 7; + sun.shadow.normalBias = .0008; sun.shadow.bias = -.00008; + sun.shadow.radius = 4; world.add(sun, sun.target); + const fill = new THREE.DirectionalLight(0xdce9f5, .9); + fill.position.set(1, 1, 2); world.add(fill); + bodies = model.bodies.map(() => { const group = new THREE.Group(); world.add(group); return group; }); + const meshes = new Map(), view = new DataView(bytes), wood = texture('wood'), fabric = texture('fabric'); + for (const source of model.meshes) { + const positions = new Float32Array(source.vertex_count * 3), indices = new Uint32Array(source.index_count); + for (let i = 0; i < positions.length; i++) positions[i] = view.getFloat32(source.position_byte_offset + i * 4, true); + for (let i = 0; i < indices.length; i++) indices[i] = view.getUint32(source.index_byte_offset + i * 4, true); + const geometry = new THREE.BufferGeometry(); + geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3)); + geometry.setIndex(new THREE.BufferAttribute(indices, 1)); geometry.computeVertexNormals(); + meshes.set(source.id, geometry); + } + let visualCount = 0; + for (const geom of model.geoms) { + const geometry = primitive(geom, meshes), name = geom.name || ''; + const isShoe = manifest.shoe_body_names.includes(model.bodies[geom.body_id].name); + if (geom.rgba[3] > 0 && geom.group <= 2 && !isShoe) { + const material = new THREE.MeshStandardMaterial({ + color: new THREE.Color().setRGB(...geom.rgba.slice(0, 3), THREE.LinearSRGBColorSpace), + metalness: .05, roughness: .66, transparent: geom.rgba[3] < 1, opacity: geom.rgba[3] + }); + if (name === manifest.environment_geoms.table || name === manifest.environment_geoms.rack) { + material.color.set(0xe9dcc1); material.map = wood; material.roughness = .78; material.metalness = 0; + } else if (name === manifest.environment_geoms.floor) { + material.color.set(0xd9ded1); material.roughness = 1; material.metalness = 0; + } else if (isShoe) { + material.color.set(name.includes('sole') ? 0xece8d7 : name.includes('heel') ? 0x788785 : 0x334d5e); + material.roughness = .97; material.metalness = 0; + if (!name.includes('sole')) material.map = fabric; + } else if (!name.startsWith('workstation_') && geom.type === 'mesh') { + const brightness = (geom.rgba[0] + geom.rgba[1] + geom.rgba[2]) / 3; + material.color.set(brightness > .35 ? 0xe3e1d7 : 0x223c4c); + material.roughness = .5; material.metalness = .15; + } + const mesh = new THREE.Mesh(geometry, material); + mesh.position.fromArray(geom.position); nativeQuaternion(geom.quaternion_wxyz, mesh.quaternion); + mesh.castShadow = geom.type !== 'plane'; mesh.receiveShadow = true; + bodies[geom.body_id].add(mesh); visualCount++; + } + if (geom.collision && geom.type !== 'plane') { + const wire = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({ + color: isShoe ? 0xe3a66d : 0x649d91, wireframe: true, transparent: true, opacity: .38, depthWrite: false + })); + wire.position.fromArray(geom.position); nativeQuaternion(geom.quaternion_wxyz, wire.quaternion); + wire.visible = false; wire.renderOrder = 3; bodies[geom.body_id].add(wire); collisionMeshes.push(wire); + } + } + const shoeIndex = model.bodies.findIndex(body => body.name === manifest.shoe_body_names[0]); + assert(shoeIndex >= 0, 'The native shoe is missing.'); shoeBody = bodies[shoeIndex]; + authoredDetails(shoeBody, fabric); + target = new THREE.Group(); world.add(target); + const marker = new THREE.Mesh(new THREE.SphereGeometry(.008, 20, 14), + new THREE.MeshBasicMaterial({color: 0x769f74, transparent: true, opacity: .7, depthTest: false})); + marker.renderOrder = 10; target.add(marker); + actualTool = new THREE.Mesh(new THREE.SphereGeometry(.0035, 16, 12), new THREE.MeshBasicMaterial({color: 0xdee9da})); + world.add(actualTool); + targetLine = new THREE.Line(new THREE.BufferGeometry().setFromPoints([new THREE.Vector3(), new THREE.Vector3()]), + new THREE.LineDashedMaterial({color: 0x819b71, dashSize: .008, gapSize: .005, transparent: true, opacity: .6})); + world.add(targetLine); + transform = new TransformControls(camera, $('canvas')); transform.setMode('translate'); transform.setSpace('world'); transform.setSize(.65); + transform.attach(target); transformHelper = transform.getHelper(); world.add(transformHelper); + transform.addEventListener('dragging-changed', event => { + manipulating = event.value; orbit.enabled = !event.value; + if (!event.value) flushTarget(); + requestRender(); + }); + transform.addEventListener('objectChange', () => { + if (settingTarget || !ready) return; + const position = boundedTarget(target.position.toArray()); + targetDraftDirty = false; $('target-error').textContent = ''; + target.position.fromArray(position); showTarget(position, true); queueTarget(position); + requestRender(); + }); + transform.addEventListener('change', requestRender); + new ResizeObserver(() => { + const rect = $('stage').getBoundingClientRect(); + if (rect.width < 1 || rect.height < 1) return; + const old = camera.aspect; camera.aspect = rect.width / rect.height; + camera.position.sub(orbit.target).multiplyScalar(Math.max(1, .95 / camera.aspect) / Math.max(1, .95 / old)).add(orbit.target); + camera.updateProjectionMatrix(); renderer.setSize(rect.width, rect.height, false); requestRender(); + }).observe($('stage')); + const rect = $('stage').getBoundingClientRect(); camera.aspect = rect.width / rect.height; + camera.updateProjectionMatrix(); renderer.setSize(rect.width, rect.height, false); cameraPreset('perspective'); + $('canvas').addEventListener('webglcontextlost', event => { event.preventDefault(); fail(new Error('WebGL was interrupted. Reload the workstation to restart.')); }); + $('stage').dataset.visualGeoms = String(visualCount); $('stage').dataset.collisionGeoms = String(collisionMeshes.length); + sceneReady = true; +} +function appendBounded(array, value, limit, droppedKey) { + if (array.length === limit) { array.shift(); receipt[droppedKey]++; } + array.push(value); +} +function command(value) { + if (!ready || failed) return; + worker.postMessage(value); + appendBounded(receipt.commands, {wall_ms: performance.now() - sessionStart, sim_time: latest?.sim_time ?? null, ...value}, 2000, 'commands_dropped'); +} +function boundedTarget(position) { return position.map((value, axis) => clamp(value, ...sceneBounds[axis])); } +function showTarget(position, force = false) { + for (const [index, axis] of ['x', 'y', 'z'].entries()) { + const input = $('target-' + axis); + if (force || (!targetDraftDirty && document.activeElement !== input)) input.value = String(Math.round(position[index] * 1000)); + } + $('height').value = String(Math.round(position[2] * 1000)); + $('height-value').textContent = (position[2] * 1000).toFixed(0) + ' mm'; +} +function setTarget(position, send = true) { + vec(position, 3); + const bounded = boundedTarget(position); + targetDraftDirty = false; + settingTarget = true; target.position.fromArray(bounded); settingTarget = false; + showTarget(bounded, true); $('target-error').textContent = ''; + if (send) queueTarget(bounded); + requestRender(); +} +function queueTarget(position) { + pendingTarget = position.slice(); + const wait = Math.max(0, 34 - (performance.now() - lastSentTargetAt)); + if (!targetTimer) targetTimer = setTimeout(flushTarget, wait); +} +function flushTarget() { + clearTimeout(targetTimer); targetTimer = null; + if (pendingTarget) { command({type: 'target', position: pendingTarget}); pendingTarget = null; lastSentTargetAt = performance.now(); } +} +function setJaw(value, send = true) { + const jaw = clamp(value, ...jawRange); + $('gripper').value = String(jaw * 1000); $('gripper-value').textContent = (jaw * 1000).toFixed(1) + ' mm'; + document.querySelector('.gripper-diagram').style.setProperty('--jaw-visual', (7 + jaw / jawRange[1] * 18) + 'px'); + if (send) command({type: 'gripper', jaw}); +} +function pause(paused) { + if (!ready || awaitingPause) return; + awaitingPause = true; $('pause').disabled = true; + command({type: 'pause', paused}); +} +function format(value, digits = 1) { return Number.isFinite(value) ? value.toFixed(digits) : '—'; } +function setStatus(state) { + if (failed) return; + const paused = state.paused === true; + const mode = paused ? 'paused' : 'running'; + if ($('session').dataset.state !== mode) { + $('session').dataset.state = mode; + $('session-label').textContent = paused ? 'Simulation paused' : 'Simulation running'; + } + $('pause').setAttribute('aria-pressed', String(paused)); + $('pause-label').textContent = paused ? 'Resume' : 'Pause'; + $('pause-icon').setAttribute('d', paused ? 'M6 4 16 10 6 16Z' : 'M7 5v10M13 5v10'); + $('live-status').textContent = paused ? 'Physics paused · camera stays active' : 'Live native physics'; + if (lastPause !== paused) { $('announcer').textContent = paused ? 'Simulation paused.' : 'Simulation running.'; lastPause = paused; } + awaitingPause = false; $('pause').disabled = !ready; +} +function applyState(state) { + const positions = state.body_pos, quaternions = state.body_quat; + vec(positions, bodies.length * 3); vec(quaternions, bodies.length * 4); + vec(state.tcp_position, 3); vec(state.target_position, 3); + assert(Number.isFinite(state.sim_time) && state.sim_time >= 0, 'Invalid native simulation time.'); + if (!reportedTarget || state.target_position.some((value, index) => Math.abs(value - reportedTarget[index]) > 1e-9)) { + reportedTarget = state.target_position.slice(); trackingErrorSince = null; + } + if (state.tracking_error_m > .005) { + if (trackingErrorSince === null || state.sim_time < trackingErrorSince) trackingErrorSince = state.sim_time; + } else trackingErrorSince = null; + const limited = trackingErrorSince !== null && state.sim_time - trackingErrorSince >= 4; + if (limited && !trackingLimited) $('announcer').textContent = 'The tool has not reached within five millimeters of this target after four simulated seconds. Try a closer target.'; + trackingLimited = limited; + bodies.forEach((body, index) => { + body.position.fromArray(positions, index * 3); + const offset = index * 4; + const norm = Math.hypot(...quaternions.slice(offset, offset + 4)); + assert(Math.abs(norm - 1) < .002, 'Invalid native body rotation.'); + body.quaternion.set(quaternions[offset + 1], quaternions[offset + 2], quaternions[offset + 3], quaternions[offset]); + }); + actualTool.position.fromArray(state.tcp_position); + if (!manipulating && pendingTarget === null && performance.now() - lastSentTargetAt > 150) { + settingTarget = true; target.position.fromArray(state.target_position); settingTarget = false; + showTarget(state.target_position); + } + const points = targetLine.geometry.attributes.position; + points.setXYZ(0, ...state.tcp_position); points.setXYZ(1, ...target.position.toArray()); + points.needsUpdate = true; targetLine.computeLineDistances(); targetLine.geometry.computeBoundingSphere(); + renderedPoses++; + $('stage').dataset.stateCount = String(stateCount); $('stage').dataset.simTime = String(state.sim_time); + $('stage').dataset.renderedPoses = String(renderedPoses); + const now = performance.now(); + if (now - lastSampleAt >= 100) { + appendBounded(receipt.samples, { + wall_ms: now - sessionStart, sim_time: state.sim_time, paused: state.paused, + tcp_position: state.tcp_position, target_position: state.target_position, + body_pos: state.body_pos, body_quat: state.body_quat, qpos: state.qpos, qvel: state.qvel, + ctrl: state.ctrl, actuator_force: state.actuator_force, jaw_target_m: state.jaw, + jaw_actual_m: state.actual_jaw, jaw_commanded_m: state.commanded_jaw, + contacts: state.contacts, contact_normal_force_total_n: state.contact_normal_force_total_n, + contact_normal_force_max_n: state.contact_normal_force_max_n, + tracking_error_m: state.tracking_error_m, metrics: state.metrics, warnings: state.warnings + }, 3000, 'samples_dropped'); + lastSampleAt = now; + } + setStatus(state); + if (now - lastMetricsAt >= 150) { + const time = state.sim_time, minutes = Math.floor(time / 60); + $('sim-time').textContent = String(minutes).padStart(2, '0') + ':' + (time % 60).toFixed(2).padStart(5, '0'); + $('tracking-error').textContent = format(state.tracking_error_m * 1000); + $('contacts').textContent = Number.isInteger(state.contacts) ? String(state.contacts) : '—'; + const metrics = state.metrics || {}; + $('step-p95').textContent = format(metrics.step_ms_p95, 2); + $('rtf').textContent = format(metrics.rtf, 2); + $('control-p95').textContent = format(metrics.control_ms_p95, 2) + ' ms'; + $('lag').textContent = format(metrics.lag_ms, 0) + ' ms'; + $('actual-jaw').textContent = format(state.actual_jaw * 1000, 1) + ' mm'; + $('contact-force').textContent = format(state.contact_normal_force_total_n, 2) + ' N'; + $('state-count').textContent = String(stateCount); + $('receipt-count').textContent = String(receipt.samples.length); + $('engine-version').textContent = state.engine || 'MuJoCo WASM'; + const warnings = (state.warnings || []).map(String).join(' · '); + $('warning').hidden = !warnings; $('warning').textContent = warnings; + $('tool-state').lastChild.textContent = limited ? ' Target not reached' : state.tracking_error_m > .005 ? ' Approaching' : ' Tracking'; + $('tool-state').dataset.state = limited ? 'limited' : 'tracking'; + $('tool-state').title = limited ? 'Target error remains above 5 mm after 4 simulated seconds. Workspace bounds do not guarantee reachability.' : 'Measured native tool position compared with the requested target.'; + lastMetricsAt = now; + } + requestRender(); +} +function becomeReady() { + if (!sceneReady || !workerReady || ready || failed) return; + ready = true; + document.querySelectorAll('button,input').forEach(element => { element.disabled = false; }); + setTarget(manifest.initial_target_xyz, false); + setJaw(latest?.jaw ?? manifest.home_ctrl[manifest.gripper_actuator_ids[0]], false); + $('loading').hidden = true; $('stage').dataset.ready = 'true'; + if (latest) applyState(latest); + if (document.hidden) pause(true); +} +function receiptDownload() { + flushTarget(); + const output = { + schema: 'dvidia.live-workstation-session/v1', opened_at: openedAt, exported_at: new Date().toISOString(), + source: {manifest_sha256: manifestDigest, compiled_model_sha256: manifest.compiled_model_sha256, + geometry_sha256: model.geometry_binary.sha256, native_version: manifest.native_version, + robot: manifest.robot, shoe_asset_ids: manifest.shoe_asset_ids}, + scope: 'Local browser interaction with privileged native simulator state. No learned policy, physical robot control, or grasp qualification.', + controller: manifest.controller, bounds_xyz: manifest.bounds_xyz, timestep: manifest.timestep, + control_dt: manifest.control_dt, interaction_limits: manifest.interaction_limits, + recording: {sample_wall_interval_ms: 100, sample_limit: 3000, command_limit: 2000, + received_states: stateCount, samples_dropped: receipt.samples_dropped, commands_dropped: receipt.commands_dropped, + note: 'Bounded recent samples and commands; wall timestamps continue across reset. Simulation time restarts on reset. UI samples may omit intervening physics steps.'}, + latest_metrics: latest?.metrics ?? null, commands: receipt.commands, samples: receipt.samples + }; + const url = URL.createObjectURL(new Blob([JSON.stringify(output, null, 2) + '\n'], {type: 'application/json'})); + const link = document.createElement('a'); link.href = url; + link.download = 'dvidia-workstation-session-' + new Date().toISOString().replace(/[:.]/g, '-') + '.json'; + document.body.append(link); link.click(); link.remove(); setTimeout(() => URL.revokeObjectURL(url), 30000); + $('announcer').textContent = 'Session receipt downloaded. Measurements remain on your device.'; +} +function connect() { + for (const axis of ['x', 'y', 'z']) { + $('target-' + axis).addEventListener('input', () => { + targetDraftDirty = true; + $('target-error').textContent = 'Coordinates edited. Apply target to send.'; + }); + } + document.querySelectorAll('[data-camera]').forEach(button => button.addEventListener('click', () => cameraPreset(button.dataset.camera))); + $('home-camera').addEventListener('click', () => cameraPreset('perspective')); + $('focus-shoe').addEventListener('click', () => { + orbit.target.copy(shoeBody.position).add(new THREE.Vector3(0, 0, .05)); + camera.position.copy(orbit.target).add(new THREE.Vector3(.48, -.65, .42).multiplyScalar(Math.max(1, .7 / camera.aspect))); + orbit.update(); document.querySelectorAll('[data-camera]').forEach(button => button.setAttribute('aria-pressed', 'false')); + requestRender(); + }); + $('gizmo').addEventListener('click', () => { + const visible = $('gizmo').getAttribute('aria-pressed') !== 'true'; + $('gizmo').setAttribute('aria-pressed', String(visible)); + transformHelper.visible = visible; transform.enabled = visible; target.visible = visible; targetLine.visible = visible; + requestRender(); + }); + $('collision').addEventListener('click', () => { + const visible = $('collision').getAttribute('aria-pressed') !== 'true'; + $('collision').setAttribute('aria-pressed', String(visible)); + collisionMeshes.forEach(mesh => { mesh.visible = visible; }); + $('scene-caption').textContent = visible ? 'Native collision wireframes over visual geometry.' : 'One arm. One object. Interactive local simulation.'; + requestRender(); + }); + $('target-form').addEventListener('submit', event => { + event.preventDefault(); + const position = ['x', 'y', 'z'].map(axis => $('target-' + axis).valueAsNumber / 1000); + if (!position.every((value, axis) => Number.isFinite(value) && value >= sceneBounds[axis][0] - 1e-9 && value <= sceneBounds[axis][1] + 1e-9)) { + $('target-error').textContent = 'Use coordinates inside the displayed workspace bounds.'; return; + } + setTarget(position); flushTarget(); + }); + $('reset-target').addEventListener('click', () => { + if (!latest) return; setTarget(latest.tcp_position); flushTarget(); + if (latest.tcp_position.some((n, i) => n < sceneBounds[i][0] || n > sceneBounds[i][1])) { + $('target-error').textContent = 'The current tool is outside the command volume; target moved to the nearest allowed position.'; + } + }); + $('height').addEventListener('input', () => setTarget([target.position.x, target.position.y, $('height').valueAsNumber / 1000])); + $('height').addEventListener('change', flushTarget); + $('gripper').addEventListener('input', () => setJaw($('gripper').valueAsNumber / 1000)); + $('pause').addEventListener('click', () => pause(!latest?.paused)); + $('reset').addEventListener('click', () => { + clearTimeout(targetTimer); targetTimer = null; pendingTarget = null; + command({type: 'reset'}); setTarget(manifest.initial_target_xyz, false); + setJaw(manifest.home_ctrl[manifest.gripper_actuator_ids[0]], false); + $('announcer').textContent = 'Reset requested. The original arm and shoe state will be restored.'; + }); + $('push').addEventListener('click', () => { + const impulse = Math.min(.12, manifest.interaction_limits.push_impulse_norm_max_ns); + command({type: 'push', body: manifest.shoe_body_names[0], impulse: [0, impulse, 0]}); + $('announcer').textContent = latest?.paused + ? 'Nudge queued. Resume the simulation to apply it.' + : 'Nudge requested: ' + impulse.toFixed(2) + ' newton seconds toward positive Y.'; + }); + $('receipt').addEventListener('click', receiptDownload); + $('canvas').addEventListener('keydown', event => { + if (!ready) return; + if (['h', 'H', 'Home'].includes(event.key)) { event.preventDefault(); cameraPreset('perspective'); } + else if (event.key === ' ') { event.preventDefault(); pause(!latest?.paused); } + else if (['+', '=', '-', '_'].includes(event.key)) { + event.preventDefault(); + const offset = camera.position.clone().sub(orbit.target); + offset.setLength(clamp(offset.length() * (['+', '='].includes(event.key) ? .9 : 1 / .9), orbit.minDistance, orbit.maxDistance)); + camera.position.copy(orbit.target).add(offset); orbit.update(); requestRender(); + } + }); + document.addEventListener('visibilitychange', () => { + if (document.hidden && ready && !latest?.paused) pause(true); + if (!document.hidden) requestRender(); + }); + window.addEventListener('pagehide', () => worker?.terminate()); +} +function fail(error) { + if (failed) return; + failed = true; ready = false; worker?.terminate(); clearTimeout(targetTimer); + $('session').dataset.state = 'error'; $('session-label').textContent = 'Simulation unavailable'; + $('loading').hidden = false; $('loading').classList.add('error'); + $('loading-title').textContent = 'The workstation could not continue'; + $('loading-message').textContent = error?.message || String(error); + $('stage').dataset.ready = 'error'; + $('live-status').textContent = 'Physics stopped'; + document.querySelectorAll('button,input').forEach(element => { element.disabled = true; }); + $('retry-download').hidden = false; $('retry-download').disabled = false; + // Preserve the session's evidence if an engine or renderer failure occurs. + if (receipt.samples.length) $('receipt').disabled = false; + $('announcer').textContent = $('loading-message').textContent; +} +async function main() { + assert(['http:', 'https:'].includes(location.protocol), 'Serve the exported workstation over local HTTP or HTTPS.'); + assert(typeof Worker === 'function', 'This browser does not support local physics workers.'); + const manifestBytes = await fetchBytes('workstation.json', 4 * 1024 * 1024); + manifest = JSON.parse(new TextDecoder().decode(manifestBytes)); manifestDigest = await digest(manifestBytes); + assert(manifest.schema === 'dvidia.live-workstation/v1' && manifest.physical_robot_ready === false + && manifest.learned_policy === false, 'Unsupported workstation manifest.'); + assert(Array.isArray(manifest.bounds_xyz) && manifest.bounds_xyz.length === 3, 'Missing target workspace bounds.'); + sceneBounds = manifest.bounds_xyz.map(bounds => { vec(bounds, 2); assert(bounds[1] > bounds[0], 'Invalid workspace bounds.'); return bounds; }); + jawRange = vec(manifest.controller.gripper_range_m, 2); + vec(manifest.initial_target_xyz, 3); vec(manifest.camera.position, 3); vec(manifest.camera.target, 3); + assert(Number.isFinite(manifest.interaction_limits.push_impulse_norm_max_ns) && manifest.interaction_limits.push_impulse_norm_max_ns > 0, + 'Missing physical disturbance limit.'); + for (const [index, axis] of ['x', 'y', 'z'].entries()) { + $('target-' + axis).min = String(sceneBounds[index][0] * 1000); + $('target-' + axis).max = String(sceneBounds[index][1] * 1000); + $('target-' + axis).title = Math.round(sceneBounds[index][0] * 1000) + ' to ' + Math.round(sceneBounds[index][1] * 1000) + ' mm'; + } + $('height').min = String(sceneBounds[2][0] * 1000); $('height').max = String(sceneBounds[2][1] * 1000); + $('height-min').textContent = Math.round(sceneBounds[2][0] * 1000) + ' mm'; + $('height-max').textContent = Math.round(sceneBounds[2][1] * 1000) + ' mm'; + $('gripper').min = String(jawRange[0] * 1000); $('gripper').max = String(jawRange[1] * 1000); + $('physics-step').textContent = format(manifest.timestep * 1000, 0) + ' ms'; + worker = new Worker('./workstation_worker.bundle.js', {type: 'module'}); + worker.addEventListener('error', event => fail(new Error(event.message || 'The local physics worker stopped unexpectedly.'))); + worker.addEventListener('message', event => { + try { + const message = event.data; + if (message.type === 'error') { fail(new Error(message.message)); return; } + if (message.type === 'ready' || message.type === 'state') { + if (!message.state) return; + latest = message.state; stateCount++; lastStateAt = performance.now(); + if (message.type === 'ready') workerReady = true; + if (ready) applyState(latest); else becomeReady(); + worker.postMessage({type: 'ack'}); + } else if (message.type === 'progress') { + if (message.download) downloadProgress(message.download); + else if (!failed) $('loading-message').textContent = String(message.message || 'Preparing the native physics engine.'); + } + } catch (error) { fail(error); } + }); + worker.postMessage({type: 'init', manifest_url: new URL('workstation.json', location.href).href}); + [model, catalog] = await Promise.all([loadJSON(manifest.model_url), loadJSON('catalog.json')]); + const geometry = await loadGeometry(model.geometry_binary); validateGeometry(geometry); + setupGeometry(geometry); connect(); + const asset = catalog.shoes.find(item => item.id === manifest.shoe_asset_ids[0]); + assert(asset, 'The shoe is missing from the asset catalog.'); + $('object-name').textContent = asset.name; + $('object-mass').textContent = format(asset.properties.mass_kg.value * 1000, 0) + ' g'; + $('object-friction').textContent = format(asset.properties.sliding_friction.value, 2) + ' μ'; + becomeReady(); + setInterval(() => { + if (!ready || failed || latest?.paused || document.hidden) return; + if (lastStateAt && performance.now() - lastStateAt > 2000) { + $('live-status').textContent = 'Waiting for physics updates'; + $('session').dataset.state = 'loading'; $('session-label').textContent = 'Waiting for physics'; + } + }, 1000); +} +$('retry-download').addEventListener('click', () => location.reload()); +main().catch(fail); diff --git a/src/dvidia_training/workstation.py b/src/dvidia_training/workstation.py new file mode 100644 index 0000000..3e8ac05 --- /dev/null +++ b/src/dvidia_training/workstation.py @@ -0,0 +1,525 @@ +"""Live native PiPER workstation: authored pose tracking, synthetic free shoes. + +Target tracking uses native position actuators and damped differential IK. The +scene contains no shoe weld, grasp attachment, hidden carrying force or policy +trained from footage. Rich visual detail is separate from collision evidence. +""" +from __future__ import annotations + +import argparse +from hashlib import sha256 +import gzip +import io +import json +import math +from pathlib import Path +from pathlib import PurePosixPath +import re +import tempfile +import shutil +import xml.etree.ElementTree as ET +import zlib + +from . import asset_library, asset_preview, reference_sim as sim, robot_profiles + +SCHEMA = 'dvidia.live-workstation/v1' +INTEGRITY_SCHEMA = 'dvidia.live-workstation-integrity/v1' +MAX_FILE_BYTES = 64 * 1024 * 1024 +MAX_TOTAL_BYTES = 128 * 1024 * 1024 +RUNTIME_FILES = {'index.html':'workstation.html', + 'workstation.bundle.js':'workstation.bundle.js', + 'workstation_worker.bundle.js':'workstation_worker.bundle.js', + 'mujoco.wasm':'mujoco.wasm', + 'workstation.third-party.txt':'workstation.third-party.txt'} +TIMESTEP = .002 +CONTROL_DT = .02 +TCP = 'workstation_tcp' +SHOE = 'shoe_trainer_left' +HOME_TARGET = (.36, -.06, .27) +ORIENTATION = (math.cos(5 * math.pi / 12), 0., math.sin(5 * math.pi / 12), 0.) +BOUNDS = ((.18, .54), (-.24, .24), (.055, .34)) +CONTROLLER = {'orientation_weight': .25, 'translation_error_cap_m': .045, + 'rotation_error_cap_rad': .15, 'damping': .012, + 'max_joint_delta_rad': .18, 'joint_margin_rad': .02, + 'joint_rate_rad_s': 1.5, 'gripper_rate_m_s': .05, + 'gripper_range_m': [0., .035]} +SCOPE = ('Live native PiPER position tracking with authored IK, pinned upstream ' + 'mechanics and a free synthetic rigid shoe. No learned shoe manipulation ' + 'policy, calibrated shoe contact, deformation or hardware qualification.') + + +def _json(value): + return (json.dumps(value, indent=2, allow_nan=False) + '\n').encode() + + +def _vec(value, count, label, low=-10., high=10.): + if not isinstance(value, (tuple, list)) or len(value) != count: + raise ValueError(label + ' requires ' + str(count) + ' values') + if any(type(x) not in (int, float) or not low <= x <= high or not math.isfinite(x) for x in value): + raise ValueError(label + ' must contain bounded finite numbers') + return list(map(float, value)) + + +def _spec(assets): + spec = asset_library._robot_spec('piper', assets, TIMESTEP) + mj, _ = sim._native_imports() + spec.modelname = 'dvidia_live_piper_workstation_v01' + spec.body('link6').add_site(name=TCP, pos=[0, 0, .12003], size=[.004, 0, 0], rgba=[.18,.65,.49,1]) + world = spec.worldbody + world.add_geom(name='workstation_floor', type=mj.mjtGeom.mjGEOM_PLANE, + pos=[0,0,-.8], size=[2,2,.1], rgba=[.82,.84,.79,1]) + world.add_geom(name='workstation_table_top', type=mj.mjtGeom.mjGEOM_BOX, + pos=[.22,0,-.04], size=[.65,.46,.04], rgba=[.62,.43,.26,1]) + for index,(x,y) in enumerate(((-.34,-.37),(-.34,.37),(.77,-.37),(.77,.37))): + world.add_geom(name='workstation_table_leg_'+str(index),type=mj.mjtGeom.mjGEOM_BOX, + pos=[x,y,-.44],size=[.028,.028,.36],rgba=[.16,.19,.20,1]) + world.add_geom(name='workstation_rack_shelf',type=mj.mjtGeom.mjGEOM_BOX, + pos=[.37,.33,.10],size=[.20,.10,.012],rgba=[.49,.35,.23,1]) + for index,x in enumerate((.165,.575)): + world.add_geom(name='workstation_rack_side_'+str(index),type=mj.mjtGeom.mjGEOM_BOX, + pos=[x,.33,.065],size=[.012,.11,.065],rgba=[.23,.27,.26,1]) + world.add_geom(name='workstation_rack_back',type=mj.mjtGeom.mjGEOM_BOX, + pos=[.37,.435,.065],size=[.20,.009,.065],rgba=[.23,.27,.26,1]) + shoe = next(item for item in asset_library.catalog()['shoes'] if item['id']=='trainer-left') + body = world.add_body(name=SHOE,pos=[.32,-.145,.012],gravcomp=0) + body.add_freejoint(name=SHOE+'_free') + properties=shoe['properties'] + for piece in shoe['geometry']: + body.add_geom(name=SHOE+'_'+piece['name'], + type={'box':mj.mjtGeom.mjGEOM_BOX,'ellipsoid':mj.mjtGeom.mjGEOM_ELLIPSOID}[piece['type']], + pos=piece['position_m'],size=piece['size_m'],mass=properties['mass_kg']['value']*piece['mass_fraction'], + rgba=piece['rgba'],contype=1,conaffinity=1,condim=4,priority=1, + friction=[properties[name]['value'] for name in ('sliding_friction','torsional_friction','rolling_friction')], + solref=[.02,1],solimp=[.9,.95,.001,.5,2]) + return spec + + +def build_model(assets): + spec=_spec(assets) + mj,_=sim._native_imports() + # Canonical XML is the identical input used by the browser engine. + model=mj.MjModel.from_xml_string(spec.to_xml(),assets=spec.assets) + if (model.nq,model.nv,model.nu,model.neq,model.nmocap)!=(15,14,7,1,0): + raise ValueError('Workstation mechanical dimensions differ from the pinned PiPER contract') + return model + + +def _ids(model): + mj,_=sim._native_imports() + if model.names.split(b'\0',1)[0] != b'dvidia_live_piper_workstation_v01': + raise ValueError('Expected a native workstation model') + tcp=mj.mj_name2id(model,mj.mjtObj.mjOBJ_SITE,TCP) + shoe=mj.mj_name2id(model,mj.mjtObj.mjOBJ_BODY,SHOE) + if tcp<0 or shoe<0: + raise ValueError('Workstation TCP or shoe is missing') + return tcp,shoe + + +def controller_action(model,data,target_position_m,gripper_position_m,*,validate=True): + """One 20 ms differential-IK target; does not mutate physics or teleport bodies.""" + target=_vec(target_position_m,3,'target') + if validate and any(not bounds[0]<=value<=bounds[1] for value,bounds in zip(target,BOUNDS)): + raise ValueError('Target is outside the bounded workstation volume') + jaw=_vec([gripper_position_m],1,'gripper',0,.035)[0] + mj,np=sim._native_imports() + tcp,_=_ids(model) + jacp,jacr=np.zeros((3,model.nv)),np.zeros((3,model.nv)) + mj.mj_jacSite(model,data,jacp,jacr,tcp) + current,rotation=np.empty(4),np.empty(3) + mj.mju_mat2Quat(current,data.site_xmat[tcp]) + mj.mju_subQuat(rotation,np.asarray(ORIENTATION),current) + rotation=data.site_xmat[tcp].reshape(3,3)@rotation + translation=np.asarray(target)-data.site_xpos[tcp] + for vector,limit in ((translation,CONTROLLER['translation_error_cap_m']),(rotation,CONTROLLER['rotation_error_cap_rad'])): + norm=float(np.linalg.norm(vector)) + if norm>limit:vector*=limit/norm + weight=CONTROLLER['orientation_weight'] + jac=np.vstack((jacp[:,:6],weight*jacr[:,:6])) + error=np.concatenate((translation,weight*rotation)) + delta=jac.T@np.linalg.solve(jac@jac.T+CONTROLLER['damping']**2*np.eye(6),error) + targets=np.clip(data.qpos[:6]+np.clip(delta,-CONTROLLER['max_joint_delta_rad'],CONTROLLER['max_joint_delta_rad']), + model.actuator_ctrlrange[:6,0]+CONTROLLER['joint_margin_rad'], + model.actuator_ctrlrange[:6,1]-CONTROLLER['joint_margin_rad']) + return np.concatenate((targets,[jaw])) + + +def initialize(model): + """Initialize a declared home pose; no simulation time or shoe settling hidden.""" + mj,np=sim._native_imports();_ids(model) + data=mj.MjData(model) + data.qpos[:8]=[0,1.57,-1.3485,0,0,0,.035,-.035] + # Solve only the robot's initial pose. This reset-only kinematic solve is not + # used when responding to target changes or interacting with the shoe. + for _ in range(180): + mj.mj_forward(model,data) + command=controller_action(model,data,HOME_TARGET,.035) + data.qpos[:6]=command[:6] + data.qvel[:]=0 + data.ctrl[:6]=data.qpos[:6] + data.ctrl[6]=.035 + mj.mj_forward(model,data) + if not np.isfinite(data.qpos).all():raise ValueError('Invalid workstation home state') + return data + + +def run_control(model,data,controller_state,target_position_m,gripper_position_m,substeps=10,*,impulse_xyz=None): + """Advance bounded native ticks, retaining the 20 ms controller clock. + + Pass the same initially empty dictionary on every call. Target packets can + arrive at rendering frequency; desired joint commands update every ten native + steps, independently of rendering. The returned state is privileged truth. + """ + if type(substeps) is not int or not 1<=substeps<=100: + raise ValueError('substeps must be an integer in [1,100]') + if type(controller_state) is not dict or set(controller_state)-{'native_steps','desired_ctrl'}: + raise ValueError('Controller state requires its own empty or initialized dictionary') + if type(controller_state.get('native_steps',0)) is not int or controller_state.get('native_steps',0)<0: + raise ValueError('Controller native step count is invalid') + mj,np=sim._native_imports();_,shoe=_ids(model) + target=_vec(target_position_m,3,'target') + if any(not bounds[0]<=value<=bounds[1] for value,bounds in zip(target,BOUNDS)): + raise ValueError('Target is outside the bounded workstation volume') + jaw=_vec([gripper_position_m],1,'gripper',0,.035)[0] + impulse=None if impulse_xyz is None else _vec(impulse_xyz,3,'shoe impulse',-.12,.12) + if impulse is not None and float(np.linalg.norm(impulse)) > .12 + 1e-12: + raise ValueError('Shoe impulse norm exceeds 0.12 N s') + for index in range(substeps): + native_steps=controller_state.get('native_steps',0) + if native_steps%10==0 or 'desired_ctrl' not in controller_state: + controller_state['desired_ctrl']=controller_action(model,data,target,jaw).tolist() + targets=np.asarray(_vec(controller_state['desired_ctrl'],7,'desired controls')) + data.ctrl[:6]+=np.clip(targets[:6]-data.ctrl[:6],-CONTROLLER['joint_rate_rad_s']*TIMESTEP,CONTROLLER['joint_rate_rad_s']*TIMESTEP) + data.ctrl[6]+=float(np.clip(targets[6]-data.ctrl[6],-CONTROLLER['gripper_rate_m_s']*TIMESTEP,CONTROLLER['gripper_rate_m_s']*TIMESTEP)) + data.xfrc_applied[:]=0 + if impulse is not None and index==0:data.xfrc_applied[shoe,:3]=np.asarray(impulse)/TIMESTEP + mj.mj_step(model,data) + data.xfrc_applied[:]=0 + mj.mj_forward(model,data) + if not all(np.isfinite(x).all() for x in (data.qpos,data.qvel,data.qacc)) or any(w.number for w in data.warning): + raise RuntimeError('Invalid workstation native state or solver warning') + controller_state['native_steps']=native_steps+1 + return state(model,data,target_position_m) + + +def step(model,data,target_position_m,gripper_position_m,*,impulse_xyz=None): + """Convenience wrapper for exactly one complete 20 ms control interval.""" + return run_control(model,data,{},target_position_m,gripper_position_m,10,impulse_xyz=impulse_xyz) + + +def protocol(): + """Deterministic initial state and authored tracking sequence for parity tests. + + Numeric tolerances below are proposed test criteria, not reported outcomes. + This is target tracking; none of these targets constitutes a grasp policy. + """ + return {'schema':'dvidia.live-workstation-protocol/v1','scope':SCOPE, + 'timestep':TIMESTEP,'control_dt':CONTROL_DT,'orientation_wxyz':list(ORIENTATION), + 'actions':[{'name':name,'target':list(target),'jaw':jaw,'control_steps':100} + for name,target,jaw in [('home',HOME_TARGET,.035), + ('above_shoe',(.32,-.145,.18),.035), + ('inspect_front',(.42,-.02,.20),.035), + ('inspect_side',(.32,.12,.18),.035), + ('close_clear',HOME_TARGET,0.),('open_clear',HOME_TARGET,.035)]], + 'acceptance':{'settled_position_error_m':.005,'settled_orientation_error_rad':math.radians(3), + 'solver_warnings':0,'unintended_moving_arm_contacts':0, + 'native_browser_position_tolerance_m':.001, + 'scope':'Declared target values require measured native and browser results; no automatic qualification.'}} + + +def state(model,data,target_position_m=None): + mj,np=sim._native_imports();tcp,shoe=_ids(model) + contacts=[] + for i in range(data.ncon): + c=data.contact[i];force=np.zeros(6);mj.mj_contactForce(model,data,i,force) + if force[0]>.001:contacts.append({'geom1':int(c.geom1),'geom2':int(c.geom2),'normal_force_n':float(force[0])}) + quaternion=np.empty(4);mj.mju_mat2Quat(quaternion,data.site_xmat[tcp]) + return {'time':float(data.time),'qpos':data.qpos.tolist(),'ctrl':data.ctrl.tolist(), + 'body_positions':data.xpos.tolist(),'body_quaternions':data.xquat.tolist(), + 'tcp_position':data.site_xpos[tcp].tolist(),'tcp_quaternion':quaternion.tolist(), + 'shoe_position':data.xpos[shoe].tolist(),'contacts':contacts, + 'position_error_m':None if target_position_m is None else float(np.linalg.norm(data.site_xpos[tcp]-target_position_m)), + 'observation_origin':'privileged native simulator state'} + + +def metadata(model,data): + mj,_=sim._native_imports();tcp,shoe=_ids(model) + joints=[mj.mj_name2id(model,mj.mjtObj.mjOBJ_JOINT,'joint'+str(i)) for i in range(1,7)] + return {'schema':SCHEMA,'scope':SCOPE,'physical_robot_ready':False,'learned_policy':False, + 'robot':'piper','timestep':TIMESTEP,'control_dt':CONTROL_DT,'scene_url':'scene.xml', + 'model_url':'model.json','geometry_url':'geometry.bin.gz','tcp_site_name':TCP,'tcp_site_id':tcp, + 'joint_names':['joint'+str(i) for i in range(1,7)],'joint_ids':joints, + 'arm_qpos_addresses':[int(model.jnt_qposadr[j]) for j in joints], + 'arm_dof_addresses':[int(model.jnt_dofadr[j]) for j in joints], + 'actuator_names':['joint'+str(i) for i in range(1,7)],'actuator_ids':list(range(6)), + 'gripper_actuator_names':['gripper'],'gripper_actuator_ids':[6], + 'actuator_ctrlrange':model.actuator_ctrlrange.tolist(), + 'home_qpos':data.qpos.tolist(),'home_ctrl':data.ctrl.tolist(), + 'initial_target_xyz':list(HOME_TARGET),'bounds_xyz':[list(row) for row in BOUNDS], + 'orientation_wxyz':list(ORIENTATION),'controller':dict(CONTROLLER), + 'shoe_body_names':[SHOE],'shoe_body_ids':[shoe],'shoe_asset_ids':['trainer-left'], + 'native_version':mj.__version__,'compiled_model_sha256':sim.model_digest(model), + 'camera':{'target':[.24,0,.10],'position':[1.02,-1.45,1.02]}, + 'environment_geoms':{'table':'workstation_table_top','rack':'workstation_rack_shelf','floor':'workstation_floor'}, + 'interaction_limits':{'push_impulse_norm_max_ns':.12, 'push_duration_s':TIMESTEP, + 'grip_scope':'Jaw motion and native contacts are available; no validated retained shoe lift or autonomous placement.'}} + + +def export(assets,output,*,runtime_directory=None): + """Export native XML/verified meshes plus renderer geometry and metadata.""" + destination=Path(output) + if destination.exists() or destination.is_symlink():raise ValueError('Workstation output must be fresh') + item,blobs=robot_profiles._payload('piper',assets) + spec=_spec(assets);native_xml=spec.to_xml().encode() + mj,_=sim._native_imports() + model=mj.MjModel.from_xml_string(native_xml.decode(),assets=spec.assets);data=initialize(model) + manifest=metadata(model,data) + manifest['provenance']=robot_profiles.verify_assets('piper',assets) + scene,geometry=asset_preview._scene(model,{'robot':'piper','native_version':manifest['native_version'], + 'compiled_model_sha256':manifest['compiled_model_sha256'],'scope':SCOPE}) + scene.update(schema='dvidia.live-workstation-model/v1',scope=SCOPE) + packed=gzip.compress(geometry,mtime=0) + scene['geometry_binary']={'href':'geometry.bin.gz','compression':'gzip','bytes':len(geometry), + 'compressed_bytes':len(packed),'compressed_sha256':sha256(packed).hexdigest(),'sha256':sha256(geometry).hexdigest()} + files={'scene.xml':native_xml,'model.json':_json(scene),'geometry.bin.gz':packed, + 'catalog.json':_json(asset_library.catalog()),'LICENSE':asset_preview.replay.MIT_LICENSE.encode(), + 'licenses/agilex_piper/LICENSE':blobs[item['folder']+'/LICENSE'], + 'licenses/agilex_piper/README.md':blobs[item['folder']+'/README.md']} + for path,raw in blobs.items(): + local=path.removeprefix(item['folder']+'/') + if local.startswith('assets/'):files[local]=raw + manifest['assets']=[{'path':name,'bytes':len(raw),'sha256':sha256(raw).hexdigest()} for name,raw in sorted(files.items()) if name.startswith('assets/')] + native_assets=b''.join(files[asset['path']] for asset in manifest['assets']) + files['native-assets.bin.gz']=gzip.compress(native_assets,mtime=0) + manifest['native_asset_bundle']={'path':'native-assets.bin.gz','compression':'gzip', + 'bytes':len(files['native-assets.bin.gz']),'sha256':sha256(files['native-assets.bin.gz']).hexdigest(), + 'uncompressed_bytes':len(native_assets)} + manifest['native_scene']={'path':'scene.xml','bytes':len(files['scene.xml']),'sha256':sha256(files['scene.xml']).hexdigest()} + runtime=Path(runtime_directory) if runtime_directory is not None else Path(__file__).parent + if runtime.is_symlink() or not runtime.is_dir(): + raise ValueError('Runtime directory must be a plain directory') + for name,source in RUNTIME_FILES.items(): + files[name]=asset_preview.replay._read(runtime/source,MAX_FILE_BYTES) + manifest['native_wasm']={'path':'mujoco.wasm','bytes':len(files['mujoco.wasm']), + 'sha256':sha256(files['mujoco.wasm']).hexdigest()} + files['mujoco.wasm.gz']=gzip.compress(files['mujoco.wasm'],mtime=0) + manifest['wasm_bundle']={'path':'mujoco.wasm.gz','compression':'gzip', + 'bytes':len(files['mujoco.wasm.gz']),'sha256':sha256(files['mujoco.wasm.gz']).hexdigest(), + 'uncompressed_bytes':len(files['mujoco.wasm'])} + files['README.md']=("# DVIDIA live shoe workstation v0.1\n\n"+SCOPE+"\n\n" + "Serve this folder with `python -m http.server 8000` and open http://localhost:8000. " + "It runs MuJoCo physics in a browser worker. JavaScript, WebAssembly, WebGL2 and " + "DecompressionStream are required. No model download, remote inference or GPU training " + "is needed; physics runs locally on the CPU and rendering uses WebGL. Browser performance " + "depends on the machine. All assets and runtime files are included.\n\n" + "For faster startup, native-assets.bin.gz delivers the original mesh bytes in one " + "compressed request. Each unpacked mesh is checked against its original SHA-256. " + "The raw assets remain included for independent reproduction.\n\n" + "The physics engine also downloads compressed, with its decoded SHA-256 verified. " + "Interrupted downloads make up to three attempts with a 30-second idle timeout and " + "a 120-second total deadline per resource. Progress and a reload button expose recovery.\n\n" + "The official Hugging Face workstation uses a DVIDIA-hosted mirror for three pinned " + "compressed assets, with size and SHA-256 checks and bounded Hugging Face fallback. " + "Local exports load their own files and work offline after initial provisioning.\n\n" + "Native PiPER meshes and MIT notices are pinned to the upstream commit in workstation.json. " + "The rigid procedural shoe is MIT, with assumed untested physical properties in catalog.json. " + "The controller is authored differential IK, not a learned policy. The jaw can make physical " + "contacts; retained shoe lifting is not qualified. MuJoCo and Three.js notices are in " + "workstation.third-party.txt. Integrity hashes check file consistency, not authenticity.\n").encode() + files['workstation.json']=_json(manifest) + seal={'schema':INTEGRITY_SCHEMA,'scope':'Artifact consistency, not authenticity or physical qualification', + 'files':{name:{'bytes':len(raw),'sha256':sha256(raw).hexdigest()} for name,raw in sorted(files.items())}} + files['workstation-integrity.json']=_json(seal) + if any(len(raw)>MAX_FILE_BYTES for raw in files.values()) or sum(map(len,files.values()))>MAX_TOTAL_BYTES: + raise ValueError('Workstation exceeds bounded export size') + destination.parent.mkdir(parents=True,exist_ok=True) + staging=Path(tempfile.mkdtemp(prefix='.dvidia-workstation-',dir=destination.parent)) + try: + for name,raw in files.items(): + path=staging/name;path.parent.mkdir(parents=True,exist_ok=True) + with path.open('xb') as stream:stream.write(raw) + inspected=inspect_export(staging) + if destination.exists() or destination.is_symlink(): + raise ValueError('Workstation output must remain fresh') + staging.rename(destination) + finally: + if staging.exists():shutil.rmtree(staging) + return {**inspected,'initial':state(model,data,HOME_TARGET)} + + +def _unpack_native_assets(bundle,assets,payload): + """Validate optional delivery compression without changing native inputs.""" + expected_keys={'path','compression','bytes','sha256','uncompressed_bytes'} + total=sum(asset['bytes'] for asset in assets) + if (type(bundle) is not dict or set(bundle)!=expected_keys + or bundle['path']!='native-assets.bin.gz' or bundle['compression']!='gzip' + or type(bundle['bytes']) is not int or not 0<=bundle['bytes']<=MAX_FILE_BYTES + or type(bundle['sha256']) is not str or re.fullmatch('[a-f0-9]{64}',bundle['sha256']) is None + or type(bundle['uncompressed_bytes']) is not int or bundle['uncompressed_bytes']!=total + or not 0<=total<=MAX_TOTAL_BYTES): + raise ValueError('Workstation native asset bundle descriptor mismatch') + packed=payload.get(bundle['path']) + if packed is None or len(packed)!=bundle['bytes'] or sha256(packed).hexdigest()!=bundle['sha256']: + raise ValueError('Workstation native asset bundle checksum mismatch') + try: + with gzip.GzipFile(fileobj=io.BytesIO(packed),mode='rb') as stream: + unpacked=stream.read(total+1) + except (OSError,EOFError,zlib.error) as exc: + raise ValueError('Invalid compressed native asset bundle') from exc + if len(unpacked)!=total:raise ValueError('Workstation native asset bundle size mismatch') + offset=0 + for asset in assets: + raw=unpacked[offset:offset+asset['bytes']];offset+=asset['bytes'] + if raw!=payload[asset['path']] or sha256(raw).hexdigest()!=asset['sha256']: + raise ValueError('Workstation bundled mesh differs from its pinned original') + return unpacked + + +def _unpack_wasm(manifest,payload): + """Require compressed delivery to reproduce the original native engine exactly.""" + native=manifest.get('native_wasm') + raw=payload['mujoco.wasm'] + if native!={'path':'mujoco.wasm','bytes':len(raw),'sha256':sha256(raw).hexdigest()}: + raise ValueError('Workstation native WASM descriptor mismatch') + bundle=manifest.get('wasm_bundle') + packed=payload.get('mujoco.wasm.gz') + if (packed is None or bundle!={'path':'mujoco.wasm.gz','compression':'gzip', + 'bytes':len(packed),'sha256':sha256(packed).hexdigest(),'uncompressed_bytes':len(raw)}): + raise ValueError('Workstation compressed WASM descriptor mismatch') + try: + with gzip.GzipFile(fileobj=io.BytesIO(packed),mode='rb') as stream: + unpacked=stream.read(len(raw)+1) + except (OSError,EOFError,zlib.error) as exc: + raise ValueError('Invalid compressed WASM') from exc + if unpacked!=raw:raise ValueError('Workstation compressed WASM differs from the original engine') + return unpacked + + +def inspect_export(directory): + """Verify a bounded, self-contained native scene and its renderer geometry. + + Inspection reads data, compiles only the contained XML with the fixed pinned + mesh allowlist, and never executes the packaged JavaScript. The manifest seal + proves consistency, not the identity or trustworthiness of its publisher. + """ + root=Path(directory) + if root.is_symlink() or not root.is_dir():raise ValueError('Workstation must be a plain directory') + read,decode=asset_preview.replay._read,asset_preview.replay._decode + seal=decode(read(root/'workstation-integrity.json',128*1024)) + if type(seal) is not dict or seal.get('schema')!=INTEGRITY_SCHEMA or type(seal.get('files')) is not dict: + raise ValueError('Workstation integrity schema mismatch') + records=seal['files'] + if not 10<=len(records)<=128:raise ValueError('Workstation inventory outside bounds') + payload={};total=0 + for name,record in records.items(): + if (type(name) is not str or re.fullmatch(r'[A-Za-z0-9_.-]+(?:/[A-Za-z0-9_.-]+)*',name) is None + or str(PurePosixPath(name))!=name or any(part.startswith('.') for part in PurePosixPath(name).parts)): + raise ValueError('Workstation file path is not contained') + path=root/name + if any(parent.is_symlink() for parent in path.parents if parent==root or root in parent.parents): + raise ValueError('Workstation path contains a symlink') + if (type(record) is not dict or set(record)!={'bytes','sha256'} or type(record['bytes']) is not int + or not 0<=record['bytes']<=MAX_FILE_BYTES or type(record['sha256']) is not str + or re.fullmatch('[a-f0-9]{64}',record['sha256']) is None): + raise ValueError('Workstation file record mismatch') + raw=read(path,MAX_FILE_BYTES);total+=len(raw) + if len(raw)!=record['bytes'] or sha256(raw).hexdigest()!=record['sha256'] or total>MAX_TOTAL_BYTES: + raise ValueError('Workstation file integrity mismatch') + payload[name]=raw + paths=list(root.rglob('*')) + if any(path.is_symlink() for path in paths):raise ValueError('Workstation contains a symlink') + actual={path.relative_to(root).as_posix() for path in paths if path.is_file()} + if actual!=set(payload)|{'workstation-integrity.json'}:raise ValueError('Workstation file inventory mismatch') + profile=robot_profiles._profile('piper') + asset_names=set();notice_names=set() + for record in profile['files']: + original=record['path'];local=original.removeprefix(profile['folder']+'/') + if local.startswith('assets/'): + name=local;asset_names.add(name) + elif local in ('LICENSE','README.md'): + name='licenses/'+original;notice_names.add(name) + else:continue + raw=payload.get(name) + if raw is None or len(raw)!=record['bytes'] or sha256(raw).hexdigest()!=record['sha256']: + raise ValueError('Workstation differs from pinned upstream mesh or notice: '+name) + expected=set(RUNTIME_FILES)|asset_names|notice_names|{'scene.xml','model.json','geometry.bin.gz','catalog.json','LICENSE','README.md','workstation.json'} + manifest=decode(payload['workstation.json']) + if type(manifest) is not dict or manifest.get('schema')!=SCHEMA:raise ValueError('Workstation schema mismatch') + if 'native_asset_bundle' in manifest:expected.add('native-assets.bin.gz') + if 'wasm_bundle' in manifest:expected.add('mujoco.wasm.gz') + if set(payload)!=expected:raise ValueError('Workstation portable file allowlist mismatch') + if payload['LICENSE']!=asset_preview.replay.MIT_LICENSE.encode():raise ValueError('Workstation MIT notice mismatch') + if not payload['mujoco.wasm'].startswith(b'\0asm\x01\0\0\0'):raise ValueError('Invalid WebAssembly header') + scene=decode(payload['model.json']) + if decode(payload['catalog.json'])!=asset_library.catalog():raise ValueError('Workstation catalog differs from the immutable catalog') + expected_assets=[{'path':name,**records[name]} for name in sorted(asset_names)] + if manifest.get('assets')!=expected_assets or manifest.get('native_scene')!={'path':'scene.xml',**records['scene.xml']}: + raise ValueError('Workstation native asset manifest mismatch') + if 'native_asset_bundle' in manifest: + _unpack_native_assets(manifest['native_asset_bundle'],expected_assets,payload) + if 'wasm_bundle' in manifest or 'native_wasm' in manifest: + _unpack_wasm(manifest,payload) + lock=robot_profiles._lock() + provenance={'profile':'piper','repository':lock['repository'],'commit':lock['commit'], + 'files_verified':len(profile['files']),'bytes_verified':sum(item['bytes'] for item in profile['files']), + 'lock_sha256':sha256(robot_profiles.LOCK_PATH.read_bytes()).hexdigest(), + 'simulation_asset_license':profile['simulation_asset_license']} + if manifest.get('provenance')!=provenance:raise ValueError('Workstation source provenance mismatch') + native=payload['scene.xml'] + if b'4096:raise ValueError('Invalid workstation XML root or element count') + for element in xml.iter(): + if element.tag in ('include','plugin','extension'): + raise ValueError('Workstation external XML or plugins are unsupported') + if 'file' in element.attrib: + name=element.attrib['file'] + if element.tag!='mesh' or '/' in name or '\\' in name or 'assets/'+name not in asset_names: + raise ValueError('Workstation XML file reference is not a pinned local mesh') + compilers=xml.findall('compiler') + if len(compilers)!=1 or compilers[0].get('meshdir')!='assets/' or compilers[0].get('assetdir') or compilers[0].get('texturedir'): + raise ValueError('Workstation XML asset directory mismatch') + mj,np=sim._native_imports() + if manifest.get('native_version')!=mj.__version__:raise ValueError('Inspection requires the recorded native MuJoCo version') + warnings=[] + with sim.native_warnings(warnings): + model=mj.MjModel.from_xml_string(native.decode(),assets={name:payload[name] for name in asset_names}) + if (model.nq,model.nv,model.nu,model.neq,model.nmocap)!=(15,14,7,1,0): + raise ValueError('Workstation native mechanical contract mismatch') + data=initialize(model) + if warnings or any(item.number for item in data.warning):raise ValueError('Workstation native load emitted a warning') + native_meta=metadata(model,data) + expected_metadata=set(native_meta)|{'assets','native_scene','provenance'} + if 'native_asset_bundle' in manifest:expected_metadata.add('native_asset_bundle') + if 'wasm_bundle' in manifest:expected_metadata.update(('native_wasm','wasm_bundle')) + if set(manifest)!=expected_metadata: + raise ValueError('Workstation metadata inventory mismatch') + if any(manifest.get(key)!=value for key,value in native_meta.items()): + raise ValueError('Workstation metadata differs from the compiled native scene') + source={'robot':'piper','native_version':manifest['native_version'], + 'compiled_model_sha256':manifest['compiled_model_sha256'],'scope':SCOPE} + expected_scene,geometry=asset_preview._scene(model,source) + expected_scene.update(schema='dvidia.live-workstation-model/v1',scope=SCOPE) + geometry_meta=scene.get('geometry_binary',{}) + if 'compressed_sha256' in geometry_meta and geometry_meta['compressed_sha256']!=sha256(payload['geometry.bin.gz']).hexdigest(): + raise ValueError('Workstation compressed geometry checksum mismatch') + unpacked=asset_preview._unpack({key:value for key,value in geometry_meta.items() + if key!='compressed_sha256'},payload,'geometry.bin.gz') + if unpacked!=geometry or {key:value for key,value in scene.items() if key!='geometry_binary'}!=expected_scene: + raise ValueError('Workstation renderer differs from its compiled native geometry') + return {'schema':SCHEMA,'robot':'piper','files':records,'file_count':len(payload)+1, + 'bytes':total+len(read(root/'workstation-integrity.json',128*1024)), + 'scope':SCOPE,'physical_robot_ready':False,'learned_policy':False, + 'compiled_model_sha256':manifest['compiled_model_sha256']} + + +def main(argv=None): + parser=argparse.ArgumentParser(description=__doc__) + parser.add_argument('--assets',type=Path,required=True) + parser.add_argument('--output',type=Path,required=True) + parser.add_argument('--runtime-directory',type=Path) + args=parser.parse_args(argv) + print(json.dumps(export(args.assets,args.output,runtime_directory=args.runtime_directory),indent=2)) + + +if __name__=='__main__':main() diff --git a/src/dvidia_training/workstation.third-party.txt b/src/dvidia_training/workstation.third-party.txt new file mode 100644 index 0000000..6444169 --- /dev/null +++ b/src/dvidia_training/workstation.third-party.txt @@ -0,0 +1,4911 @@ +DVIDIA self-hosted reference replay + +Three.js 0.180.0 and OrbitControls +https://github.com/mrdoob/three.js/tree/r180 + +The MIT License + +Copyright © 2010-2025 three.js authors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +MuJoCo 3.15.0, Google DeepMind +https://github.com/google-deepmind/mujoco/tree/3.15.0 +Official WASM distribution, unmodified binary; JavaScript bundled/minified by esbuild. + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +## Third-party licenses + +Pre-built [wheels](https://packaging.python.org/en/latest/specifications/ +binary-distribution-format/#binary-distribution-format) contain binaries that +incorporate third-party open source software, which are redistributed under the +following licenses. + +### Abseil C++ Common Libraries + +``` +Copyright 2016 Google Inc. +Copyright 2017 The Abseil Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +``` + +### cereal + +``` +Copyright (c) 2013-2022, Randolph Voorhies, Shane Grant +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 copyright holder 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 HOLDER 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. +``` + +### Collisions + +``` +Copyright (c) 2015 Svetoslav Kolev + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +``` + +### Eigen + +We build with the `EIGEN_MPL2_ONLY` preprocessor macro set. + +``` +Eigen is primarily MPL2 licensed. See COPYING.MPL2 and these links: + http://www.mozilla.org/MPL/2.0/ + http://www.mozilla.org/MPL/2.0/FAQ.html + +Some files contain third-party code under BSD or LGPL licenses, whence the other +COPYING.* files here. + +All the LGPL code is either LGPL 2.1-only, or LGPL 2.1-or-later. +For this reason, the COPYING.LGPL file contains the LGPL 2.1 text. + +If you want to guarantee that the Eigen code that you are #including is licensed +under the MPL2 and possibly more permissive licenses (like BSD), #define this +preprocessor symbol: + EIGEN_MPL2_ONLY +For example, with most compilers, you could add this to your project CXXFLAGS: + -DEIGEN_MPL2_ONLY +This will cause a compilation error to be generated if you #include any code that is +LGPL licensed. + + +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at https://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. +``` + +### {fmt} + +``` +Copyright (c) 2012 - present, Victor Zverovich and {fmt} contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--- Optional exception to the license --- + +As an exception, if, as a result of your compiling your source code, portions +of this Software are embedded into a machine-executable object form of such +source code, you may redistribute such embedded portions in such object form +without including the above copyright and permission notices. +``` + +### GLAD + +``` +The glad generated code itself is CC0. The source files for the generated code +are under various licenses from Khronos. + +-------------------------------------------------------------------------------- + +Copyright 2013-2020 The Khronos Group Inc. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and/or associated documentation files (the +"Materials"), to deal in the Materials without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Materials, and to +permit persons to whom the Materials are furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Materials. + +THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. +``` + +### GLFW + +``` +Copyright (c) 2002-2006 Marcus Geelnard + +Copyright (c) 2006-2019 Camilla Löwy + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would + be appreciated but is not required. + +2. Altered source versions must be plainly marked as such, and must not + be misrepresented as being the original software. + +3. This notice may not be removed or altered from any source + distribution. +``` + +### libccd + +``` +Copyright (c)2010-2012 Daniel Fiser , +Intelligent and Mobile Robotics Group, Department of Cybernetics, +Faculty of Electrical Engineering, Czech Technical University in Prague. +All rights reserved. + + +This work was supported by SYMBRION and REPLICATOR projects. +The SYMBRION project is funded by European Commission within the work +"Future and Emergent Technologies Proactive" under grant agreement no. +216342. +The REPLICATOR project is funded within the work programme "Cognitive +Systems, Interaction, Robotics" under grant agreement no. 216240. +http://www.symbrion.eu/ +http://www.replicators.eu/ + + +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 University 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 HOLDER 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. +``` + +### LLVM runtime libraries (`compiler_rt`, `libc++`, `libc++abi`, `libunwind`) + +``` +The LLVM Project is under the Apache License v2.0 with LLVM Exceptions. +You may obtain a copy of the Apache 2.0 License at + + https://www.apache.org/licenses/LICENSE-2.0 + +---- LLVM Exceptions to the Apache 2.0 License ---- + +As an exception, if, as a result of your compiling your source code, portions +of this Software are embedded into an Object form of such source code, you +may redistribute such embedded portions in such Object form without complying +with the conditions of Sections 4(a), 4(b) and 4(d) of the License. + +In addition, if you combine or link compiled forms of this Software with +software that is licensed under the GPLv2 ("Combined Software") and if a +court of competent jurisdiction determines that the patent provision (Section +3), the indemnity provision (Section 9) or other Section of the License +conflicts with the conditions of the GPLv2, you may retroactively and +prospectively choose to deem waived or otherwise exclude such Section(s) of +the License, but only in their entirety and only with respect to the Combined +Software. +``` + +### LodePNG + +``` +Copyright (c) 2005-2018 Lode Vandevenne + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +``` + +### MarchingCubeCpp + +``` +The MIT License (MIT) + +Copyright (c) 2020 Axel Paris + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +``` + +### OpenGL Mathematics + +``` +The MIT License + +Copyright (c) 2005 - G-Truc Creation + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +``` + +### pybind11 + +``` +Copyright (c) 2016 Wenzel Jakob , All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. 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. + +3. Neither the name of the copyright holder 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 HOLDER 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. + +Please also refer to the file .github/CONTRIBUTING.md, which clarifies licensing of +external contributions to this project including patches, pull requests, etc. +``` + +### Qhull + +``` + Qhull, Copyright (c) 1993-2020 + + C.B. Barber + Arlington, MA + + and + + The National Science and Technology Research Center for + Computation and Visualization of Geometric Structures + (The Geometry Center) + University of Minnesota + + email: qhull@qhull.org + +This software includes Qhull from C.B. Barber and The Geometry Center. +Files derived from Qhull 1.0 are copyrighted by the Geometry Center. The +remaining files are copyrighted by C.B. Barber. Qhull is free software +and may be obtained via http from www.qhull.org. It may be freely copied, +modified, and redistributed under the following conditions: + +1. All copyright notices must remain intact in all files. + +2. A copy of this text file must be distributed along with any copies + of Qhull that you redistribute; this includes copies that you have + modified, or copies of programs or other software products that + include Qhull. + +3. If you modify Qhull, you must include a notice giving the + name of the person performing the modification, the date of + modification, and the reason for such modification. + +4. When distributing modified versions of Qhull, or other software + products that include Qhull, you must provide notice that the original + source code may be obtained as noted above. + +5. There is no warranty or other guarantee of fitness for Qhull, it is + provided solely "as is". Bug reports or fixes may be sent to + qhull_bug@qhull.org; the authors may or may not act on them as + they desire. +``` + +### TinyOBJLoader + +``` +The MIT License (MIT) + +Copyright (c) 2012-2019 Syoyo Fujita and many contributors. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +``` + +### TinyXML2 + +``` +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any +damages arising from the use of this software. + +Permission is granted to anyone to use this software for any +purpose, including commercial applications, and to alter it and +redistribute it freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must +not claim that you wrote the original software. If you use this +software in a product, an acknowledgment in the product documentation +would be appreciated but is not required. + +2. Altered source versions must be plainly marked as such, and +must not be misrepresented as being the original software. + +3. This notice may not be removed or altered from any source +distribution. +``` + +### miniz + +``` +Copyright 2013-2014 RAD Game Tools and Valve Software +Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC + +All Rights Reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +``` + +### Dear ImGui + +``` +The MIT License (MIT) + +Copyright (c) 2014-2025 Omar Cornut + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +``` + +### ImPlot + +``` +MIT License + +Copyright (c) 2020 Evan Pezent + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +``` + +### Open Sans Font + +``` +Copyright 2020 The Open Sans Project Authors (https://github.com/googlefonts/opensans) + +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font +creation efforts of academic and linguistic communities, and to +provide a free and open framework in which fonts may be shared and +improved in partnership with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply to +any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software +components as distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, +deleting, or substituting -- in part or in whole -- any of the +components of the Original Version, by changing formats or by porting +the Font Software to a new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, +modify, redistribute, and sell modified and unmodified copies of the +Font Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, in +Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the +corresponding Copyright Holder. This restriction only applies to the +primary font name as presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created using +the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE FONT SOFTWARE. +``` + +### Font Awesome Font + +``` +Copyright (c) 2016 Dave Gandy (http://fontawesome.io) + +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font +creation efforts of academic and linguistic communities, and to +provide a free and open framework in which fonts may be shared and +improved in partnership with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply to +any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software +components as distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, +deleting, or substituting -- in part or in whole -- any of the +components of the Original Version, by changing formats or by porting +the Font Software to a new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, +modify, redistribute, and sell modified and unmodified copies of the +Font Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, in +Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the +corresponding Copyright Holder. This restriction only applies to the +primary font name as presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created using +the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE FONT SOFTWARE. +``` + +### Filament + +``` +Copyright 2023 The Android Open Source Project + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +``` + +### SDL2 + +``` +Copyright (C) 1997-2025 Sam Lantinga + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. +2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. +3. This notice may not be removed or altered from any source distribution. +``` + +### Zstandard + +``` +BSD License + +For Zstandard software + +Copyright (c) Meta Platforms, Inc. and affiliates. 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 Facebook, nor Meta, 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 HOLDER 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. +``` + +### SMOL-V + +``` +MIT License + +Copyright (c) 2016-2018 Aras Pranckevicius + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +``` + + +### libwebp + +``` +Copyright 2010 Google LLC + +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 Google 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 +HOLDER 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. + +Additional IP Rights Grant (Patents) +------------------------------------ + +"These implementations" means the copyrightable works that implement the WebM +codecs distributed by Google as part of the WebM Project. + +Google hereby grants to you a perpetual, worldwide, non-exclusive, no-charge, +royalty-free, irrevocable (except as stated in this section) patent license to +make, have made, use, offer to sell, sell, import, transfer, and otherwise +run, modify and propagate the contents of these implementations of WebM, where +such license applies only to those patent claims, both currently owned by +Google and acquired in the future, licensable by Google that are necessarily +infringed by these implementations of WebM. This grant does not include claims +that would be infringed only as a consequence of further modification of these +implementations. If you or your agent or exclusive licensee institute or order +or agree to the institution of patent litigation or any other patent +enforcement activity against any entity (including a cross-claim or +counterclaim in a lawsuit) alleging that any of these implementations of WebM +or any code incorporated within any of these implementations of WebM +constitute direct or contributory patent infringement, or inducement of +patent infringement, then any patent rights granted to you under this License +for these implementations of WebM shall terminate as of the date such +litigation is filed. +``` + + +### Basis Universal + +``` +All files except those noted below: +apg_bmp.h +apg_bmp.c +zstd/* + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +------------------ + +File: webgl/gltf/GLTFLoader.js + +Copyright 2019 the three.js authors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +------------------ + +Files: +apg_bmp.h +apg_bmp.c + +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or +distribute this software, either in source code form or as a compiled +binary, for any purpose, commercial or non-commercial, and by any +means. + +In jurisdictions that recognize copyright laws, the author or authors +of this software dedicate any and all copyright interest in the +software to the public domain. We make this dedication for the benefit +of the public at large and to the detriment of our heirs and +successors. We intend this dedication to be an overt act of +relinquishment in perpetuity of all present and future rights to this +software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR +OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + +For more information, please refer to + +------------------ + +Copyright (c) + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. + +------------------ +zstd/* + +BSD License + +For Zstandard software + +Copyright (c) 2016-present, Facebook, Inc. 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 Facebook 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 HOLDER 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. +``` + + +### Glslang + +``` +Here, glslang proper means core GLSL parsing, HLSL parsing, and SPIR-V code +generation. Glslang proper requires use of a number of licenses, one that covers +preprocessing and others that covers non-preprocessing. + +Bison was removed long ago. You can build glslang from the source grammar, +using tools of your choice, without using bison or any bison files. + +Other parts, outside of glslang proper, include: + +- gl_types.h, only needed for OpenGL-like reflection, and can be left out of + a parse and codegen project. See it for its license. + +- update_glslang_sources.py, which is not part of the project proper and does + not need to be used. + +- Google tests and SPIR-V tools, and anything in the external subdirectory + are external and optional; see them for their respective licenses. + +-------------------------------------------------------------------------------- + +The core of glslang-proper, minus the preprocessor is licenced as follows: + +-------------------------------------------------------------------------------- +3-Clause BSD License +-------------------------------------------------------------------------------- + +// +// Copyright (C) 2015-2018 Google, Inc. +// Copyright (C) +// +// 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 3Dlabs Inc. Ltd. 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 HOLDERS 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. +// + + +-------------------------------------------------------------------------------- +2-Clause BSD License +-------------------------------------------------------------------------------- + +Copyright 2020 The Khronos Group Inc + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. 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. + +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 HOLDER 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. + + +-------------------------------------------------------------------------------- +The MIT License +-------------------------------------------------------------------------------- + +Copyright 2020 The Khronos Group Inc + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +-------------------------------------------------------------------------------- +APACHE LICENSE, VERSION 2.0 +-------------------------------------------------------------------------------- + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +-------------------------------------------------------------------------------- +GPL 3 with special bison exception +-------------------------------------------------------------------------------- + + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + +Bison Exception + +As a special exception, you may create a larger work that contains part or all +of the Bison parser skeleton and distribute that work under terms of your +choice, so long as that work isn't itself a parser generator using the skeleton +or a modified version thereof as a parser skeleton. Alternatively, if you +modify or redistribute the parser skeleton itself, you may (at your option) +remove this special exception, which will cause the skeleton and the resulting +Bison output files to be licensed under the GNU General Public License without +this special exception. + +This special exception was added by the Free Software Foundation in version +2.2 of Bison. + + END OF TERMS AND CONDITIONS + +-------------------------------------------------------------------------------- +================================================================================ +-------------------------------------------------------------------------------- + +The preprocessor has the core licenses stated above, plus additional licences: + +/****************************************************************************\ +Copyright (c) 2002, NVIDIA Corporation. + +NVIDIA Corporation("NVIDIA") supplies this software to you in +consideration of your agreement to the following terms, and your use, +installation, modification or redistribution of this NVIDIA software +constitutes acceptance of these terms. If you do not agree with these +terms, please do not use, install, modify or redistribute this NVIDIA +software. + +In consideration of your agreement to abide by the following terms, and +subject to these terms, NVIDIA grants you a personal, non-exclusive +license, under NVIDIA's copyrights in this original NVIDIA software (the +"NVIDIA Software"), to use, reproduce, modify and redistribute the +NVIDIA Software, with or without modifications, in source and/or binary +forms; provided that if you redistribute the NVIDIA Software, you must +retain the copyright notice of NVIDIA, this notice and the following +text and disclaimers in all such redistributions of the NVIDIA Software. +Neither the name, trademarks, service marks nor logos of NVIDIA +Corporation may be used to endorse or promote products derived from the +NVIDIA Software without specific prior written permission from NVIDIA. +Except as expressly stated in this notice, no other rights or licenses +express or implied, are granted by NVIDIA herein, including but not +limited to any patent rights that may be infringed by your derivative +works or by other works in which the NVIDIA Software may be +incorporated. No hardware is licensed hereunder. + +THE NVIDIA SOFTWARE IS BEING PROVIDED ON AN "AS IS" BASIS, WITHOUT +WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, +INCLUDING WITHOUT LIMITATION, WARRANTIES OR CONDITIONS OF TITLE, +NON-INFRINGEMENT, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR +ITS USE AND OPERATION EITHER ALONE OR IN COMBINATION WITH OTHER +PRODUCTS. + +IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY SPECIAL, INDIRECT, +INCIDENTAL, EXEMPLARY, CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, LOST PROFITS; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF +USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) OR ARISING IN ANY WAY +OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE +NVIDIA SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, +TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF +NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +\****************************************************************************/ + +/* +** Copyright (c) 2014-2016 The Khronos Group Inc. +** +** Permission is hereby granted, free of charge, to any person obtaining a copy +** of this software and/or associated documentation files (the "Materials"), +** to deal in the Materials without restriction, including without limitation +** the rights to use, copy, modify, merge, publish, distribute, sublicense, +** and/or sell copies of the Materials, and to permit persons to whom the +** Materials are furnished to do so, subject to the following conditions: +** +** The above copyright notice and this permission notice shall be included in +** all copies or substantial portions of the Materials. +** +** MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS KHRONOS +** STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS SPECIFICATIONS AND +** HEADER INFORMATION ARE LOCATED AT https://www.khronos.org/registry/ +** +** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +** OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +** THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +** FROM,OUT OF OR IN CONNECTION WITH THE MATERIALS OR THE USE OR OTHER DEALINGS +** IN THE MATERIALS. +*/ +``` + + +### libpng + +``` +COPYRIGHT NOTICE, DISCLAIMER, and LICENSE +========================================= + +PNG Reference Library License version 2 +--------------------------------------- + + * Copyright (c) 1995-2026 The PNG Reference Library Authors. + * Copyright (c) 2018-2026 Cosmin Truta. + * Copyright (c) 2000-2002, 2004, 2006-2018 Glenn Randers-Pehrson. + * Copyright (c) 1996-1997 Andreas Dilger. + * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc. + +The software is supplied "as is", without warranty of any kind, +express or implied, including, without limitation, the warranties +of merchantability, fitness for a particular purpose, title, and +non-infringement. In no event shall the Copyright owners, or +anyone distributing the software, be liable for any damages or +other liability, whether in contract, tort or otherwise, arising +from, out of, or in connection with the software, or the use or +other dealings in the software, even if advised of the possibility +of such damage. + +Permission is hereby granted to use, copy, modify, and distribute +this software, or portions hereof, for any purpose, without fee, +subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you + must not claim that you wrote the original software. If you + use this software in a product, an acknowledgment in the product + documentation would be appreciated, but is not required. + + 2. Altered source versions must be plainly marked as such, and must + not be misrepresented as being the original software. + + 3. This Copyright notice may not be removed or altered from any + source or altered source distribution. + + +PNG Reference Library License version 1 (for libpng 0.5 through 1.6.35) +----------------------------------------------------------------------- + +libpng versions 1.0.7, July 1, 2000, through 1.6.35, July 15, 2018 are +Copyright (c) 2000-2002, 2004, 2006-2018 Glenn Randers-Pehrson, are +derived from libpng-1.0.6, and are distributed according to the same +disclaimer and license as libpng-1.0.6 with the following individuals +added to the list of Contributing Authors: + + Simon-Pierre Cadieux + Eric S. Raymond + Mans Rullgard + Cosmin Truta + Gilles Vollant + James Yu + Mandar Sahastrabuddhe + Google Inc. + Vadim Barkov + +and with the following additions to the disclaimer: + + There is no warranty against interference with your enjoyment of + the library or against infringement. There is no warranty that our + efforts or the library will fulfill any of your particular purposes + or needs. This library is provided with all faults, and the entire + risk of satisfactory quality, performance, accuracy, and effort is + with the user. + +Some files in the "contrib" directory and some configure-generated +files that are distributed with libpng have other copyright owners, and +are released under other open source licenses. + +libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are +Copyright (c) 1998-2000 Glenn Randers-Pehrson, are derived from +libpng-0.96, and are distributed according to the same disclaimer and +license as libpng-0.96, with the following individuals added to the +list of Contributing Authors: + + Tom Lane + Glenn Randers-Pehrson + Willem van Schaik + +libpng versions 0.89, June 1996, through 0.96, May 1997, are +Copyright (c) 1996-1997 Andreas Dilger, are derived from libpng-0.88, +and are distributed according to the same disclaimer and license as +libpng-0.88, with the following individuals added to the list of +Contributing Authors: + + John Bowler + Kevin Bracey + Sam Bushell + Magnus Holmgren + Greg Roelofs + Tom Tanner + +Some files in the "scripts" directory have other copyright owners, +but are released under this license. + +libpng versions 0.5, May 1995, through 0.88, January 1996, are +Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc. + +For the purposes of this copyright and license, "Contributing Authors" +is defined as the following set of individuals: + + Andreas Dilger + Dave Martindale + Guy Eric Schalnat + Paul Schmidt + Tim Wegner + +The PNG Reference Library is supplied "AS IS". The Contributing +Authors and Group 42, Inc. disclaim all warranties, expressed or +implied, including, without limitation, the warranties of +merchantability and of fitness for any purpose. The Contributing +Authors and Group 42, Inc. assume no liability for direct, indirect, +incidental, special, exemplary, or consequential damages, which may +result from the use of the PNG Reference Library, even if advised of +the possibility of such damage. + +Permission is hereby granted to use, copy, modify, and distribute this +source code, or portions hereof, for any purpose, without fee, subject +to the following restrictions: + + 1. The origin of this source code must not be misrepresented. + + 2. Altered versions must be plainly marked as such and must not + be misrepresented as being the original source. + + 3. This Copyright notice may not be removed or altered from any + source or altered source distribution. + +The Contributing Authors and Group 42, Inc. specifically permit, +without fee, and encourage the use of this source code as a component +to supporting the PNG file format in commercial products. If you use +this source code in a product, acknowledgment is not required but would +be appreciated. +``` + + +### zlib + +``` +(extracted from README, except for match.S) + +Copyright notice: + + (C) 1995-2013 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + +If you use the zlib library in a product, we would appreciate *not* receiving +lengthy legal documents to sign. The sources are provided for free but without +warranty of any kind. The library has been entirely written by Jean-loup +Gailly and Mark Adler; it does not include third-party code. + +If you redistribute modified sources, we would appreciate that you include in +the file ChangeLog history information documenting your changes. Please read +the FAQ for more information on the distribution of modified source versions. + +(extracted from match.S, for match.S only) + +Copyright (C) 1998, 2007 Brian Raiter + +This software is provided 'as-is', without any express or implied +warranty. In no event will the author be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. +2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. +3. This notice may not be removed or altered from any source distribution. +``` + + +### robin-map + +``` +MIT License + +Copyright (c) 2017 Thibaut Goetghebuer-Planchon + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +``` + + +### SPIRV-Cross + +``` +========== +LICENSE +========== + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +========== +LICENSES/Apache-2.0.txt +========== + +Apache License + +Version 2.0, January 2004 + +http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, +AND DISTRIBUTION + + 1. Definitions. + + + +"License" shall mean the terms and conditions for use, reproduction, and distribution +as defined by Sections 1 through 9 of this document. + + + +"Licensor" shall mean the copyright owner or entity authorized by the copyright +owner that is granting the License. + + + +"Legal Entity" shall mean the union of the acting entity and all other entities +that control, are controlled by, or are under common control with that entity. +For the purposes of this definition, "control" means (i) the power, direct +or indirect, to cause the direction or management of such entity, whether +by contract or otherwise, or (ii) ownership of fifty percent (50%) or more +of the outstanding shares, or (iii) beneficial ownership of such entity. + + + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions +granted by this License. + + + +"Source" form shall mean the preferred form for making modifications, including +but not limited to software source code, documentation source, and configuration +files. + + + +"Object" form shall mean any form resulting from mechanical transformation +or translation of a Source form, including but not limited to compiled object +code, generated documentation, and conversions to other media types. + + + +"Work" shall mean the work of authorship, whether in Source or Object form, +made available under the License, as indicated by a copyright notice that +is included in or attached to the work (an example is provided in the Appendix +below). + + + +"Derivative Works" shall mean any work, whether in Source or Object form, +that is based on (or derived from) the Work and for which the editorial revisions, +annotations, elaborations, or other modifications represent, as a whole, an +original work of authorship. For the purposes of this License, Derivative +Works shall not include works that remain separable from, or merely link (or +bind by name) to the interfaces of, the Work and Derivative Works thereof. + + + +"Contribution" shall mean any work of authorship, including the original version +of the Work and any modifications or additions to that Work or Derivative +Works thereof, that is intentionally submitted to Licensor for inclusion in +the Work by the copyright owner or by an individual or Legal Entity authorized +to submit on behalf of the copyright owner. For the purposes of this definition, +"submitted" means any form of electronic, verbal, or written communication +sent to the Licensor or its representatives, including but not limited to +communication on electronic mailing lists, source code control systems, and +issue tracking systems that are managed by, or on behalf of, the Licensor +for the purpose of discussing and improving the Work, but excluding communication +that is conspicuously marked or otherwise designated in writing by the copyright +owner as "Not a Contribution." + + + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf +of whom a Contribution has been received by Licensor and subsequently incorporated +within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this +License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, +no-charge, royalty-free, irrevocable copyright license to reproduce, prepare +Derivative Works of, publicly display, publicly perform, sublicense, and distribute +the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, +each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, +no-charge, royalty-free, irrevocable (except as stated in this section) patent +license to make, have made, use, offer to sell, sell, import, and otherwise +transfer the Work, where such license applies only to those patent claims +licensable by such Contributor that are necessarily infringed by their Contribution(s) +alone or by combination of their Contribution(s) with the Work to which such +Contribution(s) was submitted. If You institute patent litigation against +any entity (including a cross-claim or counterclaim in a lawsuit) alleging +that the Work or a Contribution incorporated within the Work constitutes direct +or contributory patent infringement, then any patent licenses granted to You +under this License for that Work shall terminate as of the date such litigation +is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or +Derivative Works thereof in any medium, with or without modifications, and +in Source or Object form, provided that You meet the following conditions: + +(a) You must give any other recipients of the Work or Derivative Works a copy +of this License; and + +(b) You must cause any modified files to carry prominent notices stating that +You changed the files; and + +(c) You must retain, in the Source form of any Derivative Works that You distribute, +all copyright, patent, trademark, and attribution notices from the Source +form of the Work, excluding those notices that do not pertain to any part +of the Derivative Works; and + +(d) If the Work includes a "NOTICE" text file as part of its distribution, +then any Derivative Works that You distribute must include a readable copy +of the attribution notices contained within such NOTICE file, excluding those +notices that do not pertain to any part of the Derivative Works, in at least +one of the following places: within a NOTICE text file distributed as part +of the Derivative Works; within the Source form or documentation, if provided +along with the Derivative Works; or, within a display generated by the Derivative +Works, if and wherever such third-party notices normally appear. The contents +of the NOTICE file are for informational purposes only and do not modify the +License. You may add Your own attribution notices within Derivative Works +that You distribute, alongside or as an addendum to the NOTICE text from the +Work, provided that such additional attribution notices cannot be construed +as modifying the License. + +You may add Your own copyright statement to Your modifications and may provide +additional or different license terms and conditions for use, reproduction, +or distribution of Your modifications, or for any such Derivative Works as +a whole, provided Your use, reproduction, and distribution of the Work otherwise +complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any +Contribution intentionally submitted for inclusion in the Work by You to the +Licensor shall be under the terms and conditions of this License, without +any additional terms or conditions. Notwithstanding the above, nothing herein +shall supersede or modify the terms of any separate license agreement you +may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, +trademarks, service marks, or product names of the Licensor, except as required +for reasonable and customary use in describing the origin of the Work and +reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to +in writing, Licensor provides the Work (and each Contributor provides its +Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, either express or implied, including, without limitation, any warranties +or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR +A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness +of using or redistributing the Work and assume any risks associated with Your +exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether +in tort (including negligence), contract, or otherwise, unless required by +applicable law (such as deliberate and grossly negligent acts) or agreed to +in writing, shall any Contributor be liable to You for damages, including +any direct, indirect, special, incidental, or consequential damages of any +character arising as a result of this License or out of the use or inability +to use the Work (including but not limited to damages for loss of goodwill, +work stoppage, computer failure or malfunction, or any and all other commercial +damages or losses), even if such Contributor has been advised of the possibility +of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work +or Derivative Works thereof, You may choose to offer, and charge a fee for, +acceptance of support, warranty, indemnity, or other liability obligations +and/or rights consistent with this License. However, in accepting such obligations, +You may act only on Your own behalf and on Your sole responsibility, not on +behalf of any other Contributor, and only if You agree to indemnify, defend, +and hold each Contributor harmless for any liability incurred by, or claims +asserted against, such Contributor by reason of your accepting any such warranty +or additional liability. END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +To apply the Apache License to your work, attach the following boilerplate +notice, with the fields enclosed by brackets "[]" replaced with your own identifying +information. (Don't include the brackets!) The text should be enclosed in +the appropriate comment syntax for the file format. We also recommend that +a file or class name and description of purpose be included on the same "printed +page" as the copyright notice for easier identification within third-party +archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); + +you may not use this file except in compliance with the License. + +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software + +distributed under the License is distributed on an "AS IS" BASIS, + +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +See the License for the specific language governing permissions and + +limitations under the License. + + +========== +LICENSES/CC-BY-4.0.txt +========== + +Creative Commons Attribution 4.0 International Creative Commons Corporation +("Creative Commons") is not a law firm and does not provide legal services +or legal advice. Distribution of Creative Commons public licenses does not +create a lawyer-client or other relationship. Creative Commons makes its licenses +and related information available on an "as-is" basis. Creative Commons gives +no warranties regarding its licenses, any material licensed under their terms +and conditions, or any related information. Creative Commons disclaims all +liability for damages resulting from their use to the fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and conditions +that creators and other rights holders may use to share original works of +authorship and other material subject to copyright and certain other rights +specified in the public license below. The following considerations are for +informational purposes only, are not exhaustive, and do not form part of our +licenses. + +Considerations for licensors: Our public licenses are intended for use by +those authorized to give the public permission to use material in ways otherwise +restricted by copyright and certain other rights. Our licenses are irrevocable. +Licensors should read and understand the terms and conditions of the license +they choose before applying it. Licensors should also secure all rights necessary +before applying our licenses so that the public can reuse the material as +expected. Licensors should clearly mark any material not subject to the license. +This includes other CC-licensed material, or material used under an exception +or limitation to copyright. More considerations for licensors : wiki.creativecommons.org/Considerations_for_licensors + +Considerations for the public: By using one of our public licenses, a licensor +grants the public permission to use the licensed material under specified +terms and conditions. If the licensor's permission is not necessary for any +reason–for example, because of any applicable exception or limitation to copyright–then +that use is not regulated by the license. Our licenses grant only permissions +under copyright and certain other rights that a licensor has authority to +grant. Use of the licensed material may still be restricted for other reasons, +including because others have copyright or other rights in the material. A +licensor may make special requests, such as asking that all changes be marked +or described. Although not required by our licenses, you are encouraged to +respect those requests where reasonable. More considerations for the public +: wiki.creativecommons.org/Considerations_for_licensees Creative Commons Attribution +4.0 International Public License + +By exercising the Licensed Rights (defined below), You accept and agree to +be bound by the terms and conditions of this Creative Commons Attribution +4.0 International Public License ("Public License"). To the extent this Public +License may be interpreted as a contract, You are granted the Licensed Rights +in consideration of Your acceptance of these terms and conditions, and the +Licensor grants You such rights in consideration of benefits the Licensor +receives from making the Licensed Material available under these terms and +conditions. + +Section 1 – Definitions. + +a. Adapted Material means material subject to Copyright and Similar Rights +that is derived from or based upon the Licensed Material and in which the +Licensed Material is translated, altered, arranged, transformed, or otherwise +modified in a manner requiring permission under the Copyright and Similar +Rights held by the Licensor. For purposes of this Public License, where the +Licensed Material is a musical work, performance, or sound recording, Adapted +Material is always produced where the Licensed Material is synched in timed +relation with a moving image. + +b. Adapter's License means the license You apply to Your Copyright and Similar +Rights in Your contributions to Adapted Material in accordance with the terms +and conditions of this Public License. + +c. Copyright and Similar Rights means copyright and/or similar rights closely +related to copyright including, without limitation, performance, broadcast, +sound recording, and Sui Generis Database Rights, without regard to how the +rights are labeled or categorized. For purposes of this Public License, the +rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. + +d. Effective Technological Measures means those measures that, in the absence +of proper authority, may not be circumvented under laws fulfilling obligations +under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, +and/or similar international agreements. + +e. Exceptions and Limitations means fair use, fair dealing, and/or any other +exception or limitation to Copyright and Similar Rights that applies to Your +use of the Licensed Material. + +f. Licensed Material means the artistic or literary work, database, or other +material to which the Licensor applied this Public License. + +g. Licensed Rights means the rights granted to You subject to the terms and +conditions of this Public License, which are limited to all Copyright and +Similar Rights that apply to Your use of the Licensed Material and that the +Licensor has authority to license. + +h. Licensor means the individual(s) or entity(ies) granting rights under this +Public License. + +i. Share means to provide material to the public by any means or process that +requires permission under the Licensed Rights, such as reproduction, public +display, public performance, distribution, dissemination, communication, or +importation, and to make material available to the public including in ways +that members of the public may access the material from a place and at a time +individually chosen by them. + +j. Sui Generis Database Rights means rights other than copyright resulting +from Directive 96/9/EC of the European Parliament and of the Council of 11 +March 1996 on the legal protection of databases, as amended and/or succeeded, +as well as other essentially equivalent rights anywhere in the world. + +k. You means the individual or entity exercising the Licensed Rights under +this Public License. Your has a corresponding meaning. + +Section 2 – Scope. + + a. License grant. + +1. Subject to the terms and conditions of this Public License, the Licensor +hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, +irrevocable license to exercise the Licensed Rights in the Licensed Material +to: + + A. reproduce and Share the Licensed Material, in whole or in part; and + + B. produce, reproduce, and Share Adapted Material. + +2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions +and Limitations apply to Your use, this Public License does not apply, and +You do not need to comply with its terms and conditions. + + 3. Term. The term of this Public License is specified in Section 6(a). + +4. Media and formats; technical modifications allowed. The Licensor authorizes +You to exercise the Licensed Rights in all media and formats whether now known +or hereafter created, and to make technical modifications necessary to do +so. The Licensor waives and/or agrees not to assert any right or authority +to forbid You from making technical modifications necessary to exercise the +Licensed Rights, including technical modifications necessary to circumvent +Effective Technological Measures. For purposes of this Public License, simply +making modifications authorized by this Section 2(a)(4) never produces Adapted +Material. + + 5. Downstream recipients. + +A. Offer from the Licensor – Licensed Material. Every recipient of the Licensed +Material automatically receives an offer from the Licensor to exercise the +Licensed Rights under the terms and conditions of this Public License. + +B. No downstream restrictions. You may not offer or impose any additional +or different terms or conditions on, or apply any Effective Technological +Measures to, the Licensed Material if doing so restricts exercise of the Licensed +Rights by any recipient of the Licensed Material. + +6. No endorsement. Nothing in this Public License constitutes or may be construed +as permission to assert or imply that You are, or that Your use of the Licensed +Material is, connected with, or sponsored, endorsed, or granted official status +by, the Licensor or others designated to receive attribution as provided in +Section 3(a)(1)(A)(i). + + b. Other rights. + +1. Moral rights, such as the right of integrity, are not licensed under this +Public License, nor are publicity, privacy, and/or other similar personality +rights; however, to the extent possible, the Licensor waives and/or agrees +not to assert any such rights held by the Licensor to the limited extent necessary +to allow You to exercise the Licensed Rights, but not otherwise. + +2. Patent and trademark rights are not licensed under this Public License. + +3. To the extent possible, the Licensor waives any right to collect royalties +from You for the exercise of the Licensed Rights, whether directly or through +a collecting society under any voluntary or waivable statutory or compulsory +licensing scheme. In all other cases the Licensor expressly reserves any right +to collect such royalties. + +Section 3 – License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the following +conditions. + + a. Attribution. + +1. If You Share the Licensed Material (including in modified form), You must: + +A. retain the following if it is supplied by the Licensor with the Licensed +Material: + +i. identification of the creator(s) of the Licensed Material and any others +designated to receive attribution, in any reasonable manner requested by the +Licensor (including by pseudonym if designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of warranties; + +v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; + +B. indicate if You modified the Licensed Material and retain an indication +of any previous modifications; and + +C. indicate the Licensed Material is licensed under this Public License, and +include the text of, or the URI or hyperlink to, this Public License. + +2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner +based on the medium, means, and context in which You Share the Licensed Material. +For example, it may be reasonable to satisfy the conditions by providing a +URI or hyperlink to a resource that includes the required information. + +3. If requested by the Licensor, You must remove any of the information required +by Section 3(a)(1)(A) to the extent reasonably practicable. + +4. If You Share Adapted Material You produce, the Adapter's License You apply +must not prevent recipients of the Adapted Material from complying with this +Public License. + +Section 4 – Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that apply to +Your use of the Licensed Material: + +a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, +reuse, reproduce, and Share all or a substantial portion of the contents of +the database; + +b. if You include all or a substantial portion of the database contents in +a database in which You have Sui Generis Database Rights, then the database +in which You have Sui Generis Database Rights (but not its individual contents) +is Adapted Material; and + +c. You must comply with the conditions in Section 3(a) if You Share all or +a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not replace +Your obligations under this Public License where the Licensed Rights include +other Copyright and Similar Rights. + +Section 5 – Disclaimer of Warranties and Limitation of Liability. + +a. Unless otherwise separately undertaken by the Licensor, to the extent possible, +the Licensor offers the Licensed Material as-is and as-available, and makes +no representations or warranties of any kind concerning the Licensed Material, +whether express, implied, statutory, or other. This includes, without limitation, +warranties of title, merchantability, fitness for a particular purpose, non-infringement, +absence of latent or other defects, accuracy, or the presence or absence of +errors, whether or not known or discoverable. Where disclaimers of warranties +are not allowed in full or in part, this disclaimer may not apply to You. + +b. To the extent possible, in no event will the Licensor be liable to You +on any legal theory (including, without limitation, negligence) or otherwise +for any direct, special, indirect, incidental, consequential, punitive, exemplary, +or other losses, costs, expenses, or damages arising out of this Public License +or use of the Licensed Material, even if the Licensor has been advised of +the possibility of such losses, costs, expenses, or damages. Where a limitation +of liability is not allowed in full or in part, this limitation may not apply +to You. + +c. The disclaimer of warranties and limitation of liability provided above +shall be interpreted in a manner that, to the extent possible, most closely +approximates an absolute disclaimer and waiver of all liability. + +Section 6 – Term and Termination. + +a. This Public License applies for the term of the Copyright and Similar Rights +licensed here. However, if You fail to comply with this Public License, then +Your rights under this Public License terminate automatically. + +b. Where Your right to use the Licensed Material has terminated under Section +6(a), it reinstates: + +1. automatically as of the date the violation is cured, provided it is cured +within 30 days of Your discovery of the violation; or + + 2. upon express reinstatement by the Licensor. + +c. For the avoidance of doubt, this Section 6(b) does not affect any right +the Licensor may have to seek remedies for Your violations of this Public +License. + +d. For the avoidance of doubt, the Licensor may also offer the Licensed Material +under separate terms or conditions or stop distributing the Licensed Material +at any time; however, doing so will not terminate this Public License. + + e. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. + +Section 7 – Other Terms and Conditions. + +a. The Licensor shall not be bound by any additional or different terms or +conditions communicated by You unless expressly agreed. + +b. Any arrangements, understandings, or agreements regarding the Licensed +Material not stated herein are separate from and independent of the terms +and conditions of this Public License. + +Section 8 – Interpretation. + +a. For the avoidance of doubt, this Public License does not, and shall not +be interpreted to, reduce, limit, restrict, or impose conditions on any use +of the Licensed Material that could lawfully be made without permission under +this Public License. + +b. To the extent possible, if any provision of this Public License is deemed +unenforceable, it shall be automatically reformed to the minimum extent necessary +to make it enforceable. If the provision cannot be reformed, it shall be severed +from this Public License without affecting the enforceability of the remaining +terms and conditions. + +c. No term or condition of this Public License will be waived and no failure +to comply consented to unless expressly agreed to by the Licensor. + +d. Nothing in this Public License constitutes or may be interpreted as a limitation +upon, or waiver of, any privileges and immunities that apply to the Licensor +or You, including from the legal processes of any jurisdiction or authority. + +Creative Commons is not a party to its public licenses. Notwithstanding, Creative +Commons may elect to apply one of its public licenses to material it publishes +and in those instances will be considered the "Licensor." The text of the +Creative Commons public licenses is dedicated to the public domain under the +CC0 Public Domain Dedication. Except for the limited purpose of indicating +that material is shared under a Creative Commons public license or as otherwise +permitted by the Creative Commons policies published at creativecommons.org/policies, +Creative Commons does not authorize the use of the trademark "Creative Commons" +or any other trademark or logo of Creative Commons without its prior written +consent including, without limitation, in connection with any unauthorized +modifications to any of its public licenses or any other arrangements, understandings, +or agreements concerning use of licensed material. For the avoidance of doubt, +this paragraph does not form part of the public licenses. + +Creative Commons may be contacted at creativecommons.org. + + +========== +LICENSES/LicenseRef-KhronosFreeUse.txt +========== + +Copyright (c) 2014-2020 The Khronos Group Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and/or associated documentation files (the "Materials"), +to deal in the Materials without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Materials, and to permit persons to whom the +Materials are furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Materials. + +MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS KHRONOS +STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS SPECIFICATIONS AND +HEADER INFORMATION ARE LOCATED AT https://www.khronos.org/registry/ + +THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM,OUT OF OR IN CONNECTION WITH THE MATERIALS OR THE USE OR OTHER DEALINGS +IN THE MATERIALS. + + +========== +LICENSES/MIT.txt +========== + +MIT License Copyright (c) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice (including the next +paragraph) shall be included in all copies or substantial portions of the +Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS +OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF +OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +``` + + +### SPIRV-Headers + +``` +Files: All files except for those called out below. +Copyright (c) 2015-2024 The Khronos Group Inc. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and/or associated documentation files (the +"Materials"), to deal in the Materials without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Materials, and to +permit persons to whom the Materials are furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Materials. + +MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS +KHRONOS STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS +SPECIFICATIONS AND HEADER INFORMATION ARE LOCATED AT + https://www.khronos.org/registry/ + +THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. + +--- + +Files: include/spirv/spir-v.xml +Copyright (c) 2015-2024 The Khronos Group Inc. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and/or associated documentation files (the +"Materials"), to deal in the Materials without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Materials, and to +permit persons to whom the Materials are furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Materials. + +THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. + +--- + +Files: tools/buildHeaders/jsoncpp/* +The JsonCpp library's source code, including accompanying documentation, +tests and demonstration applications, are licensed under the following +conditions... + +The author (Baptiste Lepilleur) explicitly disclaims copyright in all +jurisdictions which recognize such a disclaimer. In such jurisdictions, +this software is released into the Public Domain. + +In jurisdictions which do not recognize Public Domain property (e.g. Germany as of +2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur, and is +released under the terms of the MIT License (see below). + +In jurisdictions which recognize Public Domain property, the user of this +software may choose to accept it either as 1) Public Domain, 2) under the +conditions of the MIT License (see below), or 3) under the terms of dual +Public Domain/MIT License conditions described here, as they choose. + +The MIT License is about as close to Public Domain as a license can get, and is +described in clear, concise terms at: + + http://en.wikipedia.org/wiki/MIT_License + +The full text of the MIT License follows: + +======================================================================== +Copyright (c) 2007-2010 Baptiste Lepilleur + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, copy, +modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS +BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +======================================================================== + +--- + +Files: **.md, WORKSPACE, .git** + +Attribution 4.0 International + +======================================================================= + +Creative Commons Corporation ("Creative Commons") is not a law firm and +does not provide legal services or legal advice. Distribution of +Creative Commons public licenses does not create a lawyer-client or +other relationship. Creative Commons makes its licenses and related +information available on an "as-is" basis. Creative Commons gives no +warranties regarding its licenses, any material licensed under their +terms and conditions, or any related information. Creative Commons +disclaims all liability for damages resulting from their use to the +fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and +conditions that creators and other rights holders may use to share +original works of authorship and other material subject to copyright +and certain other rights specified in the public license below. The +following considerations are for informational purposes only, are not +exhaustive, and do not form part of our licenses. + + Considerations for licensors: Our public licenses are + intended for use by those authorized to give the public + permission to use material in ways otherwise restricted by + copyright and certain other rights. Our licenses are + irrevocable. Licensors should read and understand the terms + and conditions of the license they choose before applying it. + Licensors should also secure all rights necessary before + applying our licenses so that the public can reuse the + material as expected. Licensors should clearly mark any + material not subject to the license. This includes other CC- + licensed material, or material used under an exception or + limitation to copyright. More considerations for licensors: + wiki.creativecommons.org/Considerations_for_licensors + + Considerations for the public: By using one of our public + licenses, a licensor grants the public permission to use the + licensed material under specified terms and conditions. If + the licensor's permission is not necessary for any reason--for + example, because of any applicable exception or limitation to + copyright--then that use is not regulated by the license. Our + licenses grant only permissions under copyright and certain + other rights that a licensor has authority to grant. Use of + the licensed material may still be restricted for other + reasons, including because others have copyright or other + rights in the material. A licensor may make special requests, + such as asking that all changes be marked or described. + Although not required by our licenses, you are encouraged to + respect those requests where reasonable. More considerations + for the public: + wiki.creativecommons.org/Considerations_for_licensees + +======================================================================= + +Creative Commons Attribution 4.0 International Public License + +By exercising the Licensed Rights (defined below), You accept and agree +to be bound by the terms and conditions of this Creative Commons +Attribution 4.0 International Public License ("Public License"). To the +extent this Public License may be interpreted as a contract, You are +granted the Licensed Rights in consideration of Your acceptance of +these terms and conditions, and the Licensor grants You such rights in +consideration of benefits the Licensor receives from making the +Licensed Material available under these terms and conditions. + + +Section 1 -- Definitions. + + a. Adapted Material means material subject to Copyright and Similar + Rights that is derived from or based upon the Licensed Material + and in which the Licensed Material is translated, altered, + arranged, transformed, or otherwise modified in a manner requiring + permission under the Copyright and Similar Rights held by the + Licensor. For purposes of this Public License, where the Licensed + Material is a musical work, performance, or sound recording, + Adapted Material is always produced where the Licensed Material is + synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright + and Similar Rights in Your contributions to Adapted Material in + accordance with the terms and conditions of this Public License. + + c. Copyright and Similar Rights means copyright and/or similar rights + closely related to copyright including, without limitation, + performance, broadcast, sound recording, and Sui Generis Database + Rights, without regard to how the rights are labeled or + categorized. For purposes of this Public License, the rights + specified in Section 2(b)(1)-(2) are not Copyright and Similar + Rights. + + d. Effective Technological Measures means those measures that, in the + absence of proper authority, may not be circumvented under laws + fulfilling obligations under Article 11 of the WIPO Copyright + Treaty adopted on December 20, 1996, and/or similar international + agreements. + + e. Exceptions and Limitations means fair use, fair dealing, and/or + any other exception or limitation to Copyright and Similar Rights + that applies to Your use of the Licensed Material. + + f. Licensed Material means the artistic or literary work, database, + or other material to which the Licensor applied this Public + License. + + g. Licensed Rights means the rights granted to You subject to the + terms and conditions of this Public License, which are limited to + all Copyright and Similar Rights that apply to Your use of the + Licensed Material and that the Licensor has authority to license. + + h. Licensor means the individual(s) or entity(ies) granting rights + under this Public License. + + i. Share means to provide material to the public by any means or + process that requires permission under the Licensed Rights, such + as reproduction, public display, public performance, distribution, + dissemination, communication, or importation, and to make material + available to the public including in ways that members of the + public may access the material from a place and at a time + individually chosen by them. + + j. Sui Generis Database Rights means rights other than copyright + resulting from Directive 96/9/EC of the European Parliament and of + the Council of 11 March 1996 on the legal protection of databases, + as amended and/or succeeded, as well as other essentially + equivalent rights anywhere in the world. + + k. You means the individual or entity exercising the Licensed Rights + under this Public License. Your has a corresponding meaning. + + +Section 2 -- Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, + the Licensor hereby grants You a worldwide, royalty-free, + non-sublicensable, non-exclusive, irrevocable license to + exercise the Licensed Rights in the Licensed Material to: + + a. reproduce and Share the Licensed Material, in whole or + in part; and + + b. produce, reproduce, and Share Adapted Material. + + 2. Exceptions and Limitations. For the avoidance of doubt, where + Exceptions and Limitations apply to Your use, this Public + License does not apply, and You do not need to comply with + its terms and conditions. + + 3. Term. The term of this Public License is specified in Section + 6(a). + + 4. Media and formats; technical modifications allowed. The + Licensor authorizes You to exercise the Licensed Rights in + all media and formats whether now known or hereafter created, + and to make technical modifications necessary to do so. The + Licensor waives and/or agrees not to assert any right or + authority to forbid You from making technical modifications + necessary to exercise the Licensed Rights, including + technical modifications necessary to circumvent Effective + Technological Measures. For purposes of this Public License, + simply making modifications authorized by this Section 2(a) + (4) never produces Adapted Material. + + 5. Downstream recipients. + + a. Offer from the Licensor -- Licensed Material. Every + recipient of the Licensed Material automatically + receives an offer from the Licensor to exercise the + Licensed Rights under the terms and conditions of this + Public License. + + b. No downstream restrictions. You may not offer or impose + any additional or different terms or conditions on, or + apply any Effective Technological Measures to, the + Licensed Material if doing so restricts exercise of the + Licensed Rights by any recipient of the Licensed + Material. + + 6. No endorsement. Nothing in this Public License constitutes or + may be construed as permission to assert or imply that You + are, or that Your use of the Licensed Material is, connected + with, or sponsored, endorsed, or granted official status by, + the Licensor or others designated to receive attribution as + provided in Section 3(a)(1)(A)(i). + + b. Other rights. + + 1. Moral rights, such as the right of integrity, are not + licensed under this Public License, nor are publicity, + privacy, and/or other similar personality rights; however, to + the extent possible, the Licensor waives and/or agrees not to + assert any such rights held by the Licensor to the limited + extent necessary to allow You to exercise the Licensed + Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this + Public License. + + 3. To the extent possible, the Licensor waives any right to + collect royalties from You for the exercise of the Licensed + Rights, whether directly or through a collecting society + under any voluntary or waivable statutory or compulsory + licensing scheme. In all other cases the Licensor expressly + reserves any right to collect such royalties. + + +Section 3 -- License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the +following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified + form), You must: + + a. retain the following if it is supplied by the Licensor + with the Licensed Material: + + i. identification of the creator(s) of the Licensed + Material and any others designated to receive + attribution, in any reasonable manner requested by + the Licensor (including by pseudonym if + designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of + warranties; + + v. a URI or hyperlink to the Licensed Material to the + extent reasonably practicable; + + b. indicate if You modified the Licensed Material and + retain an indication of any previous modifications; and + + c. indicate the Licensed Material is licensed under this + Public License, and include the text of, or the URI or + hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any + reasonable manner based on the medium, means, and context in + which You Share the Licensed Material. For example, it may be + reasonable to satisfy the conditions by providing a URI or + hyperlink to a resource that includes the required + information. + + 3. If requested by the Licensor, You must remove any of the + information required by Section 3(a)(1)(A) to the extent + reasonably practicable. + + 4. If You Share Adapted Material You produce, the Adapter's + License You apply must not prevent recipients of the Adapted + Material from complying with this Public License. + + +Section 4 -- Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that +apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right + to extract, reuse, reproduce, and Share all or a substantial + portion of the contents of the database; + + b. if You include all or a substantial portion of the database + contents in a database in which You have Sui Generis Database + Rights, then the database in which You have Sui Generis Database + Rights (but not its individual contents) is Adapted Material; and + + c. You must comply with the conditions in Section 3(a) if You Share + all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not +replace Your obligations under this Public License where the Licensed +Rights include other Copyright and Similar Rights. + + +Section 5 -- Disclaimer of Warranties and Limitation of Liability. + + a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE + EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS + AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF + ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, + IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, + WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR + PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, + ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT + KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT + ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. + + b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE + TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, + NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, + INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, + COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR + USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR + DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR + IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. + + c. The disclaimer of warranties and limitation of liability provided + above shall be interpreted in a manner that, to the extent + possible, most closely approximates an absolute disclaimer and + waiver of all liability. + + +Section 6 -- Term and Termination. + + a. This Public License applies for the term of the Copyright and + Similar Rights licensed here. However, if You fail to comply with + this Public License, then Your rights under this Public License + terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under + Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided + it is cured within 30 days of Your discovery of the + violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any + right the Licensor may have to seek remedies for Your violations + of this Public License. + + c. For the avoidance of doubt, the Licensor may also offer the + Licensed Material under separate terms or conditions or stop + distributing the Licensed Material at any time; however, doing so + will not terminate this Public License. + + d. Sections 1, 5, 6, 7, and 8 survive termination of this Public + License. + + +Section 7 -- Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different + terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the + Licensed Material not stated herein are separate from and + independent of the terms and conditions of this Public License. + + +Section 8 -- Interpretation. + + a. For the avoidance of doubt, this Public License does not, and + shall not be interpreted to, reduce, limit, restrict, or impose + conditions on any use of the Licensed Material that could lawfully + be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is + deemed unenforceable, it shall be automatically reformed to the + minimum extent necessary to make it enforceable. If the provision + cannot be reformed, it shall be severed from this Public License + without affecting the enforceability of the remaining terms and + conditions. + + c. No term or condition of this Public License will be waived and no + failure to comply consented to unless expressly agreed to by the + Licensor. + + d. Nothing in this Public License constitutes or may be interpreted + as a limitation upon, or waiver of, any privileges and immunities + that apply to the Licensor or You, including from the legal + processes of any jurisdiction or authority. + + +======================================================================= + +Creative Commons is not a party to its public +licenses. Notwithstanding, Creative Commons may elect to apply one of +its public licenses to material it publishes and in those instances +will be considered the “Licensor.” The text of the Creative Commons +public licenses is dedicated to the public domain under the CC0 Public +Domain Dedication. Except for the limited purpose of indicating that +material is shared under a Creative Commons public license or as +otherwise permitted by the Creative Commons policies published at +creativecommons.org/policies, Creative Commons does not authorize the +use of the trademark "Creative Commons" or any other trademark or logo +of Creative Commons without its prior written consent including, +without limitation, in connection with any unauthorized modifications +to any of its public licenses or any other arrangements, +understandings, or agreements concerning use of licensed material. For +the avoidance of doubt, this paragraph does not form part of the +public licenses. + +Creative Commons may be contacted at creativecommons.org. +``` + + +### SPIRV-Tools + +``` +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +``` + + +### TinyEXR + +``` +Copyright (c) 2014 - 2018, Syoyo Fujita and many contributors. +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 ------------------------------------------------- + +BEGIN ASL-2.0.txt + +// Copyright 2017 The Wuffs Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +END ASL-2.0.txt + +------------------ + +BEGIN third_party/tinyexr/APACHE2_LICENSE.txt + + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +END third_party/tinyexr/APACHE2_LICENSE.txt +``` + + +### Vulkan Memory Allocator + +``` +Copyright (c) 2017-2019 Advanced Micro Devices, Inc. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +``` diff --git a/src/dvidia_training/workstation_assets.js b/src/dvidia_training/workstation_assets.js new file mode 100644 index 0000000..41d3ec1 --- /dev/null +++ b/src/dvidia_training/workstation_assets.js @@ -0,0 +1,298 @@ +/* Verified delivery of the exact native mesh bytes. MIT. */ +export const MAX_RESOURCE_BYTES = 64 * 1024 * 1024; +export const MAX_TOTAL_BYTES = 192 * 1024 * 1024; + +export function localResource(path, base) { + if (typeof path !== 'string' || path.length > 1024 || path.startsWith('/') + || path.split('/').some(part => part === '..') || path.includes('\\')) throw new Error('Invalid local asset path'); + const url = new URL(path, base); + if (url.origin !== base.origin || !['http:', 'https:'].includes(url.protocol)) { + throw new Error('Workstation resources must be same-origin HTTP assets'); + } + return url; +} + +function descriptor(expected, limit = MAX_RESOURCE_BYTES) { + if (!expected || !Number.isSafeInteger(expected.bytes) || expected.bytes < 0 || expected.bytes > limit + || typeof expected.sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(expected.sha256)) { + throw new Error('Asset size or digest descriptor mismatch'); + } +} + +async function verify(bytes, expected) { + descriptor(expected); + if (bytes.length !== expected.bytes) throw new Error('Asset size mismatch'); + const digest = Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)), + value => value.toString(16).padStart(2, '0')).join(''); + if (digest !== expected.sha256) throw new Error('Asset checksum mismatch'); +} + +export async function boundedStreamBytes(stream, limit) { + if (!stream) throw new Error('Streaming resource responses are required'); + if (!Number.isSafeInteger(limit) || limit < 0 || limit > MAX_TOTAL_BYTES) throw new Error('Invalid resource limit'); + const reader = stream.getReader(); + const chunks = []; let received = 0; + try { + while (true) { + const {done, value} = await reader.read(); + if (done) break; + received += value.byteLength; + if (received > limit) { + await reader.cancel(); + throw new Error('Resource is too large'); + } + chunks.push(value); + } + } finally { reader.releaseLock(); } + const bytes = new Uint8Array(received); let offset = 0; + for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; } + return bytes; +} + +const HF_SPACE_HOST = 'dvidia-robot-simulation-lab.static.hf.space'; +const HF_CDN_HOST = 'us.aws.cdn.hf.co'; +const RETRY_HTTP_STATUS = new Set([408, 429, 502, 503, 504]); +// Only these reviewed bytes in the published v0.1 Space have a public mirror. +// A different scene, hash, origin or path keeps its ordinary local delivery. +const HOSTED_ASSETS = Object.freeze({ + 'geometry.bin.gz': {bytes: 3574720, sha256: '51365a5a661d8062e28c66abc6bdb843ee410811f84b49d62c5878c265b3631f'}, + 'native-assets.bin.gz': {bytes: 7318481, sha256: '9c960598f9b2c0c7459a8bdfc8a544513b4c6ffaff2c8787fa49f728774eb9e7'}, + 'mujoco.wasm.gz': {bytes: 2543112, sha256: 'ad01772e00939bf6300a953b396d38aa9ec03c05fcda46c3c8d940d56f772b3b'}, +}); + +function hostedMirror(url, expected) { + if (url.protocol !== 'https:' || url.host !== HF_SPACE_HOST || url.search || url.hash || !expected) return null; + const name = url.pathname.split('/').pop(); + const approved = HOSTED_ASSETS[name]; + if (!approved || url.pathname !== '/workstation/v01/' + name + || expected.bytes !== approved.bytes || expected.sha256 !== approved.sha256) return null; + return new URL('https://research.dvidia.org/runtime/workstation/' + approved.sha256 + '/' + name); +} + +class ResourceDownloadError extends Error { + constructor(message, retryable = false) { + super(message); this.name = 'ResourceDownloadError'; this.retryable = retryable; + } +} + +function transportOptions(options, expected) { + const settings = {maxBytes: expected?.bytes ?? MAX_RESOURCE_BYTES, idleTimeoutMs: 30000, + timeoutMs: 120000, maxAttempts: 3, retryDelayMs: 250, ...options}; + for (const [name, maximum, minimum] of [['maxBytes', MAX_RESOURCE_BYTES, 0], + ['idleTimeoutMs', 120000, 1], ['timeoutMs', 120000, 1], ['maxAttempts', 3, 1], ['retryDelayMs', 2000, 0]]) { + if (!Number.isSafeInteger(settings[name]) || settings[name] < minimum || settings[name] > maximum) { + throw new Error(`Invalid resource transport option: ${name}`); + } + } + if (expected && settings.maxBytes < expected.bytes) throw new Error('Resource byte limit is smaller than its descriptor'); + if (settings.onProgress !== undefined && typeof settings.onProgress !== 'function') throw new Error('Invalid resource progress callback'); + return settings; +} + +// Fetch resolves at headers. Cover every body read too so a stalled CDN +// response cannot leave startup hanging indefinitely. +async function withAbort(promise, signal) { + if (signal.aborted) throw signal.reason; + let listener; + const interrupted = new Promise((resolve, reject) => { + listener = () => reject(signal.reason); + signal.addEventListener('abort', listener, {once: true}); + }); + try { return await Promise.race([promise, interrupted]); } + finally { signal.removeEventListener('abort', listener); } +} + +async function downloadBody(stream, limit, signal, onChunk) { + if (!stream) throw new ResourceDownloadError('The server returned an empty resource'); + const reader = stream.getReader(); const chunks = []; let received = 0; let finished = false; + try { + for (;;) { + let result; + try { result = await withAbort(reader.read(), signal); } + catch (error) { + if (signal.aborted) throw signal.reason; + throw new ResourceDownloadError(`Body download interrupted: ${error.message || 'network error'}`, true); + } + if (result.done) { finished = true; break; } + received += result.value.byteLength; + if (received > limit) throw new ResourceDownloadError('Resource is too large'); + chunks.push(result.value); + if (result.value.byteLength) onChunk(received); + } + } finally { + // Do not wait for a broken underlying source to acknowledge cancellation. + if (!finished) void reader.cancel().catch(() => {}); + reader.releaseLock(); + } + const bytes = new Uint8Array(received); let offset = 0; + for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; } + return bytes; +} + +export async function resourceBytes(input, expected, options = {}) { + if (expected) descriptor(expected); + const settings = transportOptions(options, expected); + const url = new URL(input); + if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) throw new Error('Invalid resource URL'); + const hosted = url.protocol === 'https:' && url.host === HF_SPACE_HOST; + const mirror = hostedMirror(url, expected); + const deadline = performance.now() + settings.timeoutMs; + const label = url.pathname.split('/').pop() || 'resource'; + let totalBytes = expected?.bytes ?? null; + const progress = (phase, attempt, receivedBytes = 0) => settings.onProgress?.({ + path: url.pathname, phase, attempt, receivedBytes, totalBytes}); + const expired = () => new ResourceDownloadError('Total download deadline exceeded'); + for (let attempt = 1; attempt <= settings.maxAttempts; attempt += 1) { + const remaining = deadline - performance.now(); + if (remaining <= 0) throw new Error(`Could not download ${label}: total download deadline exceeded`); + const controller = new AbortController(); + const mirrored = mirror !== null && attempt === 1; + const requestURL = mirrored ? mirror : url; + const totalTimer = setTimeout(() => controller.abort(expired()), remaining); + let idleTimer; + const active = () => { + clearTimeout(idleTimer); + idleTimer = setTimeout(() => controller.abort(new ResourceDownloadError('Download stalled without receiving data', true)), + settings.idleTimeoutMs); + }; + try { + totalBytes = expected?.bytes ?? null; + progress('downloading', attempt); active(); + let response; + try { + response = await withAbort(fetch(requestURL, {credentials: 'omit', referrerPolicy: 'no-referrer', + redirect: mirrored ? 'manual' : hosted ? 'follow' : 'error', signal: controller.signal, + ...(attempt > 1 ? {cache: 'reload'} : {})}), controller.signal); + } catch (error) { + if (controller.signal.aborted) throw controller.signal.reason; + throw new ResourceDownloadError(`Network request failed: ${error.message || 'network error'}`, true); + } + active(); + // A manual cross-origin redirect is opaque. Reject it without following + // or treating a policy violation as transient mirror unavailability. + if (mirrored && (response.type === 'opaqueredirect' || response.redirected + || (response.status >= 300 && response.status < 400))) { + void response.body?.cancel().catch(() => {}); + throw new ResourceDownloadError('The pinned workstation mirror may not redirect'); + } + const final = new URL(response.url); + if (mirrored ? final.href !== requestURL.href + : final.origin !== url.origin && !(hosted && final.protocol === 'https:' && final.host === HF_CDN_HOST)) { + void response.body?.cancel().catch(() => {}); + throw new ResourceDownloadError('Resource redirected outside the permitted workstation host'); + } + if (!response.ok) { + void response.body?.cancel().catch(() => {}); + throw new ResourceDownloadError(`HTTP ${response.status}`, RETRY_HTTP_STATUS.has(response.status) + || (mirrored && [404, 410].includes(response.status))); + } + if (Number(response.headers.get('content-length')) > settings.maxBytes) { + void response.body?.cancel().catch(() => {}); + throw new ResourceDownloadError('Resource is too large'); + } + const lengthHeader = response.headers.get('content-length'); + const encoding = response.headers.get('content-encoding'); + if (!expected && (!encoding || encoding === 'identity') && /^\d+$/.test(lengthHeader ?? '') + && Number.isSafeInteger(Number(lengthHeader)) && Number(lengthHeader) <= settings.maxBytes) { + totalBytes = Number(lengthHeader); progress('downloading', attempt); + } + const bytes = await downloadBody(response.body, expected?.bytes ?? settings.maxBytes, controller.signal, received => { + active(); progress('downloading', attempt, received); + }); + if (expected) await verify(bytes, expected); + progress('complete', attempt, bytes.byteLength); + return bytes; + } catch (error) { + const canRetry = error instanceof ResourceDownloadError && error.retryable + && attempt < settings.maxAttempts && performance.now() < deadline; + if (!canRetry) throw new Error(`Could not download ${label} (attempt ${attempt}/${settings.maxAttempts}): ${error.message}`); + progress('retrying', attempt); + const delay = Math.min(settings.retryDelayMs * attempt, Math.max(0, deadline - performance.now())); + if (delay) await new Promise(resolve => setTimeout(resolve, delay)); + } finally { clearTimeout(totalTimer); clearTimeout(idleTimer); } + } +} + +export function nativeAssetBytes(assets) { + if (!Array.isArray(assets) || assets.length > 256) throw new Error('Invalid asset manifest'); + let total = 0; + const paths = new Set(); + for (const asset of assets) { + descriptor(asset); + if (paths.has(asset.path)) throw new Error('Duplicate native asset path'); + paths.add(asset.path); + total += asset.bytes; + if (total > MAX_TOTAL_BYTES) throw new Error('Scene assets exceed worker memory budget'); + } + return total; +} + +export function validateBundle(bundle, assets) { + descriptor(bundle); + const total = nativeAssetBytes(assets); + if (bundle.compression !== 'gzip' || bundle.path !== 'native-assets.bin.gz' + || !Number.isSafeInteger(bundle.uncompressed_bytes) || bundle.uncompressed_bytes !== total) { + throw new Error('Invalid native asset bundle descriptor'); + } + return total; +} + +async function decodeGzip(packed, limit, path) { + try { + const stream = new Blob([packed]).stream().pipeThrough(new DecompressionStream('gzip')); + return await boundedStreamBytes(stream, limit); + } catch (error) { throw new Error(`Could not decode ${path}: ${error.message}`); } +} + +export async function unpackNativeAssets(packed, bundle, assets) { + const total = validateBundle(bundle, assets); + await verify(packed, bundle); + // Bound decoded output independently of the compressed download to reject + // truncation, trailing members and compression bombs before model loading. + const unpacked = await decodeGzip(packed, total, bundle.path); + if (unpacked.byteLength !== total) throw new Error('Native asset bundle is truncated'); + const result = []; let offset = 0; + for (const asset of assets) { + const bytes = unpacked.subarray(offset, offset + asset.bytes); + await verify(bytes, asset); + result.push({path: asset.path, bytes}); offset += asset.bytes; + } + return result; +} + +export async function loadNativeAssets(manifest, base, options = {}) { + nativeAssetBytes(manifest.assets); + for (const asset of manifest.assets) localResource(asset.path, base); + if (manifest.native_asset_bundle !== undefined) { + const bundle = manifest.native_asset_bundle; + validateBundle(bundle, manifest.assets); + const packed = await resourceBytes(localResource(bundle.path, base), bundle, options); + return unpackNativeAssets(packed, bundle, manifest.assets); + } + // Older exports remain readable. Newly exported scenes use one compressed + // request while keeping these original files for independent reproduction. + const result = []; + for (const asset of manifest.assets) result.push({path: asset.path, + bytes: await resourceBytes(localResource(asset.path, base), asset, options)}); + return result; +} + +export async function loadWasmBytes(manifest, base, options = {}) { + const native = manifest.native_wasm; + if (native !== undefined) { + descriptor(native); + if (native.path !== 'mujoco.wasm') throw new Error('Invalid native WASM descriptor'); + } + const bundle = manifest.wasm_bundle; + if (bundle === undefined) return resourceBytes(localResource('mujoco.wasm', base), native, options); + descriptor(bundle); + if (!native || bundle.path !== 'mujoco.wasm.gz' || bundle.compression !== 'gzip' + || !Number.isSafeInteger(bundle.uncompressed_bytes) || bundle.uncompressed_bytes !== native.bytes) { + throw new Error('Invalid WASM bundle descriptor'); + } + const packed = await resourceBytes(localResource(bundle.path, base), bundle, options); + const unpacked = await decodeGzip(packed, native.bytes, bundle.path); + try { await verify(unpacked, native); } + catch (error) { throw new Error(`Decoded ${native.path} from ${bundle.path}: ${error.message}`); } + return unpacked; +} diff --git a/src/dvidia_training/workstation_benchmark.py b/src/dvidia_training/workstation_benchmark.py new file mode 100644 index 0000000..df88fdf --- /dev/null +++ b/src/dvidia_training/workstation_benchmark.py @@ -0,0 +1,168 @@ +"""Frozen native tracking and contact diagnostics for the live workstation. + +Every planned attempt is retained. This protocol evaluates authored target +tracking and free-object mechanics, not autonomous shoe grasping or real transfer. +""" +from __future__ import annotations +import argparse +from hashlib import sha256 +import json +import math +import os +from pathlib import Path +import platform +import time + +from . import workstation as ws, reference_sim as sim + + +def encode(value): + return (json.dumps(value, indent=2, allow_nan=False)+'\n').encode() + + +def protocol(stability_seconds=600): + if type(stability_seconds) is not int or not 10 <= stability_seconds <= 600: + raise ValueError('Stability duration must be an integer from 10 through 600 seconds') + targets = [('home', [.36,-.06,.27]), ('left', [.32,-.16,.24]), + ('right', [.36,.10,.25]), ('near', [.27,-.04,.22]), + ('far', [.47,-.04,.24]), ('high', [.36,-.06,.32]), + ('low', [.36,-.06,.12]), ('shoe_approach', [.32,-.145,.16])] + attempts = [{'id':name+'-'+str(repeat), 'kind':'tracking', 'target':position, + 'seconds':4, 'jaw':.035} for repeat in range(2) for name,position in targets] + attempts += [ + {'id':'jaw_close_open','kind':'jaw','target':list(ws.HOME_TARGET),'seconds':4,'jaw':.035}, + {'id':'shoe_nudge','kind':'push','target':list(ws.HOME_TARGET),'seconds':4,'jaw':.035}, + {'id':'table_disabled','kind':'gravity_control','target':list(ws.HOME_TARGET),'seconds':2,'jaw':.035}, + {'id':'sustained_hold','kind':'stability','target':list(ws.HOME_TARGET),'seconds':stability_seconds,'jaw':.035}] + return {'schema':'dvidia.workstation-benchmark-protocol/v1','attempts':attempts, + 'scope':'Authored target tracking, jaw travel, free-object support and numerical stability; no learned grasp policy', + 'physics_dt_s':ws.TIMESTEP,'control_dt_s':ws.CONTROL_DT, + 'tracking_position_tolerance_m':.005,'tracking_orientation_tolerance_deg':3., + 'jaw_endpoint_tolerance_m':.002,'push_impulse_ns':[0,.12,0], + 'tracking_deadline_s':4,'sample_interval_s':.02,'stability_sample_interval_s':.1, + 'timing_scope':'Native Python control interval including ten physics steps, forward kinematics and diagnostic extraction; rendering and network excluded', + 'repeats_scope':'Two deterministic resets per target; not independent real-world reliability trials'} + + +def hashes(): + root=Path(__file__).parent + return {name:sha256((root/name).read_bytes()).hexdigest() for name in + ['workstation.py','workstation_benchmark.py','asset_library.py','asset_catalog.json','robot_profiles.py']} + + +def peak_rss(): + try: + import resource + return resource.getrusage(resource.RUSAGE_SELF).ru_maxrss*(1 if platform.system()=='Darwin' else 1024) + except ImportError: + return None + + +def benchmark(assets, output, *, stability_seconds=600, source_commit=None): + destination=Path(output) + if destination.exists() or destination.is_symlink():raise ValueError('Benchmark output must be fresh') + if source_commit is not None and (len(source_commit)!=40 or any(c not in '0123456789abcdef' for c in source_commit)): + raise ValueError('Source commit must be a complete Git SHA') + mj,np=sim._native_imports() + plan=protocol(stability_seconds) + plan.update(source_commit=source_commit, implementation_sha256=hashes()) + destination.mkdir(parents=True) + (destination/'protocol.json').write_bytes(encode(plan)) + records=[]; started=time.perf_counter() + all_durations=[] + for case in plan['attempts']: + begin=time.perf_counter(); warnings=[] + rows=[]; durations=[]; errors=[]; valid=True; controls_within_limits=True + arm_environment_contact_samples=0; maximum_arm_environment_force_n=0. + try: + with sim.native_warnings(warnings): + model=ws.build_model(assets); data=ws.initialize(model) + tcp,shoe=ws._ids(model) + if case['kind']=='gravity_control': + table=mj.mj_name2id(model,mj.mjtObj.mjOBJ_GEOM,'workstation_table_top') + model.geom_contype[table]=0;model.geom_conaffinity[table]=0 + mj.mj_forward(model,data) + initial=ws.state(model,data,case['target']) + rows.append({'step':0,**initial}) + jaw_closed=None; peak_shoe_displacement=0.; push_origin=None + for step in range(round(case['seconds']/ws.CONTROL_DT)): + jaw=0. if case['kind']=='jaw' and step<100 else case['jaw'] + impulse=plan['push_impulse_ns'] if case['kind']=='push' and step==50 else None + if impulse is not None:push_origin=data.xpos[shoe].copy() + start=time.perf_counter_ns() + state=ws.step(model,data,case['target'],jaw,impulse_xyz=impulse) + durations.append((time.perf_counter_ns()-start)/1e6) + controls_within_limits &= bool(np.all(data.ctrl>=model.actuator_ctrlrange[:,0]) and np.all(data.ctrl<=model.actuator_ctrlrange[:,1])) + for contact in state['contacts']: + body1,body2=(int(model.geom_bodyid[contact[name]]) for name in ('geom1','geom2')) + if ((body1==0 and body2 not in (0,1,shoe)) or (body2==0 and body1 not in (0,1,shoe))): + arm_environment_contact_samples+=1 + maximum_arm_environment_force_n=max(maximum_arm_environment_force_n,contact['normal_force_n']) + if case['kind']=='jaw' and step==99:jaw_closed=float(data.qpos[6]) + if push_origin is not None:peak_shoe_displacement=max(peak_shoe_displacement,float(np.linalg.norm(data.xpos[shoe]-push_origin))) + if case['kind']!='stability' or (step+1)%5==0: + rows.append({'step':step+1,**state}) + final=ws.state(model,data,case['target']) + dot=abs(float(np.dot(final['tcp_quaternion'],ws.ORIENTATION))) + angle=math.degrees(2*math.acos(min(1.,dot))) + result={'position_error_m':final['position_error_m'],'orientation_error_deg':angle, + 'final_shoe_position_m':final['shoe_position'],'final_jaw_m':float(data.qpos[6]), + 'closed_jaw_m':jaw_closed,'peak_post_push_displacement_m':peak_shoe_displacement, + 'controls_within_limits':bool(controls_within_limits), + 'simulated_seconds':float(data.time), + 'arm_environment_loaded_contact_samples':arm_environment_contact_samples, + 'maximum_arm_environment_normal_force_n':maximum_arm_environment_force_n} + if case['kind']=='tracking':passed=final['position_error_m']<=.005 and angle<=3 + elif case['kind']=='jaw':passed=abs(jaw_closed)<=.002 and abs(float(data.qpos[6])-.035)<=.002 + elif case['kind']=='push':passed=peak_shoe_displacement>.001 + elif case['kind']=='gravity_control':passed=final['shoe_position'][2]<-.3 + else:passed=controls_within_limits and final['position_error_m']<=.005 + valid=(not warnings and not any(w.number for w in data.warning) + and all(np.isfinite(value).all() for value in (data.qpos,data.qvel,data.qacc,data.ctrl)) + and abs(float(data.time)-case['seconds'])<1e-6) + passed=passed and controls_within_limits + except Exception as exc: + valid=False;passed=False;result={};errors.append(type(exc).__name__+': '+str(exc)) + records.append({'case':case,'valid':valid,'passed':bool(passed and valid), + 'warnings':warnings,'errors':errors,'result':result, + 'wall_seconds_including_model':time.perf_counter()-begin, + 'control_interval_compute_ms':durations,'trajectory':rows}) + all_durations.extend(durations) + # Preserve each completed attempt even if a later attempt is interrupted. + (destination/'attempts.json').write_bytes((json.dumps(records, separators=(',', ':'), allow_nan=False)+'\n').encode()) + array=np.asarray(all_durations) + tracking=[item for item in records if item['case']['kind']=='tracking'] + measured_tracking=[r['result']['position_error_m'] for r in tracking if 'position_error_m' in r['result']] + report={'schema':'dvidia.workstation-benchmark/v1','source_commit':source_commit, + 'protocol_sha256':sha256((destination/'protocol.json').read_bytes()).hexdigest(), + 'native_version':mj.__version__,'physical_robot_ready':False,'learned_policy':False, + 'attempts':len(records),'valid_attempts':sum(r['valid'] for r in records), + 'tracking':{'passed':sum(r['passed'] for r in tracking),'attempts':len(tracking), + 'worst_position_error_m':max(measured_tracking,default=None), + 'unmeasured_attempts':len(tracking)-len(measured_tracking)}, + 'diagnostics':{r['case']['kind']:{'passed':r['passed'],**r['result']} for r in records if r['case']['kind']!='tracking'}, + 'timing':{'wall_seconds':time.perf_counter()-started, + 'compute_ms_p50':float(np.percentile(array,50)) if len(array) else None, + 'compute_ms_p95':float(np.percentile(array,95)) if len(array) else None, + 'compute_ms_p99':float(np.percentile(array,99)) if len(array) else None, + 'compute_ms_max':float(array.max()) if len(array) else None, + 'intervals_over_20ms':int(np.sum(array>20)),'intervals':len(array)}, + 'host':{'os':platform.system(),'os_release':platform.release(),'machine':platform.machine(),'logical_cpus':os.cpu_count(), + 'peak_process_rss_bytes':peak_rss()}, + 'scope':plan['scope'],'timing_scope':plan['timing_scope'], + 'sampling_scope':'Full qpos, ctrl, body poses and loaded contact diagnostics at 20 ms, or 100 ms for sustained hold; not an exhaustive every-physics-tick contact record'} + (destination/'report.json').write_bytes(encode(report)) + files={p.name:{'bytes':p.stat().st_size,'sha256':sha256(p.read_bytes()).hexdigest()} for p in sorted(destination.iterdir()) if p.is_file()} + (destination/'integrity.json').write_bytes(encode({'schema':'dvidia.workstation-benchmark-integrity/v1','files':files})) + return report + + +def main(): + parser=argparse.ArgumentParser(description=__doc__) + parser.add_argument('--assets',required=True);parser.add_argument('--output',required=True) + parser.add_argument('--stability-seconds',type=int,default=600);parser.add_argument('--source-commit') + args=parser.parse_args() + print(json.dumps(benchmark(args.assets,args.output,stability_seconds=args.stability_seconds,source_commit=args.source_commit),indent=2)) + + +if __name__=='__main__':main() diff --git a/src/dvidia_training/workstation_control.js b/src/dvidia_training/workstation_control.js new file mode 100644 index 0000000..75566e2 --- /dev/null +++ b/src/dvidia_training/workstation_control.js @@ -0,0 +1,85 @@ +/* DVIDIA live workstation control math. MIT. SI units; quaternions are wxyz. */ + +export const clamp = (value, minimum, maximum) => Math.max(minimum, Math.min(maximum, value)); + +export function finiteVector(value, length, name) { + if (!Array.isArray(value) || value.length !== length || !value.every(Number.isFinite)) { + throw new Error(`${name} must contain ${length} finite numbers`); + } + return value.slice(); +} + +export function boundedTarget(value, bounds) { + const position = finiteVector(value, 3, 'Target'); + if (position.some((coordinate, axis) => coordinate < bounds[axis][0] || coordinate > bounds[axis][1])) { + throw new Error('Target is outside the workstation workspace'); + } + return position; +} + +export function limitNorm(vector, maximum) { + const length = Math.hypot(...vector); + return length > maximum ? vector.map(value => value * maximum / length) : vector.slice(); +} + +// Partial-pivot Gaussian elimination on the small regularized 6x6 system. +// Throws instead of sending non-finite or ill-conditioned targets to actuators. +export function solveLinear(matrix, rhs) { + const n = rhs.length; + const rows = matrix.map((row, index) => [...row, rhs[index]]); + for (let column = 0; column < n; column += 1) { + let pivot = column; + for (let row = column + 1; row < n; row += 1) { + if (Math.abs(rows[row][column]) > Math.abs(rows[pivot][column])) pivot = row; + } + if (!Number.isFinite(rows[pivot][column]) || Math.abs(rows[pivot][column]) < 1e-14) { + throw new Error('Controller solve is singular'); + } + [rows[column], rows[pivot]] = [rows[pivot], rows[column]]; + const divisor = rows[column][column]; + for (let item = column; item <= n; item += 1) rows[column][item] /= divisor; + for (let row = 0; row < n; row += 1) { + if (row === column) continue; + const scale = rows[row][column]; + for (let item = column; item <= n; item += 1) rows[row][item] -= scale * rows[column][item]; + } + } + return rows.map(row => row[n]); +} + +export function dampedTargets({jacp, jacr, nv, dofIds, qpos, qposIds, target, current, + rotationWorld, ctrlRange, config}) { + const translation = limitNorm(target.map((value, axis) => value - current[axis]), config.translation_error_cap_m); + const rotation = limitNorm(rotationWorld, config.rotation_error_cap_rad); + const weight = config.orientation_weight; + const jacobian = Array.from({length: 6}, (_, row) => dofIds.map(dof => ( + row < 3 ? jacp[row * nv + dof] : weight * jacr[(row - 3) * nv + dof] + ))); + const error = [...translation, ...rotation.map(value => value * weight)]; + const normal = jacobian.map((row, i) => jacobian.map((other, j) => ( + row.reduce((sum, value, index) => sum + value * other[index], 0) + + (i === j ? config.damping ** 2 : 0) + ))); + const solution = solveLinear(normal, error); + return dofIds.map((_, joint) => { + const delta = jacobian.reduce((sum, row, index) => sum + row[joint] * solution[index], 0); + const value = clamp(qpos[qposIds[joint]] + clamp(delta, -config.max_joint_delta_rad, config.max_joint_delta_rad), + ctrlRange[joint][0] + config.joint_margin_rad, ctrlRange[joint][1] - config.joint_margin_rad); + if (!Number.isFinite(value)) throw new Error('Controller produced a non-finite target'); + return value; + }); +} + +export class RollingSamples { + constructor(capacity = 2048) { this.capacity = capacity; this.values = []; this.index = 0; } + add(value) { + if (!Number.isFinite(value)) return; + if (this.values.length < this.capacity) this.values.push(value); + else { this.values[this.index] = value; this.index = (this.index + 1) % this.capacity; } + } + quantile(fraction) { + if (!this.values.length) return 0; + const ordered = this.values.slice().sort((a, b) => a - b); + return ordered[Math.min(ordered.length - 1, Math.floor(fraction * (ordered.length - 1)))]; + } +} diff --git a/src/dvidia_training/workstation_worker.bundle.js b/src/dvidia_training/workstation_worker.bundle.js new file mode 100644 index 0000000..e9776af --- /dev/null +++ b/src/dvidia_training/workstation_worker.bundle.js @@ -0,0 +1,23 @@ +/* DVIDIA live workstation worker. MIT. MuJoCo 3.15.0 Apache-2.0. See workstation.third-party.txt. */ +var Tl=(async function(y={}){var h,u=y,v=typeof window=="object",m=typeof WorkerGlobalScope<"u",A=typeof process=="object"&&process.versions?.node&&process.type!="renderer",O=!v&&!A&&!m;if(A){let{createRequire:e}=await import("module");var P=e(import.meta.url)}var D=[],B="./this.program",$=(e,r)=>{throw r},W=import.meta.url,Y="";function we(e){return u.locateFile?u.locateFile(e,Y):Y+e}var re,se;if(A){if(!(typeof process=="object"&&process.versions?.node&&process.type!="renderer"))throw new Error("not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)");var xe=process.versions.node,Ee=xe.split(".").slice(0,3);if(Ee=Ee[0]*1e4+Ee[1]*100+Ee[2].split("-")[0]*1,Ee<16e4)throw new Error("This emscripten-generated code requires node v16.0.0 (detected v"+xe+")");var ie=P("fs");W.startsWith("file:")&&(Y=P("path").dirname(P("url").fileURLToPath(W))+"/"),se=r=>{r=Qe(r)?new URL(r):r;var t=ie.readFileSync(r);return T(Buffer.isBuffer(t)),t},re=async(r,t=!0)=>{r=Qe(r)?new URL(r):r;var n=ie.readFileSync(r,t?void 0:"utf8");return T(t?Buffer.isBuffer(n):typeof n=="string"),n},process.argv.length>1&&(B=process.argv[1].replace(/\\/g,"/")),D=process.argv.slice(2),$=(r,t)=>{throw process.exitCode=r,t}}else if(O){if(typeof process=="object"&&process.versions?.node&&process.type!="renderer"||typeof window=="object"||typeof WorkerGlobalScope<"u")throw new Error("not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)")}else if(v||m){try{Y=new URL(".",W).href}catch{}if(!(typeof window=="object"||typeof WorkerGlobalScope<"u"))throw new Error("not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)");m&&(se=e=>{var r=new XMLHttpRequest;return r.open("GET",e,!1),r.responseType="arraybuffer",r.send(null),new Uint8Array(r.response)}),re=async e=>{if(Qe(e))return new Promise((t,n)=>{var i=new XMLHttpRequest;i.open("GET",e,!0),i.responseType="arraybuffer",i.onload=()=>{if(i.status==200||i.status==0&&i.response){t(i.response);return}n(i.status)},i.onerror=n,i.send(null)});var r=await fetch(e,{credentials:"same-origin"});if(r.ok)return r.arrayBuffer();throw new Error(r.status+" : "+r.url)}}else throw new Error("environment detection error");var G=console.log.bind(console),x=console.error.bind(console),he="IDBFS is no longer included by default; build with -lidbfs.js",ue="PROXYFS is no longer included by default; build with -lproxyfs.js",be="WORKERFS is no longer included by default; build with -lworkerfs.js",Ae="FETCHFS is no longer included by default; build with -lfetchfs.js",ur="ICASEFS is no longer included by default; build with -licasefs.js",Bl="JSFILEFS is no longer included by default; build with -ljsfilefs.js",Wl="OPFS is no longer included by default; build with -lopfs.js",zl="NODEFS is no longer included by default; build with -lnodefs.js";T(!O,"shell environment detected but not enabled at build time. Add `shell` to `-sENVIRONMENT` to enable.");var Je;typeof WebAssembly!="object"&&x("no native wasm support detected");var Ke=!1,ct;function T(e,r){e||K("Assertion failed"+(r?": "+r:""))}var Qe=e=>e.startsWith("file://");function Cn(){var e=tt();T((e&3)==0),e==0&&(e+=4),R[e>>2]=34821223,R[e+4>>2]=2310721022,R[0]=1668509029}function jr(){if(!Ke){var e=tt();e==0&&(e+=4);var r=R[e>>2],t=R[e+4>>2];(r!=34821223||t!=2310721022)&&K(`Stack overflow! Stack cookie has been overwritten at ${ze(e)}, expected hex dwords 0x89BACDFE and 0x2135467, but received ${ze(t)} ${ze(r)}`),R[0]!=1668509029&&K("Runtime error: The application has corrupted its heap memory area (address zero)!")}}class E extends Error{}class xn extends E{}class Ir extends E{constructor(r){super(r),this.excPtr=r;let t=tn(r);this.name=t[0],this.message=t[1]}}var lt=!0;function Hl(...e){!lt&&typeof lt<"u"||console.warn(...e)}(()=>{var e=new Int16Array(1),r=new Int8Array(e.buffer);if(e[0]=25459,r[0]!==115||r[1]!==99)throw"Runtime error: expected the system to be little-endian! (Run with -sSUPPORT_BIG_ENDIAN to bypass)"})();function dr(e){Object.getOwnPropertyDescriptor(u,e)||Object.defineProperty(u,e,{configurable:!0,set(){K(`Attempt to set \`Module.${e}\` after it has already been processed. This can happen, for example, when code is injected via '--post-js' rather than '--pre-js'`)}})}function J(e){return()=>T(!1,`call to '${e}' via reference taken before Wasm module initialization`)}function Mn(e){Object.getOwnPropertyDescriptor(u,e)&&K(`\`Module.${e}\` was supplied but \`${e}\` not included in INCOMING_MODULE_JS_API`)}function ut(e){return e==="FS_createPath"||e==="FS_createDataFile"||e==="FS_createPreloadedFile"||e==="FS_unlink"||e==="addRunDependency"||e==="FS_createLazyFile"||e==="FS_createDevice"||e==="removeRunDependency"}function dt(e,r){typeof globalThis<"u"&&!Object.getOwnPropertyDescriptor(globalThis,e)&&Object.defineProperty(globalThis,e,{configurable:!0,get(){r()}})}function ft(e,r){dt(e,()=>{Pe(`\`${e}\` is not longer defined by emscripten. ${r}`)})}ft("buffer","Please use HEAP8.buffer or wasmMemory.buffer"),ft("asm","Please use wasmExports instead");function $n(e){dt(e,()=>{var r=`\`${e}\` is a library symbol and not included by default; add it to your library.js __deps or to DEFAULT_LIBRARY_FUNCS_TO_INCLUDE on the command line`,t=e;t.startsWith("_")||(t="$"+e),r+=` (e.g. -sDEFAULT_LIBRARY_FUNCS_TO_INCLUDE='${t}')`,ut(e)&&(r+=". Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you"),Pe(r)}),ht(e)}function ht(e){Object.getOwnPropertyDescriptor(u,e)||Object.defineProperty(u,e,{configurable:!0,get(){var r=`'${e}' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the Emscripten FAQ)`;ut(e)&&(r+=". Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you"),K(r)}})}var vt,Nr,Ze,X,ae,pe,Me,C,R,fr,er,de,_t,rr=!1;function pt(){var e=Ze.buffer;X=new Int8Array(e),pe=new Int16Array(e),ae=new Uint8Array(e),Me=new Uint16Array(e),C=new Int32Array(e),R=new Uint32Array(e),fr=new Float32Array(e),er=new Float64Array(e),de=new BigInt64Array(e),_t=new BigUint64Array(e)}T(typeof Int32Array<"u"&&typeof Float64Array<"u"&&Int32Array.prototype.subarray!=null&&Int32Array.prototype.set!=null,"JS engine does not provide full typed array support");function Rn(){if(u.preRun)for(typeof u.preRun=="function"&&(u.preRun=[u.preRun]);u.preRun.length;)Vn(u.preRun.shift());dr("preRun"),mt(yt)}function On(){T(!rr),rr=!0,jr(),!u.noFSInit&&!a.initialized&&a.init(),Te.init(),Ne.__wasm_call_ctors(),a.ignorePermissions=!1}function Dn(){if(jr(),u.postRun)for(typeof u.postRun=="function"&&(u.postRun=[u.postRun]);u.postRun.length;)Hn(u.postRun.shift());dr("postRun"),mt(gt)}var $e=0,tr=null,We={},Re=null;function Lr(e){$e++,u.monitorRunDependencies?.($e),e?(T(!We[e]),We[e]=1,Re===null&&typeof setInterval<"u"&&(Re=setInterval(()=>{if(Ke){clearInterval(Re),Re=null;return}var r=!1;for(var t in We)r||(r=!0,x("still waiting on run dependencies:")),x(`dependency: ${t}`);r&&x("(end of list)")},1e4))):x("warning: run dependency added without ID")}function hr(e){if($e--,u.monitorRunDependencies?.($e),e?(T(We[e]),delete We[e]):x("warning: run dependency removed without ID"),$e==0&&(Re!==null&&(clearInterval(Re),Re=null),tr)){var r=tr;tr=null,r()}}function K(e){u.onAbort?.(e),e="Aborted("+e+")",x(e),Ke=!0;var r=new WebAssembly.RuntimeError(e);throw Nr?.(r),r}function ce(e,r){return(...t)=>{T(rr,`native function \`${e}\` called before runtime initialization`);var n=Ne[e];return T(n,`exported native function \`${e}\` not found`),T(t.length<=r,`native function \`${e}\` called with ${t.length} args but expects ${r}`),n(...t)}}var nr;function jn(){return u.locateFile?we("mujoco.wasm"):new URL("mujoco.wasm",import.meta.url).href}function In(e){if(e==nr&&Je)return new Uint8Array(Je);if(se)return se(e);throw"both async and sync fetching of the wasm failed"}async function Nn(e){if(!Je)try{var r=await re(e);return new Uint8Array(r)}catch{}return In(e)}async function Ln(e,r){try{var t=await Nn(e),n=await WebAssembly.instantiate(t,r);return n}catch(i){x(`failed to asynchronously prepare wasm: ${i}`),Qe(nr)&&x(`warning: Loading from a file URI (${nr}) is not supported in most browsers. See https://emscripten.org/docs/getting_started/FAQ.html#how-do-i-run-a-local-webserver-for-testing-why-does-my-program-stall-in-downloading-or-preparing`),K(i)}}async function Un(e,r,t){if(!e&&typeof WebAssembly.instantiateStreaming=="function"&&!Qe(r)&&!A)try{var n=fetch(r,{credentials:"same-origin"}),i=await WebAssembly.instantiateStreaming(n,t);return i}catch(o){x(`wasm streaming compile failed: ${o}`),x("falling back to ArrayBuffer instantiation")}return Ln(r,t)}function Bn(){return{env:_n,wasi_snapshot_preview1:_n}}async function Wn(){function e(s,c){return Ne=s.exports,Ze=Ne.memory,T(Ze,"memory not found in wasm exports"),pt(),Ar=Ne.__indirect_function_table,T(Ar,"table not found in wasm exports"),Pa(Ne),hr("wasm-instantiate"),Ne}Lr("wasm-instantiate");var r=u;function t(s){return T(u===r,"the Module object should not be replaced during async compilation - perhaps the order of HTML elements is wrong?"),r=null,e(s.instance)}var n=Bn();if(u.instantiateWasm)return new Promise((s,c)=>{try{u.instantiateWasm(n,(l,d)=>{s(e(l,d))})}catch(l){x(`Module.instantiateWasm callback failed with error: ${l}`),c(l)}});nr??=jn();var i=await Un(Je,nr,n),o=t(i);return o}class zn{name="ExitStatus";constructor(r){this.message=`Program terminated with exit(${r})`,this.status=r}}var mt=e=>{for(;e.length>0;)e.shift()(u)},gt=[],Hn=e=>gt.push(e),yt=[],Vn=e=>yt.push(e);function Vl(e,r="i8"){switch(r.endsWith("*")&&(r="*"),r){case"i1":return X[e];case"i8":return X[e];case"i16":return pe[e>>1];case"i32":return C[e>>2];case"i64":return de[e>>3];case"float":return fr[e>>2];case"double":return er[e>>3];case"*":return R[e>>2];default:K(`invalid type for getValue: ${r}`)}}var wt=!0,ze=e=>(T(typeof e=="number"),e>>>=0,"0x"+e.toString(16).padStart(8,"0"));function Gl(e,r,t="i8"){switch(t.endsWith("*")&&(t="*"),t){case"i1":X[e]=r;break;case"i8":X[e]=r;break;case"i16":pe[e>>1]=r;break;case"i32":C[e>>2]=r;break;case"i64":de[e>>3]=BigInt(r);break;case"float":fr[e>>2]=r;break;case"double":er[e>>3]=r;break;case"*":R[e>>2]=r;break;default:K(`invalid type for setValue: ${t}`)}}var b=e=>ln(e),S=()=>dn(),Pe=e=>{Pe.shown||={},Pe.shown[e]||(Pe.shown[e]=1,A&&(e="warning: "+e),x(e))},Et=typeof TextDecoder<"u"?new TextDecoder:void 0,He=(e,r=0,t=NaN)=>{for(var n=r+t,i=r;e[i]&&!(i>=n);)++i;if(i-r>16&&e.buffer&&Et)return Et.decode(e.subarray(r,i));for(var o="";r>10,56320|d&1023)}}return o},Se=(e,r)=>(T(typeof e=="number",`UTF8ToString expects a number (got ${typeof e})`),e?He(ae,e,r):""),Gn=(e,r,t,n)=>K(`Assertion failed: ${Se(e)}, at: `+[r?Se(r):"unknown filename",t,n?Se(n):"unknown function"]),ke=[],vr=0,qn=e=>{var r=new _r(e);return r.get_caught()||(r.set_caught(!0),vr--),r.set_rethrown(!1),ke.push(r),Rr(e),vn(e)},Yn=()=>{if(!ke.length)return 0;var e=ke[ke.length-1];return Rr(e.excPtr),e.excPtr},Fe=0,Xn=()=>{k(0,0),T(ke.length>0);var e=ke.pop();nt(e.excPtr),Fe=0};class _r{constructor(r){this.excPtr=r,this.ptr=r-24}set_type(r){R[this.ptr+4>>2]=r}get_type(){return R[this.ptr+4>>2]}set_destructor(r){R[this.ptr+8>>2]=r}get_destructor(){return R[this.ptr+8>>2]}set_caught(r){r=r?1:0,X[this.ptr+12]=r}get_caught(){return X[this.ptr+12]!=0}set_rethrown(r){r=r?1:0,X[this.ptr+13]=r}get_rethrown(){return X[this.ptr+13]!=0}init(r,t){this.set_adjusted_ptr(0),this.set_type(r),this.set_destructor(t)}set_adjusted_ptr(r){R[this.ptr+16>>2]=r}get_adjusted_ptr(){return R[this.ptr+16>>2]}}var pr=e=>sn(e),Ur=e=>{var r=Fe?.excPtr;if(!r)return pr(0),0;var t=new _r(r);t.set_adjusted_ptr(r);var n=t.get_type();if(!n)return pr(0),r;for(var i of e){if(i===0||i===n)break;var o=t.ptr+16;if(hn(i,n,o))return pr(i),r}return pr(n),r},Jn=()=>Ur([]),Kn=e=>Ur([e]),Qn=(e,r)=>Ur([e,r]),bt=()=>{var e=ke.pop();e||K("no exception to throw");var r=e.excPtr;throw e.get_rethrown()||(ke.push(e),e.set_rethrown(!0),e.set_caught(!1),vr++),Fe=new Ir(r),Fe},Zn=e=>{if(e){var r=new _r(e);ke.push(r),r.set_rethrown(!0),bt()}},ei=(e,r,t)=>{var n=new _r(e);throw n.init(r,t),Fe=new Ir(e),vr++,Fe},ri=()=>vr,ti=e=>{throw Fe||(Fe=new Ir(e)),Fe},z={isAbs:e=>e.charAt(0)==="/",splitPath:e=>{var r=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return r.exec(e).slice(1)},normalizeArray:(e,r)=>{for(var t=0,n=e.length-1;n>=0;n--){var i=e[n];i==="."?e.splice(n,1):i===".."?(e.splice(n,1),t++):t&&(e.splice(n,1),t--)}if(r)for(;t;t--)e.unshift("..");return e},normalize:e=>{var r=z.isAbs(e),t=e.slice(-1)==="/";return e=z.normalizeArray(e.split("/").filter(n=>!!n),!r).join("/"),!e&&!r&&(e="."),e&&t&&(e+="/"),(r?"/":"")+e},dirname:e=>{var r=z.splitPath(e),t=r[0],n=r[1];return!t&&!n?".":(n&&(n=n.slice(0,-1)),t+n)},basename:e=>e&&e.match(/([^\/]+|\/)\/*$/)[1],join:(...e)=>z.normalize(e.join("/")),join2:(e,r)=>z.normalize(e+"/"+r)},ni=()=>{if(A){var e=P("crypto");return r=>e.randomFillSync(r)}return r=>crypto.getRandomValues(r)},St=e=>{(St=ni())(e)},Ve={resolve:(...e)=>{for(var r="",t=!1,n=e.length-1;n>=-1&&!t;n--){var i=n>=0?e[n]:a.cwd();if(typeof i!="string")throw new TypeError("Arguments to path.resolve must be strings");if(!i)return"";r=i+"/"+r,t=z.isAbs(i)}return r=z.normalizeArray(r.split("/").filter(o=>!!o),!t).join("/"),(t?"/":"")+r||"."},relative:(e,r)=>{e=Ve.resolve(e).slice(1),r=Ve.resolve(r).slice(1);function t(d){for(var f=0;f=0&&d[_]==="";_--);return f>_?[]:d.slice(f,_-f+1)}for(var n=t(e.split("/")),i=t(r.split("/")),o=Math.min(n.length,i.length),s=o,c=0;c{for(var r=0,t=0;t=55296&&n<=57343?(r+=4,++t):r+=3}return r},kt=(e,r,t,n)=>{if(T(typeof e=="string",`stringToUTF8Array expects a string (got ${typeof e})`),!(n>0))return 0;for(var i=t,o=t+n-1,s=0;s=o)break;r[t++]=c}else if(c<=2047){if(t+1>=o)break;r[t++]=192|c>>6,r[t++]=128|c&63}else if(c<=65535){if(t+2>=o)break;r[t++]=224|c>>12,r[t++]=128|c>>6&63,r[t++]=128|c&63}else{if(t+3>=o)break;c>1114111&&Pe("Invalid Unicode code point "+ze(c)+" encountered when serializing a JS string to a UTF-8 string in wasm memory! (Valid unicode code points should be in range 0-0x10FFFF)."),r[t++]=240|c>>18,r[t++]=128|c>>12&63,r[t++]=128|c>>6&63,r[t++]=128|c&63,s++}}return r[t]=0,t-i},Wr=(e,r,t)=>{var n=t>0?t:Ge(e)+1,i=new Array(n),o=kt(e,i,0,i.length);return r&&(i.length=o),i},ii=()=>{if(!Br.length){var e=null;if(A){var r=256,t=Buffer.alloc(r),n=0,i=process.stdin.fd;try{n=ie.readSync(i,t,0,r)}catch(o){if(o.toString().includes("EOF"))n=0;else throw o}n>0&&(e=t.slice(0,n).toString("utf-8"))}else typeof window<"u"&&typeof window.prompt=="function"&&(e=window.prompt("Input: "),e!==null&&(e+=` +`));if(!e)return null;Br=Wr(e,!0)}return Br.shift()},Te={ttys:[],init(){},shutdown(){},register(e,r){Te.ttys[e]={input:[],output:[],ops:r},a.registerDevice(e,Te.stream_ops)},stream_ops:{open(e){var r=Te.ttys[e.node.rdev];if(!r)throw new a.ErrnoError(43);e.tty=r,e.seekable=!1},close(e){e.tty.ops.fsync(e.tty)},fsync(e){e.tty.ops.fsync(e.tty)},read(e,r,t,n,i){if(!e.tty||!e.tty.ops.get_char)throw new a.ErrnoError(60);for(var o=0,s=0;s0&&(G(He(e.output)),e.output=[])},ioctl_tcgets(e){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets(e,r,t){return 0},ioctl_tiocgwinsz(e){return[24,80]}},default_tty1_ops:{put_char(e,r){r===null||r===10?(x(He(e.output)),e.output=[]):r!=0&&e.output.push(r)},fsync(e){e.output?.length>0&&(x(He(e.output)),e.output=[])}}},Ft=e=>{K("internal error: mmapAlloc called but `emscripten_builtin_memalign` native symbol not exported")},j={ops_table:null,mount(e){return j.createNode(null,"/",16895,0)},createNode(e,r,t,n){if(a.isBlkdev(t)||a.isFIFO(t))throw new a.ErrnoError(63);j.ops_table||={dir:{node:{getattr:j.node_ops.getattr,setattr:j.node_ops.setattr,lookup:j.node_ops.lookup,mknod:j.node_ops.mknod,rename:j.node_ops.rename,unlink:j.node_ops.unlink,rmdir:j.node_ops.rmdir,readdir:j.node_ops.readdir,symlink:j.node_ops.symlink},stream:{llseek:j.stream_ops.llseek}},file:{node:{getattr:j.node_ops.getattr,setattr:j.node_ops.setattr},stream:{llseek:j.stream_ops.llseek,read:j.stream_ops.read,write:j.stream_ops.write,mmap:j.stream_ops.mmap,msync:j.stream_ops.msync}},link:{node:{getattr:j.node_ops.getattr,setattr:j.node_ops.setattr,readlink:j.node_ops.readlink},stream:{}},chrdev:{node:{getattr:j.node_ops.getattr,setattr:j.node_ops.setattr},stream:a.chrdev_stream_ops}};var i=a.createNode(e,r,t,n);return a.isDir(i.mode)?(i.node_ops=j.ops_table.dir.node,i.stream_ops=j.ops_table.dir.stream,i.contents={}):a.isFile(i.mode)?(i.node_ops=j.ops_table.file.node,i.stream_ops=j.ops_table.file.stream,i.usedBytes=0,i.contents=null):a.isLink(i.mode)?(i.node_ops=j.ops_table.link.node,i.stream_ops=j.ops_table.link.stream):a.isChrdev(i.mode)&&(i.node_ops=j.ops_table.chrdev.node,i.stream_ops=j.ops_table.chrdev.stream),i.atime=i.mtime=i.ctime=Date.now(),e&&(e.contents[r]=i,e.atime=e.mtime=e.ctime=i.atime),i},getFileDataAsTypedArray(e){return e.contents?e.contents.subarray?e.contents.subarray(0,e.usedBytes):new Uint8Array(e.contents):new Uint8Array(0)},expandFileStorage(e,r){var t=e.contents?e.contents.length:0;if(!(t>=r)){var n=1024*1024;r=Math.max(r,t*(t>>0),t!=0&&(r=Math.max(r,256));var i=e.contents;e.contents=new Uint8Array(r),e.usedBytes>0&&e.contents.set(i.subarray(0,e.usedBytes),0)}},resizeFileStorage(e,r){if(e.usedBytes!=r)if(r==0)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(e){var r={};return r.dev=a.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,a.isDir(e.mode)?r.size=4096:a.isFile(e.mode)?r.size=e.usedBytes:a.isLink(e.mode)?r.size=e.link.length:r.size=0,r.atime=new Date(e.atime),r.mtime=new Date(e.mtime),r.ctime=new Date(e.ctime),r.blksize=4096,r.blocks=Math.ceil(r.size/r.blksize),r},setattr(e,r){for(let t of["mode","atime","mtime","ctime"])r[t]!=null&&(e[t]=r[t]);r.size!==void 0&&j.resizeFileStorage(e,r.size)},lookup(e,r){throw new a.ErrnoError(44)},mknod(e,r,t,n){return j.createNode(e,r,t,n)},rename(e,r,t){var n;try{n=a.lookupNode(r,t)}catch{}if(n){if(a.isDir(e.mode))for(var i in n.contents)throw new a.ErrnoError(55);a.hashRemoveNode(n)}delete e.parent.contents[e.name],r.contents[t]=e,e.name=t,r.ctime=r.mtime=e.parent.ctime=e.parent.mtime=Date.now()},unlink(e,r){delete e.contents[r],e.ctime=e.mtime=Date.now()},rmdir(e,r){var t=a.lookupNode(e,r);for(var n in t.contents)throw new a.ErrnoError(55);delete e.contents[r],e.ctime=e.mtime=Date.now()},readdir(e){return[".","..",...Object.keys(e.contents)]},symlink(e,r,t){var n=j.createNode(e,r,41471,0);return n.link=t,n},readlink(e){if(!a.isLink(e.mode))throw new a.ErrnoError(28);return e.link}},stream_ops:{read(e,r,t,n,i){var o=e.node.contents;if(i>=e.node.usedBytes)return 0;var s=Math.min(e.node.usedBytes-i,n);if(T(s>=0),s>8&&o.subarray)r.set(o.subarray(i,i+s),t);else for(var c=0;c0||t+r{var r=await re(e);return T(r,`Loading data file "${e}" failed (no arrayBuffer).`),new Uint8Array(r)},Tt=(...e)=>a.createDataFile(...e),ai=e=>{for(var r=e;;){if(!We[e])return e;e=r+Math.random()}},At=[],si=(e,r,t,n)=>{typeof Browser<"u"&&Browser.init();var i=!1;return At.forEach(o=>{i||o.canHandle(r)&&(o.handle(e,r,t,n),i=!0)}),i},Pt=(e,r,t,n,i,o,s,c,l,d)=>{var f=r?Ve.resolve(z.join2(e,r)):e,_=ai(`cp ${f}`);function g(p){function w(M){d?.(),c||Tt(e,r,M,n,i,l),o?.(),hr(_)}si(p,f,w,()=>{s?.(),hr(_)})||w(p)}Lr(_),typeof t=="string"?oi(t).then(g,s):g(t)},ci=e=>{var r={r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090},t=r[e];if(typeof t>"u")throw new Error(`Unknown file open mode: ${e}`);return t},zr=(e,r)=>{var t=0;return e&&(t|=365),r&&(t|=146),t},li=e=>Se(an(e)),Ct={EPERM:63,ENOENT:44,ESRCH:71,EINTR:27,EIO:29,ENXIO:60,E2BIG:1,ENOEXEC:45,EBADF:8,ECHILD:12,EAGAIN:6,EWOULDBLOCK:6,ENOMEM:48,EACCES:2,EFAULT:21,ENOTBLK:105,EBUSY:10,EEXIST:20,EXDEV:75,ENODEV:43,ENOTDIR:54,EISDIR:31,EINVAL:28,ENFILE:41,EMFILE:33,ENOTTY:59,ETXTBSY:74,EFBIG:22,ENOSPC:51,ESPIPE:70,EROFS:69,EMLINK:34,EPIPE:64,EDOM:18,ERANGE:68,ENOMSG:49,EIDRM:24,ECHRNG:106,EL2NSYNC:156,EL3HLT:107,EL3RST:108,ELNRNG:109,EUNATCH:110,ENOCSI:111,EL2HLT:112,EDEADLK:16,ENOLCK:46,EBADE:113,EBADR:114,EXFULL:115,ENOANO:104,EBADRQC:103,EBADSLT:102,EDEADLOCK:16,EBFONT:101,ENOSTR:100,ENODATA:116,ETIME:117,ENOSR:118,ENONET:119,ENOPKG:120,EREMOTE:121,ENOLINK:47,EADV:122,ESRMNT:123,ECOMM:124,EPROTO:65,EMULTIHOP:36,EDOTDOT:125,EBADMSG:9,ENOTUNIQ:126,EBADFD:127,EREMCHG:128,ELIBACC:129,ELIBBAD:130,ELIBSCN:131,ELIBMAX:132,ELIBEXEC:133,ENOSYS:52,ENOTEMPTY:55,ENAMETOOLONG:37,ELOOP:32,EOPNOTSUPP:138,EPFNOSUPPORT:139,ECONNRESET:15,ENOBUFS:42,EAFNOSUPPORT:5,EPROTOTYPE:67,ENOTSOCK:57,ENOPROTOOPT:50,ESHUTDOWN:140,ECONNREFUSED:14,EADDRINUSE:3,ECONNABORTED:13,ENETUNREACH:40,ENETDOWN:38,ETIMEDOUT:73,EHOSTDOWN:142,EHOSTUNREACH:23,EINPROGRESS:26,EALREADY:7,EDESTADDRREQ:17,EMSGSIZE:35,EPROTONOSUPPORT:66,ESOCKTNOSUPPORT:137,EADDRNOTAVAIL:4,ENETRESET:39,EISCONN:30,ENOTCONN:53,ETOOMANYREFS:141,EUSERS:136,EDQUOT:19,ESTALE:72,ENOTSUP:138,ENOMEDIUM:148,EILSEQ:25,EOVERFLOW:61,ECANCELED:11,ENOTRECOVERABLE:56,EOWNERDEAD:62,ESTRPIPE:135},a={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:!1,ignorePermissions:!0,filesystems:null,syncFSRequests:0,readFiles:{},ErrnoError:class extends Error{name="ErrnoError";constructor(e){super(rr?li(e):""),this.errno=e;for(var r in Ct)if(Ct[r]===e){this.code=r;break}}},FSStream:class{shared={};get object(){return this.node}set object(e){this.node=e}get isRead(){return(this.flags&2097155)!==1}get isWrite(){return(this.flags&2097155)!==0}get isAppend(){return this.flags&1024}get flags(){return this.shared.flags}set flags(e){this.shared.flags=e}get position(){return this.shared.position}set position(e){this.shared.position=e}},FSNode:class{node_ops={};stream_ops={};readMode=365;writeMode=146;mounted=null;constructor(e,r,t,n){e||(e=this),this.parent=e,this.mount=e.mount,this.id=a.nextInode++,this.name=r,this.mode=t,this.rdev=n,this.atime=this.mtime=this.ctime=Date.now()}get read(){return(this.mode&this.readMode)===this.readMode}set read(e){e?this.mode|=this.readMode:this.mode&=~this.readMode}get write(){return(this.mode&this.writeMode)===this.writeMode}set write(e){e?this.mode|=this.writeMode:this.mode&=~this.writeMode}get isFolder(){return a.isDir(this.mode)}get isDevice(){return a.isChrdev(this.mode)}},lookupPath(e,r={}){if(!e)throw new a.ErrnoError(44);r.follow_mount??=!0,z.isAbs(e)||(e=a.cwd()+"/"+e);e:for(var t=0;t<40;t++){for(var n=e.split("/").filter(d=>!!d),i=a.root,o="/",s=0;s>>0)%a.nameTable.length},hashAddNode(e){var r=a.hashName(e.parent.id,e.name);e.name_next=a.nameTable[r],a.nameTable[r]=e},hashRemoveNode(e){var r=a.hashName(e.parent.id,e.name);if(a.nameTable[r]===e)a.nameTable[r]=e.name_next;else for(var t=a.nameTable[r];t;){if(t.name_next===e){t.name_next=e.name_next;break}t=t.name_next}},lookupNode(e,r){var t=a.mayLookup(e);if(t)throw new a.ErrnoError(t);for(var n=a.hashName(e.id,r),i=a.nameTable[n];i;i=i.name_next){var o=i.name;if(i.parent.id===e.id&&o===r)return i}return a.lookup(e,r)},createNode(e,r,t,n){T(typeof e=="object");var i=new a.FSNode(e,r,t,n);return a.hashAddNode(i),i},destroyNode(e){a.hashRemoveNode(e)},isRoot(e){return e===e.parent},isMountpoint(e){return!!e.mounted},isFile(e){return(e&61440)===32768},isDir(e){return(e&61440)===16384},isLink(e){return(e&61440)===40960},isChrdev(e){return(e&61440)===8192},isBlkdev(e){return(e&61440)===24576},isFIFO(e){return(e&61440)===4096},isSocket(e){return(e&49152)===49152},flagsToPermissionString(e){var r=["r","w","rw"][e&3];return e&512&&(r+="w"),r},nodePermissions(e,r){return a.ignorePermissions?0:r.includes("r")&&!(e.mode&292)||r.includes("w")&&!(e.mode&146)||r.includes("x")&&!(e.mode&73)?2:0},mayLookup(e){if(!a.isDir(e.mode))return 54;var r=a.nodePermissions(e,"x");return r||(e.node_ops.lookup?0:2)},mayCreate(e,r){if(!a.isDir(e.mode))return 54;try{var t=a.lookupNode(e,r);return 20}catch{}return a.nodePermissions(e,"wx")},mayDelete(e,r,t){var n;try{n=a.lookupNode(e,r)}catch(o){return o.errno}var i=a.nodePermissions(e,"wx");if(i)return i;if(t){if(!a.isDir(n.mode))return 54;if(a.isRoot(n)||a.getPath(n)===a.cwd())return 10}else if(a.isDir(n.mode))return 31;return 0},mayOpen(e,r){return e?a.isLink(e.mode)?32:a.isDir(e.mode)&&(a.flagsToPermissionString(r)!=="r"||r&576)?31:a.nodePermissions(e,a.flagsToPermissionString(r)):44},checkOpExists(e,r){if(!e)throw new a.ErrnoError(r);return e},MAX_OPEN_FDS:4096,nextfd(){for(var e=0;e<=a.MAX_OPEN_FDS;e++)if(!a.streams[e])return e;throw new a.ErrnoError(33)},getStreamChecked(e){var r=a.getStream(e);if(!r)throw new a.ErrnoError(8);return r},getStream:e=>a.streams[e],createStream(e,r=-1){return T(r>=-1),e=Object.assign(new a.FSStream,e),r==-1&&(r=a.nextfd()),e.fd=r,a.streams[r]=e,e},closeStream(e){a.streams[e]=null},dupStream(e,r=-1){var t=a.createStream(e,r);return t.stream_ops?.dup?.(t),t},doSetAttr(e,r,t){var n=e?.stream_ops.setattr,i=n?e:r;n??=r.node_ops.setattr,a.checkOpExists(n,63),n(i,t)},chrdev_stream_ops:{open(e){var r=a.getDevice(e.node.rdev);e.stream_ops=r.stream_ops,e.stream_ops.open?.(e)},llseek(){throw new a.ErrnoError(70)}},major:e=>e>>8,minor:e=>e&255,makedev:(e,r)=>e<<8|r,registerDevice(e,r){a.devices[e]={stream_ops:r}},getDevice:e=>a.devices[e],getMounts(e){for(var r=[],t=[e];t.length;){var n=t.pop();r.push(n),t.push(...n.mounts)}return r},syncfs(e,r){typeof e=="function"&&(r=e,e=!1),a.syncFSRequests++,a.syncFSRequests>1&&x(`warning: ${a.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`);var t=a.getMounts(a.root.mount),n=0;function i(s){return T(a.syncFSRequests>0),a.syncFSRequests--,r(s)}function o(s){if(s)return o.errored?void 0:(o.errored=!0,i(s));++n>=t.length&&i(null)}t.forEach(s=>{if(!s.type.syncfs)return o(null);s.type.syncfs(s,e,o)})},mount(e,r,t){if(typeof e=="string")throw e;var n=t==="/",i=!t,o;if(n&&a.root)throw new a.ErrnoError(10);if(!n&&!i){var s=a.lookupPath(t,{follow_mount:!1});if(t=s.path,o=s.node,a.isMountpoint(o))throw new a.ErrnoError(10);if(!a.isDir(o.mode))throw new a.ErrnoError(54)}var c={type:e,opts:r,mountpoint:t,mounts:[]},l=e.mount(c);return l.mount=c,c.root=l,n?a.root=l:o&&(o.mounted=c,o.mount&&o.mount.mounts.push(c)),l},unmount(e){var r=a.lookupPath(e,{follow_mount:!1});if(!a.isMountpoint(r.node))throw new a.ErrnoError(28);var t=r.node,n=t.mounted,i=a.getMounts(n);Object.keys(a.nameTable).forEach(s=>{for(var c=a.nameTable[s];c;){var l=c.name_next;i.includes(c.mount)&&a.destroyNode(c),c=l}}),t.mounted=null;var o=t.mount.mounts.indexOf(n);T(o!==-1),t.mount.mounts.splice(o,1)},lookup(e,r){return e.node_ops.lookup(e,r)},mknod(e,r,t){var n=a.lookupPath(e,{parent:!0}),i=n.node,o=z.basename(e);if(!o)throw new a.ErrnoError(28);if(o==="."||o==="..")throw new a.ErrnoError(20);var s=a.mayCreate(i,o);if(s)throw new a.ErrnoError(s);if(!i.node_ops.mknod)throw new a.ErrnoError(63);return i.node_ops.mknod(i,o,r,t)},statfs(e){return a.statfsNode(a.lookupPath(e,{follow:!0}).node)},statfsStream(e){return a.statfsNode(e.node)},statfsNode(e){var r={bsize:4096,frsize:4096,blocks:1e6,bfree:5e5,bavail:5e5,files:a.nextInode,ffree:a.nextInode-1,fsid:42,flags:2,namelen:255};return e.node_ops.statfs&&Object.assign(r,e.node_ops.statfs(e.mount.opts.root)),r},create(e,r=438){return r&=4095,r|=32768,a.mknod(e,r,0)},mkdir(e,r=511){return r&=1023,r|=16384,a.mknod(e,r,0)},mkdirTree(e,r){var t=e.split("/"),n="";for(var i of t)if(i){(n||z.isAbs(e))&&(n+="/"),n+=i;try{a.mkdir(n,r)}catch(o){if(o.errno!=20)throw o}}},mkdev(e,r,t){return typeof t>"u"&&(t=r,r=438),r|=8192,a.mknod(e,r,t)},symlink(e,r){if(!Ve.resolve(e))throw new a.ErrnoError(44);var t=a.lookupPath(r,{parent:!0}),n=t.node;if(!n)throw new a.ErrnoError(44);var i=z.basename(r),o=a.mayCreate(n,i);if(o)throw new a.ErrnoError(o);if(!n.node_ops.symlink)throw new a.ErrnoError(63);return n.node_ops.symlink(n,i,e)},rename(e,r){var t=z.dirname(e),n=z.dirname(r),i=z.basename(e),o=z.basename(r),s,c,l;if(s=a.lookupPath(e,{parent:!0}),c=s.node,s=a.lookupPath(r,{parent:!0}),l=s.node,!c||!l)throw new a.ErrnoError(44);if(c.mount!==l.mount)throw new a.ErrnoError(75);var d=a.lookupNode(c,i),f=Ve.relative(e,n);if(f.charAt(0)!==".")throw new a.ErrnoError(28);if(f=Ve.relative(r,t),f.charAt(0)!==".")throw new a.ErrnoError(55);var _;try{_=a.lookupNode(l,o)}catch{}if(d!==_){var g=a.isDir(d.mode),p=a.mayDelete(c,i,g);if(p)throw new a.ErrnoError(p);if(p=_?a.mayDelete(l,o,g):a.mayCreate(l,o),p)throw new a.ErrnoError(p);if(!c.node_ops.rename)throw new a.ErrnoError(63);if(a.isMountpoint(d)||_&&a.isMountpoint(_))throw new a.ErrnoError(10);if(l!==c&&(p=a.nodePermissions(c,"w"),p))throw new a.ErrnoError(p);a.hashRemoveNode(d);try{c.node_ops.rename(d,l,o),d.parent=l}catch(w){throw w}finally{a.hashAddNode(d)}}},rmdir(e){var r=a.lookupPath(e,{parent:!0}),t=r.node,n=z.basename(e),i=a.lookupNode(t,n),o=a.mayDelete(t,n,!0);if(o)throw new a.ErrnoError(o);if(!t.node_ops.rmdir)throw new a.ErrnoError(63);if(a.isMountpoint(i))throw new a.ErrnoError(10);t.node_ops.rmdir(t,n),a.destroyNode(i)},readdir(e){var r=a.lookupPath(e,{follow:!0}),t=r.node,n=a.checkOpExists(t.node_ops.readdir,54);return n(t)},unlink(e){var r=a.lookupPath(e,{parent:!0}),t=r.node;if(!t)throw new a.ErrnoError(44);var n=z.basename(e),i=a.lookupNode(t,n),o=a.mayDelete(t,n,!1);if(o)throw new a.ErrnoError(o);if(!t.node_ops.unlink)throw new a.ErrnoError(63);if(a.isMountpoint(i))throw new a.ErrnoError(10);t.node_ops.unlink(t,n),a.destroyNode(i)},readlink(e){var r=a.lookupPath(e),t=r.node;if(!t)throw new a.ErrnoError(44);if(!t.node_ops.readlink)throw new a.ErrnoError(28);return t.node_ops.readlink(t)},stat(e,r){var t=a.lookupPath(e,{follow:!r}),n=t.node,i=a.checkOpExists(n.node_ops.getattr,63);return i(n)},fstat(e){var r=a.getStreamChecked(e),t=r.node,n=r.stream_ops.getattr,i=n?r:t;return n??=t.node_ops.getattr,a.checkOpExists(n,63),n(i)},lstat(e){return a.stat(e,!0)},doChmod(e,r,t,n){a.doSetAttr(e,r,{mode:t&4095|r.mode&-4096,ctime:Date.now(),dontFollow:n})},chmod(e,r,t){var n;if(typeof e=="string"){var i=a.lookupPath(e,{follow:!t});n=i.node}else n=e;a.doChmod(null,n,r,t)},lchmod(e,r){a.chmod(e,r,!0)},fchmod(e,r){var t=a.getStreamChecked(e);a.doChmod(t,t.node,r,!1)},doChown(e,r,t){a.doSetAttr(e,r,{timestamp:Date.now(),dontFollow:t})},chown(e,r,t,n){var i;if(typeof e=="string"){var o=a.lookupPath(e,{follow:!n});i=o.node}else i=e;a.doChown(null,i,n)},lchown(e,r,t){a.chown(e,r,t,!0)},fchown(e,r,t){var n=a.getStreamChecked(e);a.doChown(n,n.node,!1)},doTruncate(e,r,t){if(a.isDir(r.mode))throw new a.ErrnoError(31);if(!a.isFile(r.mode))throw new a.ErrnoError(28);var n=a.nodePermissions(r,"w");if(n)throw new a.ErrnoError(n);a.doSetAttr(e,r,{size:t,timestamp:Date.now()})},truncate(e,r){if(r<0)throw new a.ErrnoError(28);var t;if(typeof e=="string"){var n=a.lookupPath(e,{follow:!0});t=n.node}else t=e;a.doTruncate(null,t,r)},ftruncate(e,r){var t=a.getStreamChecked(e);if(r<0||(t.flags&2097155)===0)throw new a.ErrnoError(28);a.doTruncate(t,t.node,r)},utime(e,r,t){var n=a.lookupPath(e,{follow:!0}),i=n.node,o=a.checkOpExists(i.node_ops.setattr,63);o(i,{atime:r,mtime:t})},open(e,r,t=438){if(e==="")throw new a.ErrnoError(44);r=typeof r=="string"?ci(r):r,r&64?t=t&4095|32768:t=0;var n,i;if(typeof e=="object")n=e;else{i=e.endsWith("/");var o=a.lookupPath(e,{follow:!(r&131072),noent_okay:!0});n=o.node,e=o.path}var s=!1;if(r&64)if(n){if(r&128)throw new a.ErrnoError(20)}else{if(i)throw new a.ErrnoError(31);n=a.mknod(e,t|511,0),s=!0}if(!n)throw new a.ErrnoError(44);if(a.isChrdev(n.mode)&&(r&=-513),r&65536&&!a.isDir(n.mode))throw new a.ErrnoError(54);if(!s){var c=a.mayOpen(n,r);if(c)throw new a.ErrnoError(c)}r&512&&!s&&a.truncate(n,0),r&=-131713;var l=a.createStream({node:n,path:a.getPath(n),flags:r,seekable:!0,position:0,stream_ops:n.stream_ops,ungotten:[],error:!1});return l.stream_ops.open&&l.stream_ops.open(l),s&&a.chmod(n,t&511),u.logReadFiles&&!(r&1)&&(e in a.readFiles||(a.readFiles[e]=1)),l},close(e){if(a.isClosed(e))throw new a.ErrnoError(8);e.getdents&&(e.getdents=null);try{e.stream_ops.close&&e.stream_ops.close(e)}catch(r){throw r}finally{a.closeStream(e.fd)}e.fd=null},isClosed(e){return e.fd===null},llseek(e,r,t){if(a.isClosed(e))throw new a.ErrnoError(8);if(!e.seekable||!e.stream_ops.llseek)throw new a.ErrnoError(70);if(t!=0&&t!=1&&t!=2)throw new a.ErrnoError(28);return e.position=e.stream_ops.llseek(e,r,t),e.ungotten=[],e.position},read(e,r,t,n,i){if(T(t>=0),n<0||i<0)throw new a.ErrnoError(28);if(a.isClosed(e))throw new a.ErrnoError(8);if((e.flags&2097155)===1)throw new a.ErrnoError(8);if(a.isDir(e.node.mode))throw new a.ErrnoError(31);if(!e.stream_ops.read)throw new a.ErrnoError(28);var o=typeof i<"u";if(!o)i=e.position;else if(!e.seekable)throw new a.ErrnoError(70);var s=e.stream_ops.read(e,r,t,n,i);return o||(e.position+=s),s},write(e,r,t,n,i,o){if(T(t>=0),n<0||i<0)throw new a.ErrnoError(28);if(a.isClosed(e))throw new a.ErrnoError(8);if((e.flags&2097155)===0)throw new a.ErrnoError(8);if(a.isDir(e.node.mode))throw new a.ErrnoError(31);if(!e.stream_ops.write)throw new a.ErrnoError(28);e.seekable&&e.flags&1024&&a.llseek(e,0,2);var s=typeof i<"u";if(!s)i=e.position;else if(!e.seekable)throw new a.ErrnoError(70);var c=e.stream_ops.write(e,r,t,n,i,o);return s||(e.position+=c),c},mmap(e,r,t,n,i){if((n&2)!==0&&(i&2)===0&&(e.flags&2097155)!==2)throw new a.ErrnoError(2);if((e.flags&2097155)===1)throw new a.ErrnoError(2);if(!e.stream_ops.mmap)throw new a.ErrnoError(43);if(!r)throw new a.ErrnoError(28);return e.stream_ops.mmap(e,r,t,n,i)},msync(e,r,t,n,i){return T(t>=0),e.stream_ops.msync?e.stream_ops.msync(e,r,t,n,i):0},ioctl(e,r,t){if(!e.stream_ops.ioctl)throw new a.ErrnoError(59);return e.stream_ops.ioctl(e,r,t)},readFile(e,r={}){if(r.flags=r.flags||0,r.encoding=r.encoding||"binary",r.encoding!=="utf8"&&r.encoding!=="binary")throw new Error(`Invalid encoding type "${r.encoding}"`);var t=a.open(e,r.flags),n=a.stat(e),i=n.size,o=new Uint8Array(i);return a.read(t,o,0,i,0),r.encoding==="utf8"&&(o=He(o)),a.close(t),o},writeFile(e,r,t={}){t.flags=t.flags||577;var n=a.open(e,t.flags,t.mode);if(typeof r=="string"&&(r=new Uint8Array(Wr(r,!0))),ArrayBuffer.isView(r))a.write(n,r,0,r.byteLength,void 0,t.canOwn);else throw new Error("Unsupported data type");a.close(n)},cwd:()=>a.currentPath,chdir(e){var r=a.lookupPath(e,{follow:!0});if(r.node===null)throw new a.ErrnoError(44);if(!a.isDir(r.node.mode))throw new a.ErrnoError(54);var t=a.nodePermissions(r.node,"x");if(t)throw new a.ErrnoError(t);a.currentPath=r.path},createDefaultDirectories(){a.mkdir("/tmp"),a.mkdir("/home"),a.mkdir("/home/web_user")},createDefaultDevices(){a.mkdir("/dev"),a.registerDevice(a.makedev(1,3),{read:()=>0,write:(n,i,o,s,c)=>s,llseek:()=>0}),a.mkdev("/dev/null",a.makedev(1,3)),Te.register(a.makedev(5,0),Te.default_tty_ops),Te.register(a.makedev(6,0),Te.default_tty1_ops),a.mkdev("/dev/tty",a.makedev(5,0)),a.mkdev("/dev/tty1",a.makedev(6,0));var e=new Uint8Array(1024),r=0,t=()=>(r===0&&(St(e),r=e.byteLength),e[--r]);a.createDevice("/dev","random",t),a.createDevice("/dev","urandom",t),a.mkdir("/dev/shm"),a.mkdir("/dev/shm/tmp")},createSpecialDirectories(){a.mkdir("/proc");var e=a.mkdir("/proc/self");a.mkdir("/proc/self/fd"),a.mount({mount(){var r=a.createNode(e,"fd",16895,73);return r.stream_ops={llseek:j.stream_ops.llseek},r.node_ops={lookup(t,n){var i=+n,o=a.getStreamChecked(i),s={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>o.path},id:i+1};return s.parent=s,s},readdir(){return Array.from(a.streams.entries()).filter(([t,n])=>n).map(([t,n])=>t.toString())}},r}},{},"/proc/self/fd")},createStandardStreams(e,r,t){e?a.createDevice("/dev","stdin",e):a.symlink("/dev/tty","/dev/stdin"),r?a.createDevice("/dev","stdout",null,r):a.symlink("/dev/tty","/dev/stdout"),t?a.createDevice("/dev","stderr",null,t):a.symlink("/dev/tty1","/dev/stderr");var n=a.open("/dev/stdin",0),i=a.open("/dev/stdout",1),o=a.open("/dev/stderr",1);T(n.fd===0,`invalid handle for stdin (${n.fd})`),T(i.fd===1,`invalid handle for stdout (${i.fd})`),T(o.fd===2,`invalid handle for stderr (${o.fd})`)},staticInit(){a.nameTable=new Array(4096),a.mount(j,{},"/"),a.createDefaultDirectories(),a.createDefaultDevices(),a.createSpecialDirectories(),a.filesystems={MEMFS:j}},init(e,r,t){T(!a.initialized,"FS.init was previously called. If you want to initialize later with custom parameters, remove any earlier calls (note that one is automatically added to the generated code)"),a.initialized=!0,e??=u.stdin,r??=u.stdout,t??=u.stderr,a.createStandardStreams(e,r,t)},quit(){a.initialized=!1,rt(0);for(var e of a.streams)e&&a.close(e)},findObject(e,r){var t=a.analyzePath(e,r);return t.exists?t.object:null},analyzePath(e,r){try{var t=a.lookupPath(e,{follow:!r});e=t.path}catch{}var n={isRoot:!1,exists:!1,error:0,name:null,path:null,object:null,parentExists:!1,parentPath:null,parentObject:null};try{var t=a.lookupPath(e,{parent:!0});n.parentExists=!0,n.parentPath=t.path,n.parentObject=t.node,n.name=z.basename(e),t=a.lookupPath(e,{follow:!r}),n.exists=!0,n.path=t.path,n.object=t.node,n.name=t.node.name,n.isRoot=t.path==="/"}catch(i){n.error=i.errno}return n},createPath(e,r,t,n){e=typeof e=="string"?e:a.getPath(e);for(var i=r.split("/").reverse();i.length;){var o=i.pop();if(o){var s=z.join2(e,o);try{a.mkdir(s)}catch(c){if(c.errno!=20)throw c}e=s}}return s},createFile(e,r,t,n,i){var o=z.join2(typeof e=="string"?e:a.getPath(e),r),s=zr(n,i);return a.create(o,s)},createDataFile(e,r,t,n,i,o){var s=r;e&&(e=typeof e=="string"?e:a.getPath(e),s=r?z.join2(e,r):e);var c=zr(n,i),l=a.create(s,c);if(t){if(typeof t=="string"){for(var d=new Array(t.length),f=0,_=t.length;f<_;++f)d[f]=t.charCodeAt(f);t=d}a.chmod(l,c|146);var g=a.open(l,577);a.write(g,t,0,t.length,0,o),a.close(g),a.chmod(l,c)}},createDevice(e,r,t,n){var i=z.join2(typeof e=="string"?e:a.getPath(e),r),o=zr(!!t,!!n);a.createDevice.major??=64;var s=a.makedev(a.createDevice.major++,0);return a.registerDevice(s,{open(c){c.seekable=!1},close(c){n?.buffer?.length&&n(10)},read(c,l,d,f,_){for(var g=0,p=0;pthis.length-1||p<0)){var w=p%this.chunkSize,M=p/this.chunkSize|0;return this.getter(M)[w]}}setDataGetter(p){this.getter=p}cacheLength(){var p=new XMLHttpRequest;if(p.open("HEAD",t,!1),p.send(null),!(p.status>=200&&p.status<300||p.status===304))throw new Error("Couldn't load "+t+". Status: "+p.status);var w=Number(p.getResponseHeader("Content-length")),M,L=(M=p.getResponseHeader("Accept-Ranges"))&&M==="bytes",I=(M=p.getResponseHeader("Content-Encoding"))&&M==="gzip",V=1024*1024;L||(V=w);var U=(ee,oe)=>{if(ee>oe)throw new Error("invalid range ("+ee+", "+oe+") or no bytes requested!");if(oe>w-1)throw new Error("only "+w+" bytes available! programmer error!");var H=new XMLHttpRequest;if(H.open("GET",t,!1),w!==V&&H.setRequestHeader("Range","bytes="+ee+"-"+oe),H.responseType="arraybuffer",H.overrideMimeType&&H.overrideMimeType("text/plain; charset=x-user-defined"),H.send(null),!(H.status>=200&&H.status<300||H.status===304))throw new Error("Couldn't load "+t+". Status: "+H.status);return H.response!==void 0?new Uint8Array(H.response||[]):Wr(H.responseText||"",!0)},te=this;te.setDataGetter(ee=>{var oe=ee*V,H=(ee+1)*V-1;if(H=Math.min(H,w-1),typeof te.chunks[ee]>"u"&&(te.chunks[ee]=U(oe,H)),typeof te.chunks[ee]>"u")throw new Error("doXHR failed!");return te.chunks[ee]}),(I||!w)&&(V=w=1,w=this.getter(0).length,V=w,G("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=w,this._chunkSize=V,this.lengthKnown=!0}get length(){return this.lengthKnown||this.cacheLength(),this._length}get chunkSize(){return this.lengthKnown||this.cacheLength(),this._chunkSize}}if(typeof XMLHttpRequest<"u"){if(!m)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var s=new o,c={isDevice:!1,contents:s}}else var c={isDevice:!1,url:t};var l=a.createFile(e,r,c,n,i);c.contents?l.contents=c.contents:c.url&&(l.contents=null,l.url=c.url),Object.defineProperties(l,{usedBytes:{get:function(){return this.contents.length}}});var d={},f=Object.keys(l.stream_ops);f.forEach(g=>{var p=l.stream_ops[g];d[g]=(...w)=>(a.forceLoadFile(l),p(...w))});function _(g,p,w,M,L){var I=g.node.contents;if(L>=I.length)return 0;var V=Math.min(I.length-L,M);if(T(V>=0),I.slice)for(var U=0;U(a.forceLoadFile(l),_(g,p,w,M,L)),d.mmap=(g,p,w,M,L)=>{a.forceLoadFile(l);var I=Ft(p);if(!I)throw new a.ErrnoError(48);return _(g,X,I,p,w),{ptr:I,allocated:!0}},l.stream_ops=d,l},absolutePath(){K("FS.absolutePath has been removed; use PATH_FS.resolve instead")},createFolder(){K("FS.createFolder has been removed; use FS.mkdir instead")},createLink(){K("FS.createLink has been removed; use FS.symlink instead")},joinPath(){K("FS.joinPath has been removed; use PATH.join instead")},mmapAlloc(){K("FS.mmapAlloc has been replaced by the top level function mmapAlloc")},standardizePath(){K("FS.standardizePath has been removed; use PATH.normalize instead")}},q={DEFAULT_POLLMASK:5,calculateAt(e,r,t){if(z.isAbs(r))return r;var n;if(e===-100)n=a.cwd();else{var i=q.getStreamFromFD(e);n=i.path}if(r.length==0){if(!t)throw new a.ErrnoError(44);return n}return n+"/"+r},writeStat(e,r){C[e>>2]=r.dev,C[e+4>>2]=r.mode,R[e+8>>2]=r.nlink,C[e+12>>2]=r.uid,C[e+16>>2]=r.gid,C[e+20>>2]=r.rdev,de[e+24>>3]=BigInt(r.size),C[e+32>>2]=4096,C[e+36>>2]=r.blocks;var t=r.atime.getTime(),n=r.mtime.getTime(),i=r.ctime.getTime();return de[e+40>>3]=BigInt(Math.floor(t/1e3)),R[e+48>>2]=t%1e3*1e3*1e3,de[e+56>>3]=BigInt(Math.floor(n/1e3)),R[e+64>>2]=n%1e3*1e3*1e3,de[e+72>>3]=BigInt(Math.floor(i/1e3)),R[e+80>>2]=i%1e3*1e3*1e3,de[e+88>>3]=BigInt(r.ino),0},writeStatFs(e,r){C[e+4>>2]=r.bsize,C[e+40>>2]=r.bsize,C[e+8>>2]=r.blocks,C[e+12>>2]=r.bfree,C[e+16>>2]=r.bavail,C[e+20>>2]=r.files,C[e+24>>2]=r.ffree,C[e+28>>2]=r.fsid,C[e+44>>2]=r.flags,C[e+36>>2]=r.namelen},doMsync(e,r,t,n,i){if(!a.isFile(r.node.mode))throw new a.ErrnoError(43);if(n&2)return 0;var o=ae.slice(e,e+t);a.msync(r,o,i,t,n)},getStreamFromFD(e){var r=a.getStreamChecked(e);return r},varargs:void 0,getStr(e){var r=Se(e);return r}};function ui(e,r,t){try{var n=q.getStreamFromFD(e);if(T(!t),n.fd===r)return-28;if(r<0||r>=a.MAX_OPEN_FDS)return-8;var i=a.getStream(r);return i&&a.close(i),a.dupStream(n,r).fd}catch(o){if(typeof a>"u"||o.name!=="ErrnoError")throw o;return-o.errno}}var mr=()=>{T(q.varargs!=null);var e=C[+q.varargs>>2];return q.varargs+=4,e},qe=mr;function di(e,r,t){q.varargs=t;try{var n=q.getStreamFromFD(e);switch(r){case 0:{var i=mr();if(i<0)return-28;for(;a.streams[i];)i++;var o;return o=a.dupStream(n,i),o.fd}case 1:case 2:return 0;case 3:return n.flags;case 4:{var i=mr();return n.flags|=i,0}case 12:{var i=qe(),s=0;return pe[i+s>>1]=2,0}case 13:case 14:return 0}return-28}catch(c){if(typeof a>"u"||c.name!=="ErrnoError")throw c;return-c.errno}}function fi(e,r){try{return q.writeStat(r,a.fstat(e))}catch(t){if(typeof a>"u"||t.name!=="ErrnoError")throw t;return-t.errno}}function hi(e,r,t){q.varargs=t;try{var n=q.getStreamFromFD(e);switch(r){case 21509:return n.tty?0:-59;case 21505:{if(!n.tty)return-59;if(n.tty.ops.ioctl_tcgets){var i=n.tty.ops.ioctl_tcgets(n),o=qe();C[o>>2]=i.c_iflag||0,C[o+4>>2]=i.c_oflag||0,C[o+8>>2]=i.c_cflag||0,C[o+12>>2]=i.c_lflag||0;for(var s=0;s<32;s++)X[o+s+17]=i.c_cc[s]||0;return 0}return 0}case 21510:case 21511:case 21512:return n.tty?0:-59;case 21506:case 21507:case 21508:{if(!n.tty)return-59;if(n.tty.ops.ioctl_tcsets){for(var o=qe(),c=C[o>>2],l=C[o+4>>2],d=C[o+8>>2],f=C[o+12>>2],_=[],s=0;s<32;s++)_.push(X[o+s+17]);return n.tty.ops.ioctl_tcsets(n.tty,r,{c_iflag:c,c_oflag:l,c_cflag:d,c_lflag:f,c_cc:_})}return 0}case 21519:{if(!n.tty)return-59;var o=qe();return C[o>>2]=0,0}case 21520:return n.tty?-28:-59;case 21531:{var o=qe();return a.ioctl(n,r,o)}case 21523:{if(!n.tty)return-59;if(n.tty.ops.ioctl_tiocgwinsz){var g=n.tty.ops.ioctl_tiocgwinsz(n.tty),o=qe();pe[o>>1]=g[0],pe[o+2>>1]=g[1]}return 0}case 21524:return n.tty?0:-59;case 21515:return n.tty?0:-59;default:return-28}}catch(p){if(typeof a>"u"||p.name!=="ErrnoError")throw p;return-p.errno}}function vi(e,r){try{return e=q.getStr(e),q.writeStat(r,a.lstat(e))}catch(t){if(typeof a>"u"||t.name!=="ErrnoError")throw t;return-t.errno}}function _i(e,r,t,n){try{r=q.getStr(r);var i=n&256,o=n&4096;return n=n&-6401,T(!n,`unknown flags in __syscall_newfstatat: ${n}`),r=q.calculateAt(e,r,o),q.writeStat(t,i?a.lstat(r):a.stat(r))}catch(s){if(typeof a>"u"||s.name!=="ErrnoError")throw s;return-s.errno}}function pi(e,r,t,n){q.varargs=n;try{r=q.getStr(r),r=q.calculateAt(e,r);var i=n?mr():0;return a.open(r,t,i).fd}catch(o){if(typeof a>"u"||o.name!=="ErrnoError")throw o;return-o.errno}}function mi(e,r){try{return e=q.getStr(e),q.writeStat(r,a.stat(e))}catch(t){if(typeof a>"u"||t.name!=="ErrnoError")throw t;return-t.errno}}var gi=()=>K("native code called abort()"),Z=e=>{for(var r="";;){var t=ae[e++];if(!t)return r;r+=String.fromCharCode(t)}},Ye={},Oe={},gr={},ir=class extends Error{constructor(r){super(r),this.name="BindingError"}},N=e=>{throw new ir(e)};function yi(e,r,t={}){var n=r.name;if(e||N(`type "${n}" must have a positive integer typeid pointer`),Oe.hasOwnProperty(e)){if(t.ignoreDuplicateRegistrations)return;N(`Cannot register type '${n}' twice`)}if(Oe[e]=r,delete gr[e],Ye.hasOwnProperty(e)){var i=Ye[e];delete Ye[e],i.forEach(o=>o())}}function fe(e,r,t={}){if(r.argPackAdvance===void 0)throw new TypeError("registerType registeredInstance requires argPackAdvance");return yi(e,r,t)}var xt=(e,r,t)=>{switch(r){case 1:return t?n=>X[n]:n=>ae[n];case 2:return t?n=>pe[n>>1]:n=>Me[n>>1];case 4:return t?n=>C[n>>2]:n=>R[n>>2];case 8:return t?n=>de[n>>3]:n=>_t[n>>3];default:throw new TypeError(`invalid integer width (${r}): ${e}`)}},De=e=>{if(e===null)return"null";var r=typeof e;return r==="object"||r==="array"||r==="function"?e.toString():""+e},Mt=(e,r,t,n)=>{if(rn)throw new TypeError(`Passing a number "${De(r)}" from JS side to C/C++ side to an argument of type "${e}", which is outside the valid range [${t}, ${n}]!`)},wi=(e,r,t,n,i)=>{r=Z(r);let o=n===0n,s=c=>c;if(o){let c=t*8;s=l=>BigInt.asUintN(c,l),i=s(i)}fe(e,{name:r,fromWireType:s,toWireType:(c,l)=>{if(typeof l=="number")l=BigInt(l);else if(typeof l!="bigint")throw new TypeError(`Cannot convert "${De(l)}" to ${this.name}`);return Mt(r,l,n,i),l},argPackAdvance:me,readValueFromPointer:xt(r,t,!o),destructorFunction:null})},me=8,Ei=(e,r,t,n)=>{r=Z(r),fe(e,{name:r,fromWireType:function(i){return!!i},toWireType:function(i,o){return o?t:n},argPackAdvance:me,readValueFromPointer:function(i){return this.fromWireType(ae[i])},destructorFunction:null})},bi=e=>({count:e.count,deleteScheduled:e.deleteScheduled,preservePointerOnDelete:e.preservePointerOnDelete,ptr:e.ptr,ptrType:e.ptrType,smartPtr:e.smartPtr,smartPtrType:e.smartPtrType}),Hr=e=>{function r(t){return t.$$.ptrType.registeredClass.name}N(r(e)+" instance already deleted")},Vr=!1,$t=e=>{},Si=e=>{e.smartPtr?e.smartPtrType.rawDestructor(e.smartPtr):e.ptrType.registeredClass.rawDestructor(e.ptr)},Rt=e=>{e.count.value-=1;var r=e.count.value===0;r&&Si(e)},Ot=(e,r,t)=>{if(r===t)return e;if(t.baseClass===void 0)return null;var n=Ot(e,r,t.baseClass);return n===null?null:t.downcast(n)},Dt={},ki={},Fi=(e,r)=>{for(r===void 0&&N("ptr should not be undefined");e.baseClass;)r=e.upcast(r),e=e.baseClass;return r},Ti=(e,r)=>(r=Fi(e,r),ki[r]),Ai=class extends Error{constructor(r){super(r),this.name="InternalError"}},yr=e=>{throw new Ai(e)},wr=(e,r)=>{(!r.ptrType||!r.ptr)&&yr("makeClassHandle requires ptr and ptrType");var t=!!r.smartPtrType,n=!!r.smartPtr;return t!==n&&yr("Both smartPtrType and smartPtr must be specified"),r.count={value:1},or(Object.create(e,{$$:{value:r,writable:!0}}))};function jt(e){var r=this.getPointee(e);if(!r)return this.destructor(e),null;var t=Ti(this.registeredClass,r);if(t!==void 0){if(t.$$.count.value===0)return t.$$.ptr=r,t.$$.smartPtr=e,t.clone();var n=t.clone();return this.destructor(e),n}function i(){return this.isSmartPointer?wr(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:r,smartPtrType:this,smartPtr:e}):wr(this.registeredClass.instancePrototype,{ptrType:this,ptr:e})}var o=this.registeredClass.getActualType(r),s=Dt[o];if(!s)return i.call(this);var c;this.isConst?c=s.constPointerType:c=s.pointerType;var l=Ot(r,this.registeredClass,c.registeredClass);return l===null?i.call(this):this.isSmartPointer?wr(c.registeredClass.instancePrototype,{ptrType:c,ptr:l,smartPtrType:this,smartPtr:e}):wr(c.registeredClass.instancePrototype,{ptrType:c,ptr:l})}var or=e=>typeof FinalizationRegistry>"u"?(or=r=>r,e):(Vr=new FinalizationRegistry(r=>{console.warn(r.leakWarning),Rt(r.$$)}),or=r=>{var t=r.$$,n=!!t.smartPtr;if(n){var i={$$:t},o=t.ptrType.registeredClass,s=new Error(`Embind found a leaked C++ instance ${o.name} <${ze(t.ptr)}>. +We'll free it automatically in this case, but this functionality is not reliable across various environments. +Make sure to invoke .delete() manually once you're done with the instance instead. +Originally allocated`);"captureStackTrace"in Error&&Error.captureStackTrace(s,jt),i.leakWarning=s.stack.replace(/^Error: /,""),Vr.register(r,i,r)}return r},$t=r=>Vr.unregister(r),or(e)),Er=[],Pi=()=>{for(;Er.length;){var e=Er.pop();e.$$.deleteScheduled=!1,e.delete()}},It,Ci=()=>{let e=br.prototype;Object.assign(e,{isAliasOf(t){if(!(this instanceof br)||!(t instanceof br))return!1;var n=this.$$.ptrType.registeredClass,i=this.$$.ptr;t.$$=t.$$;for(var o=t.$$.ptrType.registeredClass,s=t.$$.ptr;n.baseClass;)i=n.upcast(i),n=n.baseClass;for(;o.baseClass;)s=o.upcast(s),o=o.baseClass;return n===o&&i===s},clone(){if(this.$$.ptr||Hr(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var t=or(Object.create(Object.getPrototypeOf(this),{$$:{value:bi(this.$$)}}));return t.$$.count.value+=1,t.$$.deleteScheduled=!1,t},delete(){this.$$.ptr||Hr(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&N("Object already scheduled for deletion"),$t(this),Rt(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)},isDeleted(){return!this.$$.ptr},deleteLater(){return this.$$.ptr||Hr(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&N("Object already scheduled for deletion"),Er.push(this),Er.length===1&&It&&It(Pi),this.$$.deleteScheduled=!0,this}});let r=Symbol.dispose;r&&(e[r]=e.delete)};function br(){}var Sr=(e,r)=>Object.defineProperty(r,"name",{value:e}),Gr=(e,r,t)=>{if(e[r].overloadTable===void 0){var n=e[r];e[r]=function(...i){return e[r].overloadTable.hasOwnProperty(i.length)||N(`Function '${t}' called with an invalid number of arguments (${i.length}) - expects one of (${e[r].overloadTable})!`),e[r].overloadTable[i.length].apply(this,i)},e[r].overloadTable=[],e[r].overloadTable[n.argCount]=n}},qr=(e,r,t)=>{u.hasOwnProperty(e)?((t===void 0||u[e].overloadTable!==void 0&&u[e].overloadTable[t]!==void 0)&&N(`Cannot register public name '${e}' twice`),Gr(u,e,e),u[e].overloadTable.hasOwnProperty(t)&&N(`Cannot register multiple overloads of a function with the same number of arguments (${t})!`),u[e].overloadTable[t]=r):(u[e]=r,u[e].argCount=t)},xi=48,Mi=57,$i=e=>{T(typeof e=="string"),e=e.replace(/[^a-zA-Z0-9_]/g,"$");var r=e.charCodeAt(0);return r>=xi&&r<=Mi?`_${e}`:e};function Ri(e,r,t,n,i,o,s,c){this.name=e,this.constructor=r,this.instancePrototype=t,this.rawDestructor=n,this.baseClass=i,this.getActualType=o,this.upcast=s,this.downcast=c,this.pureVirtualFunctions=[]}var kr=(e,r,t)=>{for(;r!==t;)r.upcast||N(`Expected null or instance of ${t.name}, got an instance of ${r.name}`),e=r.upcast(e),r=r.baseClass;return e};function Oi(e,r){if(r===null)return this.isReference&&N(`null is not a valid ${this.name}`),0;r.$$||N(`Cannot pass "${De(r)}" as a ${this.name}`),r.$$.ptr||N(`Cannot pass deleted object as a pointer of type ${this.name}`);var t=r.$$.ptrType.registeredClass,n=kr(r.$$.ptr,t,this.registeredClass);return n}function Di(e,r){var t;if(r===null)return this.isReference&&N(`null is not a valid ${this.name}`),this.isSmartPointer?(t=this.rawConstructor(),e!==null&&e.push(this.rawDestructor,t),t):0;(!r||!r.$$)&&N(`Cannot pass "${De(r)}" as a ${this.name}`),r.$$.ptr||N(`Cannot pass deleted object as a pointer of type ${this.name}`),!this.isConst&&r.$$.ptrType.isConst&&N(`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=kr(r.$$.ptr,n,this.registeredClass),this.isSmartPointer)switch(r.$$.smartPtr===void 0&&N("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:r.$$.smartPtrType===this?t=r.$$.smartPtr:N(`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 i=r.clone();t=this.rawShare(t,Q.toHandle(()=>i.delete())),e!==null&&e.push(this.rawDestructor,t)}break;default:N("Unsupporting sharing policy")}return t}function ji(e,r){if(r===null)return this.isReference&&N(`null is not a valid ${this.name}`),0;r.$$||N(`Cannot pass "${De(r)}" as a ${this.name}`),r.$$.ptr||N(`Cannot pass deleted object as a pointer of type ${this.name}`),r.$$.ptrType.isConst&&N(`Cannot convert argument of type ${r.$$.ptrType.name} to parameter type ${this.name}`);var t=r.$$.ptrType.registeredClass,n=kr(r.$$.ptr,t,this.registeredClass);return n}function Fr(e){return this.fromWireType(R[e>>2])}var Ii=()=>{Object.assign(Tr.prototype,{getPointee(e){return this.rawGetPointee&&(e=this.rawGetPointee(e)),e},destructor(e){this.rawDestructor?.(e)},argPackAdvance:me,readValueFromPointer:Fr,fromWireType:jt})};function Tr(e,r,t,n,i,o,s,c,l,d,f){this.name=e,this.registeredClass=r,this.isReference=t,this.isConst=n,this.isSmartPointer=i,this.pointeeType=o,this.sharingPolicy=s,this.rawGetPointee=c,this.rawConstructor=l,this.rawShare=d,this.rawDestructor=f,!i&&r.baseClass===void 0?n?(this.toWireType=Oi,this.destructorFunction=null):(this.toWireType=ji,this.destructorFunction=null):this.toWireType=Di}var Nt=(e,r,t)=>{u.hasOwnProperty(e)||yr("Replacing nonexistent public symbol"),u[e].overloadTable!==void 0&&t!==void 0?u[e].overloadTable[t]=r:(u[e]=r,u[e].argCount=t)},Lt=[],Ar,F=e=>{var r=Lt[e];return r||(Lt[e]=r=Ar.get(e)),T(Ar.get(e)==r,"JavaScript-side Wasm function table mirror is out of date!"),r},ge=(e,r,t=!1)=>{T(!t,"Async bindings are only supported with JSPI."),e=Z(e);function n(){var o=F(r);return o}var i=n();return typeof i!="function"&&N(`unknown function pointer with signature ${e}: ${r}`),i};class Ni extends Error{}var Ut=e=>{var r=on(e),t=Z(r);return _e(r),t},je=(e,r)=>{var t=[],n={};function i(o){if(!n[o]&&!Oe[o]){if(gr[o]){gr[o].forEach(i);return}t.push(o),n[o]=!0}}throw r.forEach(i),new Ni(`${e}: `+t.map(Ut).join([", "]))},ve=(e,r,t)=>{e.forEach(c=>gr[c]=r);function n(c){var l=t(c);l.length!==e.length&&yr("Mismatched type converter count");for(var d=0;d{Oe.hasOwnProperty(c)?i[l]=Oe[c]:(o.push(c),Ye.hasOwnProperty(c)||(Ye[c]=[]),Ye[c].push(()=>{i[l]=Oe[c],++s,s===o.length&&n(i)}))}),o.length===0&&n(i)},Li=(e,r,t,n,i,o,s,c,l,d,f,_,g)=>{f=Z(f),o=ge(i,o),c&&=ge(s,c),d&&=ge(l,d),g=ge(_,g);var p=$i(f);qr(p,function(){je(`Cannot construct ${f} due to unbound types`,[n])}),ve([e,r,t],n?[n]:[],w=>{w=w[0];var M,L;n?(M=w.registeredClass,L=M.instancePrototype):L=br.prototype;var I=Sr(f,function(...H){if(Object.getPrototypeOf(this)!==V)throw new ir(`Use 'new' to construct ${f}`);if(U.constructor_body===void 0)throw new ir(`${f} has no accessible constructor`);var Le=U.constructor_body[H.length];if(Le===void 0)throw new ir(`Tried to invoke ctor of ${f} with invalid number of parameters (${H.length}) - expected (${Object.keys(U.constructor_body).toString()}) parameters instead!`);return Le.apply(this,H)}),V=Object.create(L,{constructor:{value:I}});I.prototype=V;var U=new Ri(f,I,V,g,M,o,c,d);U.baseClass&&(U.baseClass.__derivedClasses??=[],U.baseClass.__derivedClasses.push(U));var te=new Tr(f,U,!0,!1,!1),ee=new Tr(f+"*",U,!1,!1,!1),oe=new Tr(f+" const*",U,!1,!0,!1);return Dt[e]={pointerType:ee,constPointerType:oe},Nt(p,I),[te,ee,oe]})},Yr=e=>{for(;e.length;){var r=e.pop(),t=e.pop();t(r)}};function Bt(e){for(var r=1;rt){var o=r==t?r:`${r} to ${t}`;i(`function ${n} called with ${e} arguments, expected ${o}`)}}function Bi(e,r,t,n){var i=Bt(e),o=e.length-2,s=[],c=["fn"];r&&c.push("thisWired");for(var l=0;l=2&&e[t].optional;--t)r--;return r}function Pr(e,r,t,n,i,o){var s=r.length;s<2&&N("argTypes array size mismatch! Must at least get return value and 'this' types!"),T(!o,"Async bindings are only supported with JSPI.");for(var c=r[1]!==null&&t!==null,l=Bt(r),d=r[0].name!=="void",f=s-2,_=Wi(r),g=[e,N,n,i,Yr,r[0],r[1]],p=0;p{for(var t=[],n=0;n>2]);return t},Xr=e=>{e=e.trim();let r=e.indexOf("(");return r===-1?e:(T(e.endsWith(")"),"Parentheses for argument names should match."),e.slice(0,r))},zi=(e,r,t,n,i,o,s,c,l)=>{var d=Cr(t,n);r=Z(r),r=Xr(r),o=ge(i,o,c),ve([],[e],f=>{f=f[0];var _=`${f.name}.${r}`;function g(){je(`Cannot call ${_} due to unbound types`,d)}r.startsWith("@@")&&(r=Symbol[r.substring(2)]);var p=f.registeredClass.constructor;return p[r]===void 0?(g.argCount=t-1,p[r]=g):(Gr(p,r,_),p[r].overloadTable[t-1]=g),ve([],d,w=>{var M=[w[0],null].concat(w.slice(1)),L=Pr(_,M,null,o,s,c);if(p[r].overloadTable===void 0?(L.argCount=t-1,p[r]=L):p[r].overloadTable[t-1]=L,f.registeredClass.__derivedClasses)for(let I of f.registeredClass.__derivedClasses)I.constructor.hasOwnProperty(r)||(I.constructor[r]=L);return[]}),[]})},Hi=(e,r,t,n,i,o)=>{T(r>0);var s=Cr(r,t);i=ge(n,i);var c=[o],l=[];ve([],[e],d=>{d=d[0];var f=`constructor ${d.name}`;if(d.registeredClass.constructor_body===void 0&&(d.registeredClass.constructor_body=[]),d.registeredClass.constructor_body[r-1]!==void 0)throw new ir(`Cannot register multiple constructors with identical number of parameters (${r-1}) for class '${d.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`);return d.registeredClass.constructor_body[r-1]=()=>{je(`Cannot construct ${d.name} due to unbound types`,s)},ve([],s,_=>(_.splice(1,0,null),d.registeredClass.constructor_body[r-1]=Pr(f,_,null,i,o),[])),[]})},Vi=(e,r,t,n,i,o,s,c,l,d)=>{var f=Cr(t,n);r=Z(r),r=Xr(r),o=ge(i,o,l),ve([],[e],_=>{_=_[0];var g=`${_.name}.${r}`;r.startsWith("@@")&&(r=Symbol[r.substring(2)]),c&&_.registeredClass.pureVirtualFunctions.push(r);function p(){je(`Cannot call ${g} due to unbound types`,f)}var w=_.registeredClass.instancePrototype,M=w[r];return M===void 0||M.overloadTable===void 0&&M.className!==_.name&&M.argCount===t-2?(p.argCount=t-2,p.className=_.name,w[r]=p):(Gr(w,r,g),w[r].overloadTable[t-2]=p),ve([],f,L=>{var I=Pr(g,L,_,o,s,l);return w[r].overloadTable===void 0?(I.argCount=t-2,w[r]=I):w[r].overloadTable[t-2]=I,[]}),[]})},Wt=(e,r,t)=>(e instanceof Object||N(`${t} with invalid "this": ${e}`),e instanceof r.registeredClass.constructor||N(`${t} incompatible with "this" of type ${e.constructor.name}`),e.$$.ptr||N(`cannot call emscripten binding method ${t} on deleted object`),kr(e.$$.ptr,e.$$.ptrType.registeredClass,r.registeredClass)),Gi=(e,r,t,n,i,o,s,c,l,d)=>{r=Z(r),i=ge(n,i),ve([],[e],f=>{f=f[0];var _=`${f.name}.${r}`,g={get(){je(`Cannot access ${_} due to unbound types`,[t,s])},enumerable:!0,configurable:!0};return l?g.set=()=>je(`Cannot access ${_} due to unbound types`,[t,s]):g.set=p=>N(_+" is a read-only property"),Object.defineProperty(f.registeredClass.instancePrototype,r,g),ve([],l?[t,s]:[t],p=>{var w=p[0],M={get(){var I=Wt(this,f,_+" getter");return w.fromWireType(i(o,I))},enumerable:!0};if(l){l=ge(c,l);var L=p[1];M.set=function(I){var V=Wt(this,f,_+" setter"),U=[];l(d,V,L.toWireType(U,I)),Yr(U)}}return Object.defineProperty(f.registeredClass.instancePrototype,r,M),[]}),[]})},qi=(e,r,t)=>{e=Z(e),ve([],[r],n=>(n=n[0],u[e]=n.fromWireType(t),[]))},zt=[],ye=[0,1,,1,null,1,!0,1,!1,1],Jr=e=>{e>9&&--ye[e+1]===0&&(T(ye[e]!==void 0,"Decref for unallocated handle."),ye[e]=void 0,zt.push(e))},Q={toValue:e=>(e||N(`Cannot use deleted val. handle = ${e}`),T(e===2||ye[e]!==void 0&&e%2===0,`invalid handle: ${e}`),ye[e]),toHandle:e=>{switch(e){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:{let r=zt.pop()||ye.length;return ye[r]=e,ye[r+1]=1,r}}}},Ht={name:"emscripten::val",fromWireType:e=>{var r=Q.toValue(e);return Jr(e),r},toWireType:(e,r)=>Q.toHandle(r),argPackAdvance:me,readValueFromPointer:Fr,destructorFunction:null},Vt=e=>fe(e,Ht),Yi=(e,r,t)=>{switch(r){case 1:return t?function(n){return this.fromWireType(X[n])}:function(n){return this.fromWireType(ae[n])};case 2:return t?function(n){return this.fromWireType(pe[n>>1])}:function(n){return this.fromWireType(Me[n>>1])};case 4:return t?function(n){return this.fromWireType(C[n>>2])}:function(n){return this.fromWireType(R[n>>2])};default:throw new TypeError(`invalid integer width (${r}): ${e}`)}},Xi=(e,r,t,n)=>{r=Z(r);function i(){}i.values={},fe(e,{name:r,constructor:i,fromWireType:function(o){return this.constructor.values[o]},toWireType:(o,s)=>s.value,argPackAdvance:me,readValueFromPointer:Yi(r,t,n),destructorFunction:null}),qr(r,i)},ar=(e,r)=>{var t=Oe[e];return t===void 0&&N(`${r} has unknown type ${Ut(e)}`),t},Ji=(e,r,t)=>{var n=ar(e,"enum");r=Z(r);var i=n.constructor,o=Object.create(n.constructor.prototype,{value:{value:t},constructor:{value:Sr(`${n.name}_${r}`,function(){})}});i.values[t]=o,i[r]=o},Ki=(e,r)=>{switch(r){case 4:return function(t){return this.fromWireType(fr[t>>2])};case 8:return function(t){return this.fromWireType(er[t>>3])};default:throw new TypeError(`invalid float width (${r}): ${e}`)}},Qi=(e,r,t)=>{r=Z(r),fe(e,{name:r,fromWireType:n=>n,toWireType:(n,i)=>{if(typeof i!="number"&&typeof i!="boolean")throw new TypeError(`Cannot convert ${De(i)} to ${this.name}`);return i},argPackAdvance:me,readValueFromPointer:Ki(r,t),destructorFunction:null})},Zi=(e,r,t,n,i,o,s,c)=>{var l=Cr(r,t);e=Z(e),e=Xr(e),i=ge(n,i,s),qr(e,function(){je(`Cannot call ${e} due to unbound types`,l)},r-1),ve([],l,d=>{var f=[d[0],null].concat(d.slice(1));return Nt(e,Pr(e,f,null,i,o,s),r-1),[]})},eo=(e,r,t,n,i)=>{r=Z(r);let o=n===0,s=l=>l;if(o){var c=32-8*t;s=l=>l<>>c,i=s(i)}fe(e,{name:r,fromWireType:s,toWireType:(l,d)=>{if(typeof d!="number"&&typeof d!="boolean")throw new TypeError(`Cannot convert "${De(d)}" to ${r}`);return Mt(r,d,n,i),d},argPackAdvance:me,readValueFromPointer:xt(r,t,n!==0),destructorFunction:null})},ro=(e,r,t)=>{var n=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array],i=n[r];function o(s){var c=R[s>>2],l=R[s+4>>2];return new i(X.buffer,l,c)}t=Z(t),fe(e,{name:t,fromWireType:o,argPackAdvance:me,readValueFromPointer:o},{ignoreDuplicateRegistrations:!0})},to=Object.assign({optional:!0},Ht),no=(e,r)=>{fe(e,to)},Ie=(e,r,t)=>(T(typeof t=="number","stringToUTF8(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!"),kt(e,ae,r,t)),io=(e,r)=>{r=Z(r);var t=!0;fe(e,{name:r,fromWireType(n){var i=R[n>>2],o=n+4,s;if(t)for(var c=o,l=0;l<=i;++l){var d=o+l;if(l==i||ae[d]==0){var f=d-c,_=Se(c,f);s===void 0?s=_:(s+="\0",s+=_),c=d+1}}else{for(var g=new Array(i),l=0;l>2]=o,s)if(t)Ie(i,l,o+1);else for(var d=0;d255&&(_e(c),N("String has UTF-16 code units that do not fit in 8 bits")),ae[l+d]=f}else ae.set(i,l);return n!==null&&n.push(_e,c),c},argPackAdvance:me,readValueFromPointer:Fr,destructorFunction(n){_e(n)}})},Gt=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,oo=(e,r)=>{T(e%2==0,"Pointer passed to UTF16ToString must be aligned to two bytes!");for(var t=e>>1,n=t+r/2,i=t;!(i>=n)&&Me[i];)++i;if(i-t>16&&Gt)return Gt.decode(Me.subarray(t,i));for(var o="",s=t;!(s>=n);++s){var c=Me[s];if(c==0)break;o+=String.fromCharCode(c)}return o},ao=(e,r,t)=>{if(T(r%2==0,"Pointer passed to stringToUTF16 must be aligned to two bytes!"),T(typeof t=="number","stringToUTF16(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!"),t??=2147483647,t<2)return 0;t-=2;for(var n=r,i=t>1]=s,r+=2}return pe[r>>1]=0,r-n},so=e=>e.length*2,co=(e,r)=>{T(e%4==0,"Pointer passed to UTF32ToString must be aligned to four bytes!");for(var t="",n=0;!(n>=r/4);n++){var i=C[e+n*4>>2];if(!i)break;t+=String.fromCodePoint(i)}return t},lo=(e,r,t)=>{if(T(r%4==0,"Pointer passed to stringToUTF32 must be aligned to four bytes!"),T(typeof t=="number","stringToUTF32(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!"),t??=2147483647,t<4)return 0;for(var n=r,i=n+t-4,o=0;o65535&&o++,C[r>>2]=s,r+=4,r+4>i)break}return C[r>>2]=0,r-n},uo=e=>{for(var r=0,t=0;t65535&&t++,r+=4}return r},fo=(e,r,t)=>{t=Z(t);var n,i,o,s;r===2?(n=oo,i=ao,s=so,o=c=>Me[c>>1]):r===4&&(n=co,i=lo,s=uo,o=c=>R[c>>2]),fe(e,{name:t,fromWireType:c=>{for(var l=R[c>>2],d,f=c+4,_=0;_<=l;++_){var g=c+4+_*r;if(_==l||o(g)==0){var p=g-f,w=n(f,p);d===void 0?d=w:(d+="\0",d+=w),f=g+r}}return _e(c),d},toWireType:(c,l)=>{typeof l!="string"&&N(`Cannot pass non-string to C++ string type ${t}`);var d=s(l),f=et(4+d+r);return R[f>>2]=d/r,i(l,f+4,d+r),c!==null&&c.push(_e,f),f},argPackAdvance:me,readValueFromPointer:Fr,destructorFunction(c){_e(c)}})},ho=(e,r)=>{Vt(e)},vo=(e,r)=>{r=Z(r),fe(e,{isVoid:!0,name:r,argPackAdvance:0,fromWireType:()=>{},toWireType:(t,n)=>{}})},_o=()=>{throw new xn},qt=(e,r,t)=>{var n=[],i=e.toWireType(n,t);return n.length&&(R[r>>2]=Q.toHandle(n)),i},po=(e,r,t)=>(e=Q.toValue(e),r=ar(r,"emval::as"),qt(r,t,e)),mo=(e,r)=>(e=Q.toValue(e),r=ar(r,"emval::as"),r.toWireType(null,e)),xr=[],go=(e,r,t,n)=>(e=xr[e],r=Q.toValue(r),e(null,r,t,n)),yo={},Kr=e=>{var r=yo[e];return r===void 0?Z(e):r},wo=(e,r,t,n,i)=>(e=xr[e],r=Q.toValue(r),t=Kr(t),e(r,r[t],n,i)),Yt=()=>globalThis,Eo=e=>e===0?Q.toHandle(Yt()):(e=Kr(e),Q.toHandle(Yt()[e])),bo=e=>{var r=xr.length;return xr.push(e),r},So=(e,r)=>{for(var t=new Array(e),n=0;n>2],`parameter ${n}`);return t},ko=(e,r,t)=>{var n=So(e,r),i=n.shift();e--;var o=`return function (obj, func, destructorsRef, args) { +`,s=0,c=[];t===0&&c.push("obj");for(var l=["retType"],d=[i],f=0;fw.name).join(", ")}) => ${i.name}>`;return bo(Sr(p,g))},Fo=(e,r)=>(e=Q.toValue(e),r=Q.toValue(r),Q.toHandle(e[r])),To=e=>{e>9&&(ye[e+1]+=1)},Ao=e=>(e=Q.toValue(e),typeof e=="number"),Po=e=>(e=Q.toValue(e),typeof e=="string"),Co=()=>Q.toHandle([]),xo=e=>Q.toHandle(Kr(e)),Mo=e=>{var r=Q.toValue(e);Yr(r),Jr(e)},$o=(e,r)=>{e=ar(e,"_emval_take_value");var t=e.readValueFromPointer(r);return Q.toHandle(t)},Ro=e=>{throw e=Q.toValue(e),e},Oo=e=>e%4===0&&(e%100!==0||e%400===0),Do=[0,31,60,91,121,152,182,213,244,274,305,335],jo=[0,31,59,90,120,151,181,212,243,273,304,334],Xt=e=>{var r=Oo(e.getFullYear()),t=r?Do:jo,n=t[e.getMonth()]+e.getDate()-1;return n},Io=9007199254740992,No=-9007199254740992,Qr=e=>eIo?NaN:Number(e);function Lo(e,r){e=Qr(e);var t=new Date(e*1e3);C[r>>2]=t.getSeconds(),C[r+4>>2]=t.getMinutes(),C[r+8>>2]=t.getHours(),C[r+12>>2]=t.getDate(),C[r+16>>2]=t.getMonth(),C[r+20>>2]=t.getFullYear()-1900,C[r+24>>2]=t.getDay();var n=Xt(t)|0;C[r+28>>2]=n,C[r+36>>2]=-(t.getTimezoneOffset()*60);var i=new Date(t.getFullYear(),0,1),o=new Date(t.getFullYear(),6,1).getTimezoneOffset(),s=i.getTimezoneOffset(),c=(o!=s&&t.getTimezoneOffset()==Math.min(s,o))|0;C[r+32>>2]=c}var Uo=function(e){var r=(()=>{var t=new Date(C[e+20>>2]+1900,C[e+16>>2],C[e+12>>2],C[e+8>>2],C[e+4>>2],C[e>>2],0),n=C[e+32>>2],i=t.getTimezoneOffset(),o=new Date(t.getFullYear(),0,1),s=new Date(t.getFullYear(),6,1).getTimezoneOffset(),c=o.getTimezoneOffset(),l=Math.min(c,s);if(n<0)C[e+32>>2]=+(s!=c&&l==i);else if(n>0!=(l==i)){var d=Math.max(c,s),f=n>0?l:d;t.setTime(t.getTime()+(f-i)*6e4)}C[e+24>>2]=t.getDay();var _=Xt(t)|0;C[e+28>>2]=_,C[e>>2]=t.getSeconds(),C[e+4>>2]=t.getMinutes(),C[e+8>>2]=t.getHours(),C[e+12>>2]=t.getDate(),C[e+16>>2]=t.getMonth(),C[e+20>>2]=t.getYear();var g=t.getTime();return isNaN(g)?-1:g/1e3})();return BigInt(r)},Bo=(e,r,t,n)=>{var i=new Date().getFullYear(),o=new Date(i,0,1),s=new Date(i,6,1),c=o.getTimezoneOffset(),l=s.getTimezoneOffset(),d=Math.max(c,l);R[e>>2]=d*60,C[r>>2]=+(c!=l);var f=p=>{var w=p>=0?"-":"+",M=Math.abs(p),L=String(Math.floor(M/60)).padStart(2,"0"),I=String(M%60).padStart(2,"0");return`UTC${w}${L}${I}`},_=f(c),g=f(l);T(_),T(g),T(Ge(_)<=16,`timezone name truncated to fit in TZNAME_MAX (${_})`),T(Ge(g)<=16,`timezone name truncated to fit in TZNAME_MAX (${g})`),lperformance.now(),Kt=()=>Date.now(),Wo=1,zo=e=>e>=0&&e<=3;function Ho(e,r,t){if(r=Qr(r),!zo(e))return 28;var n;if(e===0)n=Kt();else if(Wo)n=Jt();else return 52;var i=Math.round(n*1e3*1e3);return de[t>>3]=BigInt(i),0}var Mr=[],Vo=(e,r)=>{T(Array.isArray(Mr)),T(r%16==0),Mr.length=0;for(var t;t=ae[e++];){var n=String.fromCharCode(t),i=["d","f","i","p"];i.push("j"),T(i.includes(n),`Invalid character ${t}("${n}") in readEmAsmArgs! Use only [${i}], and do not specify "v" for void return argument.`);var o=t!=105;o&=t!=112,r+=o&&r%8?4:0,Mr.push(t==112?R[r>>2]:t==106?de[r>>3]:t==105?C[r>>2]:er[r>>3]),r+=o?8:4}return Mr},Go=(e,r,t)=>{var n=Vo(r,t);return T(nn.hasOwnProperty(e),`No EM_ASM constant found at address ${e}. The loaded WebAssembly file is likely out of sync with the generated JavaScript.`),nn[e](...n)},qo=(e,r,t)=>Go(e,r,t),Qt=()=>2147483648,Yo=()=>Qt(),Xo=(e,r)=>(T(r,"alignment argument is required"),Math.ceil(e/r)*r),Jo=e=>{var r=Ze.buffer,t=(e-r.byteLength+65535)/65536|0;try{return Ze.grow(t),pt(),1}catch(n){x(`growMemory: Attempted to grow heap from ${r.byteLength} bytes to ${e} bytes, but got error: ${n}`)}},Ko=e=>{var r=ae.length;e>>>=0,T(e>r);var t=Qt();if(e>t)return x(`Cannot enlarge memory, requested ${e} bytes, but the limit is ${t} bytes!`),!1;for(var n=1;n<=4;n*=2){var i=r*(1+.2/n);i=Math.min(i,e+100663296);var o=Math.min(t,Xo(Math.max(e,i),65536)),s=Jo(o);if(s)return!0}return x(`Failed to grow the heap from ${r} bytes to ${o} bytes, not enough memory!`),!1},Zr={},Qo=()=>B||"./this.program",sr=()=>{if(!sr.strings){var e=(typeof navigator=="object"&&navigator.language||"C").replace("-","_")+".UTF-8",r={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:e,_:Qo()};for(var t in Zr)Zr[t]===void 0?delete r[t]:r[t]=Zr[t];var n=[];for(var t in r)n.push(`${t}=${r[t]}`);sr.strings=n}return sr.strings},Zo=(e,r)=>{var t=0,n=0;for(var i of sr()){var o=r+t;R[e+n>>2]=o,t+=Ie(i,o,1/0)+1,n+=4}return 0},ea=(e,r)=>{var t=sr();R[e>>2]=t.length;var n=0;for(var i of t)n+=Ge(i)+1;return R[r>>2]=n,0},Zt=0,en=()=>wt||Zt>0,ra=e=>{ct=e,en()||(u.onExit?.(e),Ke=!0),$(e,new zn(e))},ta=(e,r)=>{if(ct=e,mc(),en()&&!r){var t=`program exited (with status: ${e}), but keepRuntimeAlive() is set (counter=${Zt}) due to an async operation, so halting execution but not exiting the runtime or preventing further async execution (you can use emscripten_force_exit, if you want to force a true shutdown)`;Nr?.(t),x(t)}ra(e)},na=ta;function ia(e){try{var r=q.getStreamFromFD(e);return a.close(r),0}catch(t){if(typeof a>"u"||t.name!=="ErrnoError")throw t;return t.errno}}var oa=(e,r,t,n)=>{for(var i=0,o=0;o>2],c=R[r+4>>2];r+=8;var l=a.read(e,X,s,c,n);if(l<0)return-1;if(i+=l,l>2]=o,0}catch(s){if(typeof a>"u"||s.name!=="ErrnoError")throw s;return s.errno}}function sa(e,r,t,n){r=Qr(r);try{if(isNaN(r))return 61;var i=q.getStreamFromFD(e);return a.llseek(i,r,t),de[n>>3]=BigInt(i.position),i.getdents&&r===0&&t===0&&(i.getdents=null),0}catch(o){if(typeof a>"u"||o.name!=="ErrnoError")throw o;return o.errno}}var ca=(e,r,t,n)=>{for(var i=0,o=0;o>2],c=R[r+4>>2];r+=8;var l=a.write(e,X,s,c,n);if(l<0)return-1;if(i+=l,l>2]=o,0}catch(s){if(typeof a>"u"||s.name!=="ErrnoError")throw s;return s.errno}}var ua=e=>e,da=e=>{var r=u["_"+e];return T(r,"Cannot call unknown function "+e+", make sure it is exported"),r},fa=(e,r)=>{T(e.length>=0,"writeArrayToMemory array must have a length (should be an array or typed array)"),X.set(e,r)},$r=e=>un(e),ha=e=>{var r=Ge(e)+1,t=$r(r);return Ie(e,t,r),t},rn=(e,r,t,n,i)=>{var o={string:w=>{var M=0;return w!=null&&w!==0&&(M=ha(w)),M},array:w=>{var M=$r(w.length);return fa(w,M),M}};function s(w){return r==="string"?Se(w):r==="boolean"?!!w:w}var c=da(e),l=[],d=0;if(T(r!=="array",'Return type should not be "array".'),n)for(var f=0;f(...i)=>rn(e,r,t,i,n),_a=(...e)=>a.createPath(...e),pa=(...e)=>a.unlink(...e),ma=(...e)=>a.createLazyFile(...e),ga=(...e)=>a.createDevice(...e),ya=e=>Rr(e),wa=e=>nt(e),Ea=e=>{var r=S(),t=$r(4),n=$r(4);fn(e,t,n);var i=R[t>>2],o=R[n>>2],s=Se(i);_e(i);var c;return o&&(c=Se(o),_e(o)),b(r),[s,c]},tn=e=>Ea(e);a.createPreloadedFile=Pt,a.staticInit(),Ci(),Ii(),T(ye.length===10),u.noExitRuntime&&(wt=u.noExitRuntime),u.preloadPlugins&&(At=u.preloadPlugins),u.print&&(G=u.print),u.printErr&&(x=u.printErr),u.wasmBinary&&(Je=u.wasmBinary),ka(),u.arguments&&(D=u.arguments),u.thisProgram&&(B=u.thisProgram),T(typeof u.memoryInitializerPrefixURL>"u","Module.memoryInitializerPrefixURL option was removed, use Module.locateFile instead"),T(typeof u.pthreadMainPrefixURL>"u","Module.pthreadMainPrefixURL option was removed, use Module.locateFile instead"),T(typeof u.cdInitializerPrefixURL>"u","Module.cdInitializerPrefixURL option was removed, use Module.locateFile instead"),T(typeof u.filePackagePrefixURL>"u","Module.filePackagePrefixURL option was removed, use Module.locateFile instead"),T(typeof u.read>"u","Module.read option was removed"),T(typeof u.readAsync>"u","Module.readAsync option was removed (modify readAsync in JS)"),T(typeof u.readBinary>"u","Module.readBinary option was removed (modify readBinary in JS)"),T(typeof u.setWindowTitle>"u","Module.setWindowTitle option was removed (modify emscripten_set_window_title in JS)"),T(typeof u.TOTAL_MEMORY>"u","Module.TOTAL_MEMORY has been renamed Module.INITIAL_MEMORY"),T(typeof u.ENVIRONMENT>"u","Module.ENVIRONMENT has been deprecated. To force the environment, use the ENVIRONMENT compile-time option (for example, -sENVIRONMENT=web or -sENVIRONMENT=node)"),T(typeof u.STACK_SIZE>"u","STACK_SIZE can no longer be set at runtime. Use -sSTACK_SIZE at link time"),T(typeof u.wasmMemory>"u","Use of `wasmMemory` detected. Use -sIMPORTED_MEMORY to define wasmMemory externally"),T(typeof u.INITIAL_MEMORY>"u","Detected runtime INITIAL_MEMORY setting. Use -sIMPORTED_MEMORY to define wasmMemory dynamically"),u.addRunDependency=Lr,u.removeRunDependency=hr,u.ccall=rn,u.cwrap=va,u.FS_createPreloadedFile=Pt,u.FS_unlink=pa,u.FS_createPath=_a,u.FS_createDevice=ga,u.FS=a,u.FS_createDataFile=Tt,u.FS_createLazyFile=ma,u.MEMFS=j;var ba=["writeI53ToI64","writeI53ToI64Clamped","writeI53ToI64Signaling","writeI53ToU64Clamped","writeI53ToU64Signaling","readI53FromI64","readI53FromU64","convertI32PairToI53","convertI32PairToI53Checked","convertU32PairToI53","getTempRet0","zeroMemory","withStackSave","inetPton4","inetNtop4","inetPton6","inetNtop6","readSockaddr","writeSockaddr","emscriptenLog","runMainThreadEmAsm","jstoi_q","autoResumeAudioContext","getDynCaller","dynCall","handleException","runtimeKeepalivePush","runtimeKeepalivePop","callUserCallback","maybeExit","asmjsMangle","HandleAllocator","getNativeTypeSize","addOnInit","addOnPostCtor","addOnPreMain","addOnExit","STACK_SIZE","STACK_ALIGN","POINTER_SIZE","ASSERTIONS","uleb128Encode","sigToWasmTypes","generateFuncType","convertJsFunctionToWasm","getEmptyTableSlot","updateTableMap","getFunctionAddress","addFunction","removeFunction","reallyNegative","unSign","strLen","reSign","formatString","intArrayToString","stringToAscii","stringToNewUTF8","registerKeyEventCallback","maybeCStringToJsString","findEventTarget","getBoundingClientRect","fillMouseEventData","registerMouseEventCallback","registerWheelEventCallback","registerUiEventCallback","registerFocusEventCallback","fillDeviceOrientationEventData","registerDeviceOrientationEventCallback","fillDeviceMotionEventData","registerDeviceMotionEventCallback","screenOrientation","fillOrientationChangeEventData","registerOrientationChangeEventCallback","fillFullscreenChangeEventData","registerFullscreenChangeEventCallback","JSEvents_requestFullscreen","JSEvents_resizeCanvasForFullscreen","registerRestoreOldStyle","hideEverythingExceptGivenElement","restoreHiddenElements","setLetterbox","softFullscreenResizeWebGLRenderTarget","doRequestFullscreen","fillPointerlockChangeEventData","registerPointerlockChangeEventCallback","registerPointerlockErrorEventCallback","requestPointerLock","fillVisibilityChangeEventData","registerVisibilityChangeEventCallback","registerTouchEventCallback","fillGamepadEventData","registerGamepadEventCallback","registerBeforeUnloadEventCallback","fillBatteryEventData","battery","registerBatteryEventCallback","setCanvasElementSize","getCanvasElementSize","jsStackTrace","getCallstack","convertPCtoSourceLocation","wasiRightsToMuslOFlags","wasiOFlagsToMuslOFlags","safeSetTimeout","setImmediateWrapped","safeRequestAnimationFrame","clearImmediateWrapped","registerPostMainLoop","registerPreMainLoop","getPromise","makePromise","idsToPromises","makePromiseCallback","Browser_asyncPrepareDataCounter","arraySum","addDays","getSocketFromFD","getSocketAddress","FS_mkdirTree","_setNetworkCallback","heapObjectForWebGLType","toTypedArrayIndex","webgl_enable_ANGLE_instanced_arrays","webgl_enable_OES_vertex_array_object","webgl_enable_WEBGL_draw_buffers","webgl_enable_WEBGL_multi_draw","webgl_enable_EXT_polygon_offset_clamp","webgl_enable_EXT_clip_control","webgl_enable_WEBGL_polygon_mode","emscriptenWebGLGet","computeUnpackAlignedImageSize","colorChannelsInGlTextureFormat","emscriptenWebGLGetTexPixelData","emscriptenWebGLGetUniform","webglGetUniformLocation","webglPrepareUniformLocationsBeforeFirstUse","webglGetLeftBracePos","emscriptenWebGLGetVertexAttrib","__glGetActiveAttribOrUniform","writeGLArray","registerWebGlEventCallback","runAndAbortIfError","ALLOC_NORMAL","ALLOC_STACK","allocate","writeStringToMemory","writeAsciiToMemory","demangle","stackTrace","getFunctionArgsName","createJsInvokerSignature","PureVirtualError","registerInheritedInstance","unregisterInheritedInstance","getInheritedInstanceCount","getLiveInheritedInstances","setDelayFunction","count_emval_handles"];ba.forEach($n);var Sa=["run","out","err","callMain","abort","wasmMemory","wasmExports","HEAPF32","HEAPF64","HEAP8","HEAPU8","HEAP16","HEAPU16","HEAP32","HEAPU32","HEAP64","HEAPU64","writeStackCookie","checkStackCookie","INT53_MAX","INT53_MIN","bigintToI53Checked","stackSave","stackRestore","stackAlloc","setTempRet0","ptrToString","exitJS","getHeapMax","growMemory","ENV","ERRNO_CODES","strError","DNS","Protocols","Sockets","timers","warnOnce","readEmAsmArgsArray","readEmAsmArgs","runEmAsmFunction","getExecutableName","keepRuntimeAlive","asyncLoad","alignMemory","mmapAlloc","wasmTable","getUniqueRunDependency","noExitRuntime","addOnPreRun","addOnPostRun","freeTableIndexes","functionsInTableMap","setValue","getValue","PATH","PATH_FS","UTF8Decoder","UTF8ArrayToString","UTF8ToString","stringToUTF8Array","stringToUTF8","lengthBytesUTF8","intArrayFromString","AsciiToString","UTF16Decoder","UTF16ToString","stringToUTF16","lengthBytesUTF16","UTF32ToString","stringToUTF32","lengthBytesUTF32","stringToUTF8OnStack","writeArrayToMemory","JSEvents","specialHTMLTargets","findCanvasEventTarget","currentFullscreenStrategy","restoreOldWindowedStyle","UNWIND_CACHE","ExitStatus","getEnvStrings","checkWasiClock","doReadv","doWritev","initRandomFill","randomFill","emSetImmediate","emClearImmediate_deps","emClearImmediate","promiseMap","uncaughtExceptionCount","exceptionLast","exceptionCaught","ExceptionInfo","findMatchingCatch","getExceptionMessageCommon","Browser","requestFullscreen","requestFullScreen","setCanvasSize","getUserMedia","createContext","getPreloadedImageData__data","wget","MONTH_DAYS_REGULAR","MONTH_DAYS_LEAP","MONTH_DAYS_REGULAR_CUMULATIVE","MONTH_DAYS_LEAP_CUMULATIVE","isLeapYear","ydayFromDate","SYSCALLS","preloadPlugins","FS_modeStringToFlags","FS_getMode","FS_stdin_getChar_buffer","FS_stdin_getChar","FS_readFile","FS_root","FS_mounts","FS_devices","FS_streams","FS_nextInode","FS_nameTable","FS_currentPath","FS_initialized","FS_ignorePermissions","FS_filesystems","FS_syncFSRequests","FS_readFiles","FS_lookupPath","FS_getPath","FS_hashName","FS_hashAddNode","FS_hashRemoveNode","FS_lookupNode","FS_createNode","FS_destroyNode","FS_isRoot","FS_isMountpoint","FS_isFile","FS_isDir","FS_isLink","FS_isChrdev","FS_isBlkdev","FS_isFIFO","FS_isSocket","FS_flagsToPermissionString","FS_nodePermissions","FS_mayLookup","FS_mayCreate","FS_mayDelete","FS_mayOpen","FS_checkOpExists","FS_nextfd","FS_getStreamChecked","FS_getStream","FS_createStream","FS_closeStream","FS_dupStream","FS_doSetAttr","FS_chrdev_stream_ops","FS_major","FS_minor","FS_makedev","FS_registerDevice","FS_getDevice","FS_getMounts","FS_syncfs","FS_mount","FS_unmount","FS_lookup","FS_mknod","FS_statfs","FS_statfsStream","FS_statfsNode","FS_create","FS_mkdir","FS_mkdev","FS_symlink","FS_rename","FS_rmdir","FS_readdir","FS_readlink","FS_stat","FS_fstat","FS_lstat","FS_doChmod","FS_chmod","FS_lchmod","FS_fchmod","FS_doChown","FS_chown","FS_lchown","FS_fchown","FS_doTruncate","FS_truncate","FS_ftruncate","FS_utime","FS_open","FS_close","FS_isClosed","FS_llseek","FS_read","FS_write","FS_mmap","FS_msync","FS_ioctl","FS_writeFile","FS_cwd","FS_chdir","FS_createDefaultDirectories","FS_createDefaultDevices","FS_createSpecialDirectories","FS_createStandardStreams","FS_staticInit","FS_init","FS_quit","FS_findObject","FS_analyzePath","FS_createFile","FS_forceLoadFile","FS_absolutePath","FS_createFolder","FS_createLink","FS_joinPath","FS_mmapAlloc","FS_standardizePath","TTY","PIPEFS","SOCKFS","tempFixedLengthArray","miniTempWebGLFloatBuffers","miniTempWebGLIntBuffers","GL","AL","GLUT","EGL","GLEW","IDBStore","SDL","SDL_gfx","allocateUTF8","allocateUTF8OnStack","print","printErr","jstoi_s","InternalError","BindingError","throwInternalError","throwBindingError","registeredTypes","awaitingDependencies","typeDependencies","tupleRegistrations","structRegistrations","sharedRegisterType","whenDependentTypesAreResolved","getTypeName","getFunctionName","heap32VectorToArray","requireRegisteredType","usesDestructorStack","checkArgCount","getRequiredArgCount","createJsInvoker","UnboundTypeError","GenericWireTypeSize","EmValType","EmValOptionalType","throwUnboundTypeError","ensureOverloadTable","exposePublicSymbol","replacePublicSymbol","createNamedFunction","embindRepr","registeredInstances","getBasestPointer","getInheritedInstance","registeredPointers","registerType","integerReadValueFromPointer","enumReadValueFromPointer","floatReadValueFromPointer","assertIntegerRange","readPointer","runDestructors","craftInvokerFunction","embind__requireFunction","genericPointerToWireType","constNoSmartPtrRawPointerToWireType","nonConstNoSmartPtrRawPointerToWireType","init_RegisteredPointer","RegisteredPointer","RegisteredPointer_fromWireType","runDestructor","releaseClassHandle","finalizationRegistry","detachFinalizer_deps","detachFinalizer","attachFinalizer","makeClassHandle","init_ClassHandle","ClassHandle","throwInstanceAlreadyDeleted","deletionQueue","flushPendingDeletes","delayFunction","RegisteredClass","shallowCopyInternalPointer","downcastPointer","upcastPointer","validateThis","char_0","char_9","makeLegalFunctionName","emval_freelist","emval_handles","emval_symbols","getStringOrSymbol","Emval","emval_get_global","emval_returnValue","emval_lookupTypes","emval_methodCallers","emval_addMethodCaller"];Sa.forEach(ht),u.incrementExceptionRefcount=ya,u.decrementExceptionRefcount=wa,u.getExceptionMessage=tn;function ka(){Mn("fetchSettings")}var nn={684552:()=>{typeof u<"u"&&"mjDISABLESTRING mjENABLESTRING mjFRAMESTRING mjLABELSTRING mjRNDSTRING mjTIMERSTRING mjVISSTRING".split(" ").forEach(function(e){Object.defineProperty(u,e,{get:function(){return u["get_"+e]()},set:function(r){},enumerable:!0,configurable:!0})})}},on=J("___getTypeName"),et=J("_malloc"),Fa=J("___cxa_free_exception"),rt=J("_fflush"),_e=J("_free"),tt=J("_emscripten_stack_get_end"),Ta=J("_emscripten_stack_get_base"),an=J("_strerror"),k=J("_setThrew"),sn=J("__emscripten_tempret_set"),cn=J("_emscripten_stack_init"),Aa=J("_emscripten_stack_get_free"),ln=J("__emscripten_stack_restore"),un=J("__emscripten_stack_alloc"),dn=J("_emscripten_stack_get_current"),nt=J("___cxa_decrement_exception_refcount"),Rr=J("___cxa_increment_exception_refcount"),fn=J("___get_exception_message"),hn=J("___cxa_can_catch"),vn=J("___cxa_get_exception_ptr");function Pa(e){on=ce("__getTypeName",1),et=ce("malloc",1),Fa=ce("__cxa_free_exception",1),rt=ce("fflush",1),_e=ce("free",1),tt=e.emscripten_stack_get_end,Ta=e.emscripten_stack_get_base,an=ce("strerror",1),k=ce("setThrew",2),sn=ce("_emscripten_tempret_set",1),cn=e.emscripten_stack_init,Aa=e.emscripten_stack_get_free,ln=e._emscripten_stack_restore,un=e._emscripten_stack_alloc,dn=e.emscripten_stack_get_current,nt=ce("__cxa_decrement_exception_refcount",1),Rr=ce("__cxa_increment_exception_refcount",1),fn=ce("__get_exception_message",3),hn=ce("__cxa_can_catch",3),vn=ce("__cxa_get_exception_ptr",1)}var _n={__assert_fail:Gn,__cxa_begin_catch:qn,__cxa_current_primary_exception:Yn,__cxa_end_catch:Xn,__cxa_find_matching_catch_2:Jn,__cxa_find_matching_catch_3:Kn,__cxa_find_matching_catch_4:Qn,__cxa_rethrow:bt,__cxa_rethrow_primary_exception:Zn,__cxa_throw:ei,__cxa_uncaught_exceptions:ri,__resumeException:ti,__syscall_dup3:ui,__syscall_fcntl64:di,__syscall_fstat64:fi,__syscall_ioctl:hi,__syscall_lstat64:vi,__syscall_newfstatat:_i,__syscall_openat:pi,__syscall_stat64:mi,_abort_js:gi,_embind_register_bigint:wi,_embind_register_bool:Ei,_embind_register_class:Li,_embind_register_class_class_function:zi,_embind_register_class_constructor:Hi,_embind_register_class_function:Vi,_embind_register_class_property:Gi,_embind_register_constant:qi,_embind_register_emval:Vt,_embind_register_enum:Xi,_embind_register_enum_value:Ji,_embind_register_float:Qi,_embind_register_function:Zi,_embind_register_integer:eo,_embind_register_memory_view:ro,_embind_register_optional:no,_embind_register_std_string:io,_embind_register_std_wstring:fo,_embind_register_user_type:ho,_embind_register_void:vo,_emscripten_throw_longjmp:_o,_emval_as:po,_emval_as_int64:mo,_emval_call:go,_emval_call_method:wo,_emval_decref:Jr,_emval_get_global:Eo,_emval_get_method_caller:ko,_emval_get_property:Fo,_emval_incref:To,_emval_is_number:Ao,_emval_is_string:Po,_emval_new_array:Co,_emval_new_cstring:xo,_emval_run_destructors:Mo,_emval_take_value:$o,_emval_throw:Ro,_localtime_js:Lo,_mktime_js:Uo,_tzset_js:Bo,clock_time_get:Ho,emscripten_asm_const_int:qo,emscripten_date_now:Kt,emscripten_get_heap_max:Yo,emscripten_get_now:Jt,emscripten_resize_heap:Ko,environ_get:Zo,environ_sizes_get:ea,exit:na,fd_close:ia,fd_read:aa,fd_seek:sa,fd_write:la,invoke_ddd:tc,invoke_dddi:ys,invoke_dddidi:ws,invoke_ddidi:gs,invoke_di:Es,invoke_dii:ls,invoke_diii:za,invoke_diiii:ms,invoke_diiiidd:_s,invoke_diiiidi:Ga,invoke_diiiii:Ia,invoke_diiiiii:Qa,invoke_diiiiiii:bs,invoke_diiiiiiiii:Ja,invoke_diiiiiiiiiiii:Ka,invoke_fiii:hc,invoke_i:Na,invoke_id:Bs,invoke_ii:Ma,invoke_iid:$s,invoke_iidddd:sc,invoke_iidiii:as,invoke_iidiiid:is,invoke_iidiiiiidi:ss,invoke_iif:ac,invoke_iii:Ca,invoke_iiid:cs,invoke_iiididdddddd:os,invoke_iiidiiiiiiii:ns,invoke_iiii:Oa,invoke_iiiidddiiiii:ks,invoke_iiiii:Wa,invoke_iiiiid:zs,invoke_iiiiii:Is,invoke_iiiiiii:Os,invoke_iiiiiiii:Ms,invoke_iiiiiiiidd:Hs,invoke_iiiiiiiii:vs,invoke_iiiiiiiiii:Ds,invoke_iiiiiiiiiidddiiiiiiiii:ts,invoke_iiiiiiiiiii:fc,invoke_iiiiiiiiiiii:vc,invoke_iiiiiiiiiiiii:Xs,invoke_iiij:js,invoke_iiji:Ws,invoke_j:uc,invoke_ji:ec,invoke_jiiii:Ns,invoke_jij:rc,invoke_v:Ra,invoke_vi:$a,invoke_vid:Rs,invoke_viddd:Ls,invoke_vidddd:Us,invoke_vidi:ps,invoke_vidiii:es,invoke_vii:ja,invoke_viid:fs,invoke_viiddi:Ys,invoke_viiddidi:qs,invoke_viiddii:Ss,invoke_viidi:ds,invoke_viidii:Va,invoke_viidiii:Cs,invoke_viidiiid:As,invoke_viidiiiii:rs,invoke_viidiiiiidi:xs,invoke_viidiiiiiiii:Za,invoke_viii:xa,invoke_viiid:Ya,invoke_viiidd:Gs,invoke_viiidi:us,invoke_viiididdddddd:Ps,invoke_viiidiiiiiiii:Ts,invoke_viiii:Ua,invoke_viiiiddd:Vs,invoke_viiiidi:nc,invoke_viiiifi:ic,invoke_viiiii:Da,invoke_viiiiid:qa,invoke_viiiiii:La,invoke_viiiiiii:Ha,invoke_viiiiiiii:hs,invoke_viiiiiiiiii:Qs,invoke_viiiiiiiiiidddiiiiiiiii:Fs,invoke_viiiiiiiiiiid:Xa,invoke_viiiiiiiiiiiii:Ks,invoke_viiiiiiiiiiiiiii:_c,invoke_viiiiiiiiiiiiiiiiii:Zs,invoke_viiiij:cc,invoke_viiij:Ba,invoke_viij:lc,invoke_viijii:dc,invoke_vij:oc,invoke_vijjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj:Js,llvm_eh_typeid_for:ua},Ne=await Wn();function Ca(e,r,t){var n=S();try{return F(e)(r,t)}catch(i){if(b(n),!(i instanceof E))throw i;k(1,0)}}function xa(e,r,t,n){var i=S();try{F(e)(r,t,n)}catch(o){if(b(i),!(o instanceof E))throw o;k(1,0)}}function Ma(e,r){var t=S();try{return F(e)(r)}catch(n){if(b(t),!(n instanceof E))throw n;k(1,0)}}function $a(e,r){var t=S();try{F(e)(r)}catch(n){if(b(t),!(n instanceof E))throw n;k(1,0)}}function Ra(e){var r=S();try{F(e)()}catch(t){if(b(r),!(t instanceof E))throw t;k(1,0)}}function Oa(e,r,t,n){var i=S();try{return F(e)(r,t,n)}catch(o){if(b(i),!(o instanceof E))throw o;k(1,0)}}function Da(e,r,t,n,i,o){var s=S();try{F(e)(r,t,n,i,o)}catch(c){if(b(s),!(c instanceof E))throw c;k(1,0)}}function ja(e,r,t){var n=S();try{F(e)(r,t)}catch(i){if(b(n),!(i instanceof E))throw i;k(1,0)}}function Ia(e,r,t,n,i,o){var s=S();try{return F(e)(r,t,n,i,o)}catch(c){if(b(s),!(c instanceof E))throw c;k(1,0)}}function Na(e){var r=S();try{return F(e)()}catch(t){if(b(r),!(t instanceof E))throw t;k(1,0)}}function La(e,r,t,n,i,o,s){var c=S();try{F(e)(r,t,n,i,o,s)}catch(l){if(b(c),!(l instanceof E))throw l;k(1,0)}}function Ua(e,r,t,n,i){var o=S();try{F(e)(r,t,n,i)}catch(s){if(b(o),!(s instanceof E))throw s;k(1,0)}}function Ba(e,r,t,n,i){var o=S();try{F(e)(r,t,n,i)}catch(s){if(b(o),!(s instanceof E))throw s;k(1,0)}}function Wa(e,r,t,n,i){var o=S();try{return F(e)(r,t,n,i)}catch(s){if(b(o),!(s instanceof E))throw s;k(1,0)}}function za(e,r,t,n){var i=S();try{return F(e)(r,t,n)}catch(o){if(b(i),!(o instanceof E))throw o;k(1,0)}}function Ha(e,r,t,n,i,o,s,c){var l=S();try{F(e)(r,t,n,i,o,s,c)}catch(d){if(b(l),!(d instanceof E))throw d;k(1,0)}}function Va(e,r,t,n,i,o){var s=S();try{F(e)(r,t,n,i,o)}catch(c){if(b(s),!(c instanceof E))throw c;k(1,0)}}function Ga(e,r,t,n,i,o,s){var c=S();try{return F(e)(r,t,n,i,o,s)}catch(l){if(b(c),!(l instanceof E))throw l;k(1,0)}}function qa(e,r,t,n,i,o,s){var c=S();try{F(e)(r,t,n,i,o,s)}catch(l){if(b(c),!(l instanceof E))throw l;k(1,0)}}function Ya(e,r,t,n,i){var o=S();try{F(e)(r,t,n,i)}catch(s){if(b(o),!(s instanceof E))throw s;k(1,0)}}function Xa(e,r,t,n,i,o,s,c,l,d,f,_,g){var p=S();try{F(e)(r,t,n,i,o,s,c,l,d,f,_,g)}catch(w){if(b(p),!(w instanceof E))throw w;k(1,0)}}function Ja(e,r,t,n,i,o,s,c,l,d){var f=S();try{return F(e)(r,t,n,i,o,s,c,l,d)}catch(_){if(b(f),!(_ instanceof E))throw _;k(1,0)}}function Ka(e,r,t,n,i,o,s,c,l,d,f,_,g){var p=S();try{return F(e)(r,t,n,i,o,s,c,l,d,f,_,g)}catch(w){if(b(p),!(w instanceof E))throw w;k(1,0)}}function Qa(e,r,t,n,i,o,s){var c=S();try{return F(e)(r,t,n,i,o,s)}catch(l){if(b(c),!(l instanceof E))throw l;k(1,0)}}function Za(e,r,t,n,i,o,s,c,l,d,f,_){var g=S();try{F(e)(r,t,n,i,o,s,c,l,d,f,_)}catch(p){if(b(g),!(p instanceof E))throw p;k(1,0)}}function es(e,r,t,n,i,o){var s=S();try{F(e)(r,t,n,i,o)}catch(c){if(b(s),!(c instanceof E))throw c;k(1,0)}}function rs(e,r,t,n,i,o,s,c,l){var d=S();try{F(e)(r,t,n,i,o,s,c,l)}catch(f){if(b(d),!(f instanceof E))throw f;k(1,0)}}function ts(e,r,t,n,i,o,s,c,l,d,f,_,g,p,w,M,L,I,V,U,te,ee){var oe=S();try{return F(e)(r,t,n,i,o,s,c,l,d,f,_,g,p,w,M,L,I,V,U,te,ee)}catch(H){if(b(oe),!(H instanceof E))throw H;k(1,0)}}function ns(e,r,t,n,i,o,s,c,l,d,f,_){var g=S();try{return F(e)(r,t,n,i,o,s,c,l,d,f,_)}catch(p){if(b(g),!(p instanceof E))throw p;k(1,0)}}function is(e,r,t,n,i,o,s){var c=S();try{return F(e)(r,t,n,i,o,s)}catch(l){if(b(c),!(l instanceof E))throw l;k(1,0)}}function os(e,r,t,n,i,o,s,c,l,d,f,_){var g=S();try{return F(e)(r,t,n,i,o,s,c,l,d,f,_)}catch(p){if(b(g),!(p instanceof E))throw p;k(1,0)}}function as(e,r,t,n,i,o){var s=S();try{return F(e)(r,t,n,i,o)}catch(c){if(b(s),!(c instanceof E))throw c;k(1,0)}}function ss(e,r,t,n,i,o,s,c,l,d){var f=S();try{return F(e)(r,t,n,i,o,s,c,l,d)}catch(_){if(b(f),!(_ instanceof E))throw _;k(1,0)}}function cs(e,r,t,n){var i=S();try{return F(e)(r,t,n)}catch(o){if(b(i),!(o instanceof E))throw o;k(1,0)}}function ls(e,r,t){var n=S();try{return F(e)(r,t)}catch(i){if(b(n),!(i instanceof E))throw i;k(1,0)}}function us(e,r,t,n,i,o){var s=S();try{F(e)(r,t,n,i,o)}catch(c){if(b(s),!(c instanceof E))throw c;k(1,0)}}function ds(e,r,t,n,i){var o=S();try{F(e)(r,t,n,i)}catch(s){if(b(o),!(s instanceof E))throw s;k(1,0)}}function fs(e,r,t,n){var i=S();try{F(e)(r,t,n)}catch(o){if(b(i),!(o instanceof E))throw o;k(1,0)}}function hs(e,r,t,n,i,o,s,c,l){var d=S();try{F(e)(r,t,n,i,o,s,c,l)}catch(f){if(b(d),!(f instanceof E))throw f;k(1,0)}}function vs(e,r,t,n,i,o,s,c,l){var d=S();try{return F(e)(r,t,n,i,o,s,c,l)}catch(f){if(b(d),!(f instanceof E))throw f;k(1,0)}}function _s(e,r,t,n,i,o,s){var c=S();try{return F(e)(r,t,n,i,o,s)}catch(l){if(b(c),!(l instanceof E))throw l;k(1,0)}}function ps(e,r,t,n){var i=S();try{F(e)(r,t,n)}catch(o){if(b(i),!(o instanceof E))throw o;k(1,0)}}function ms(e,r,t,n,i){var o=S();try{return F(e)(r,t,n,i)}catch(s){if(b(o),!(s instanceof E))throw s;k(1,0)}}function gs(e,r,t,n,i){var o=S();try{return F(e)(r,t,n,i)}catch(s){if(b(o),!(s instanceof E))throw s;k(1,0)}}function ys(e,r,t,n){var i=S();try{return F(e)(r,t,n)}catch(o){if(b(i),!(o instanceof E))throw o;k(1,0)}}function ws(e,r,t,n,i,o){var s=S();try{return F(e)(r,t,n,i,o)}catch(c){if(b(s),!(c instanceof E))throw c;k(1,0)}}function Es(e,r){var t=S();try{return F(e)(r)}catch(n){if(b(t),!(n instanceof E))throw n;k(1,0)}}function bs(e,r,t,n,i,o,s,c){var l=S();try{return F(e)(r,t,n,i,o,s,c)}catch(d){if(b(l),!(d instanceof E))throw d;k(1,0)}}function Ss(e,r,t,n,i,o,s){var c=S();try{F(e)(r,t,n,i,o,s)}catch(l){if(b(c),!(l instanceof E))throw l;k(1,0)}}function ks(e,r,t,n,i,o,s,c,l,d,f,_){var g=S();try{return F(e)(r,t,n,i,o,s,c,l,d,f,_)}catch(p){if(b(g),!(p instanceof E))throw p;k(1,0)}}function Fs(e,r,t,n,i,o,s,c,l,d,f,_,g,p,w,M,L,I,V,U,te,ee,oe){var H=S();try{F(e)(r,t,n,i,o,s,c,l,d,f,_,g,p,w,M,L,I,V,U,te,ee,oe)}catch(Le){if(b(H),!(Le instanceof E))throw Le;k(1,0)}}function Ts(e,r,t,n,i,o,s,c,l,d,f,_,g){var p=S();try{F(e)(r,t,n,i,o,s,c,l,d,f,_,g)}catch(w){if(b(p),!(w instanceof E))throw w;k(1,0)}}function As(e,r,t,n,i,o,s,c){var l=S();try{F(e)(r,t,n,i,o,s,c)}catch(d){if(b(l),!(d instanceof E))throw d;k(1,0)}}function Ps(e,r,t,n,i,o,s,c,l,d,f,_,g){var p=S();try{F(e)(r,t,n,i,o,s,c,l,d,f,_,g)}catch(w){if(b(p),!(w instanceof E))throw w;k(1,0)}}function Cs(e,r,t,n,i,o,s){var c=S();try{F(e)(r,t,n,i,o,s)}catch(l){if(b(c),!(l instanceof E))throw l;k(1,0)}}function xs(e,r,t,n,i,o,s,c,l,d,f){var _=S();try{F(e)(r,t,n,i,o,s,c,l,d,f)}catch(g){if(b(_),!(g instanceof E))throw g;k(1,0)}}function Ms(e,r,t,n,i,o,s,c){var l=S();try{return F(e)(r,t,n,i,o,s,c)}catch(d){if(b(l),!(d instanceof E))throw d;k(1,0)}}function $s(e,r,t){var n=S();try{return F(e)(r,t)}catch(i){if(b(n),!(i instanceof E))throw i;k(1,0)}}function Rs(e,r,t){var n=S();try{F(e)(r,t)}catch(i){if(b(n),!(i instanceof E))throw i;k(1,0)}}function Os(e,r,t,n,i,o,s){var c=S();try{return F(e)(r,t,n,i,o,s)}catch(l){if(b(c),!(l instanceof E))throw l;k(1,0)}}function Ds(e,r,t,n,i,o,s,c,l,d){var f=S();try{return F(e)(r,t,n,i,o,s,c,l,d)}catch(_){if(b(f),!(_ instanceof E))throw _;k(1,0)}}function js(e,r,t,n){var i=S();try{return F(e)(r,t,n)}catch(o){if(b(i),!(o instanceof E))throw o;k(1,0)}}function Is(e,r,t,n,i,o){var s=S();try{return F(e)(r,t,n,i,o)}catch(c){if(b(s),!(c instanceof E))throw c;k(1,0)}}function Ns(e,r,t,n,i){var o=S();try{return F(e)(r,t,n,i)}catch(s){if(b(o),!(s instanceof E))throw s;return k(1,0),0n}}function Ls(e,r,t,n,i){var o=S();try{F(e)(r,t,n,i)}catch(s){if(b(o),!(s instanceof E))throw s;k(1,0)}}function Us(e,r,t,n,i,o){var s=S();try{F(e)(r,t,n,i,o)}catch(c){if(b(s),!(c instanceof E))throw c;k(1,0)}}function Bs(e,r){var t=S();try{return F(e)(r)}catch(n){if(b(t),!(n instanceof E))throw n;k(1,0)}}function Ws(e,r,t,n){var i=S();try{return F(e)(r,t,n)}catch(o){if(b(i),!(o instanceof E))throw o;k(1,0)}}function zs(e,r,t,n,i,o){var s=S();try{return F(e)(r,t,n,i,o)}catch(c){if(b(s),!(c instanceof E))throw c;k(1,0)}}function Hs(e,r,t,n,i,o,s,c,l,d){var f=S();try{return F(e)(r,t,n,i,o,s,c,l,d)}catch(_){if(b(f),!(_ instanceof E))throw _;k(1,0)}}function Vs(e,r,t,n,i,o,s,c){var l=S();try{F(e)(r,t,n,i,o,s,c)}catch(d){if(b(l),!(d instanceof E))throw d;k(1,0)}}function Gs(e,r,t,n,i,o){var s=S();try{F(e)(r,t,n,i,o)}catch(c){if(b(s),!(c instanceof E))throw c;k(1,0)}}function qs(e,r,t,n,i,o,s,c){var l=S();try{F(e)(r,t,n,i,o,s,c)}catch(d){if(b(l),!(d instanceof E))throw d;k(1,0)}}function Ys(e,r,t,n,i,o){var s=S();try{F(e)(r,t,n,i,o)}catch(c){if(b(s),!(c instanceof E))throw c;k(1,0)}}function Xs(e,r,t,n,i,o,s,c,l,d,f,_,g){var p=S();try{return F(e)(r,t,n,i,o,s,c,l,d,f,_,g)}catch(w){if(b(p),!(w instanceof E))throw w;k(1,0)}}function Js(e,r,t,n,i,o,s,c,l,d,f,_,g,p,w,M,L,I,V,U,te,ee,oe,H,Le,yc,wc,Ec,bc,Sc,kc,Fc,Tc,Ac,Pc,Cc,xc,Mc,$c,Rc,Oc,Dc,jc,Ic,Nc,Lc,Uc,Bc,Wc,zc,Hc,Vc,Gc,qc,Yc,Xc,Jc,Kc,Qc,Zc,el,rl,tl,nl,il,ol,al,sl,cl,ll,ul,dl,fl,hl,vl,_l,pl,ml,gl,yl,wl,El,bl,Sl,kl){var Fl=S();try{F(e)(r,t,n,i,o,s,c,l,d,f,_,g,p,w,M,L,I,V,U,te,ee,oe,H,Le,yc,wc,Ec,bc,Sc,kc,Fc,Tc,Ac,Pc,Cc,xc,Mc,$c,Rc,Oc,Dc,jc,Ic,Nc,Lc,Uc,Bc,Wc,zc,Hc,Vc,Gc,qc,Yc,Xc,Jc,Kc,Qc,Zc,el,rl,tl,nl,il,ol,al,sl,cl,ll,ul,dl,fl,hl,vl,_l,pl,ml,gl,yl,wl,El,bl,Sl,kl)}catch(mn){if(b(Fl),!(mn instanceof E))throw mn;k(1,0)}}function Ks(e,r,t,n,i,o,s,c,l,d,f,_,g,p){var w=S();try{F(e)(r,t,n,i,o,s,c,l,d,f,_,g,p)}catch(M){if(b(w),!(M instanceof E))throw M;k(1,0)}}function Qs(e,r,t,n,i,o,s,c,l,d,f){var _=S();try{F(e)(r,t,n,i,o,s,c,l,d,f)}catch(g){if(b(_),!(g instanceof E))throw g;k(1,0)}}function Zs(e,r,t,n,i,o,s,c,l,d,f,_,g,p,w,M,L,I,V){var U=S();try{F(e)(r,t,n,i,o,s,c,l,d,f,_,g,p,w,M,L,I,V)}catch(te){if(b(U),!(te instanceof E))throw te;k(1,0)}}function ec(e,r){var t=S();try{return F(e)(r)}catch(n){if(b(t),!(n instanceof E))throw n;return k(1,0),0n}}function rc(e,r,t){var n=S();try{return F(e)(r,t)}catch(i){if(b(n),!(i instanceof E))throw i;return k(1,0),0n}}function tc(e,r,t){var n=S();try{return F(e)(r,t)}catch(i){if(b(n),!(i instanceof E))throw i;k(1,0)}}function nc(e,r,t,n,i,o,s){var c=S();try{F(e)(r,t,n,i,o,s)}catch(l){if(b(c),!(l instanceof E))throw l;k(1,0)}}function ic(e,r,t,n,i,o,s){var c=S();try{F(e)(r,t,n,i,o,s)}catch(l){if(b(c),!(l instanceof E))throw l;k(1,0)}}function oc(e,r,t){var n=S();try{F(e)(r,t)}catch(i){if(b(n),!(i instanceof E))throw i;k(1,0)}}function ac(e,r,t){var n=S();try{return F(e)(r,t)}catch(i){if(b(n),!(i instanceof E))throw i;k(1,0)}}function sc(e,r,t,n,i,o){var s=S();try{return F(e)(r,t,n,i,o)}catch(c){if(b(s),!(c instanceof E))throw c;k(1,0)}}function cc(e,r,t,n,i,o){var s=S();try{F(e)(r,t,n,i,o)}catch(c){if(b(s),!(c instanceof E))throw c;k(1,0)}}function lc(e,r,t,n){var i=S();try{F(e)(r,t,n)}catch(o){if(b(i),!(o instanceof E))throw o;k(1,0)}}function uc(e){var r=S();try{return F(e)()}catch(t){if(b(r),!(t instanceof E))throw t;return k(1,0),0n}}function dc(e,r,t,n,i,o){var s=S();try{F(e)(r,t,n,i,o)}catch(c){if(b(s),!(c instanceof E))throw c;k(1,0)}}function fc(e,r,t,n,i,o,s,c,l,d,f){var _=S();try{return F(e)(r,t,n,i,o,s,c,l,d,f)}catch(g){if(b(_),!(g instanceof E))throw g;k(1,0)}}function hc(e,r,t,n){var i=S();try{return F(e)(r,t,n)}catch(o){if(b(i),!(o instanceof E))throw o;k(1,0)}}function vc(e,r,t,n,i,o,s,c,l,d,f,_){var g=S();try{return F(e)(r,t,n,i,o,s,c,l,d,f,_)}catch(p){if(b(g),!(p instanceof E))throw p;k(1,0)}}function _c(e,r,t,n,i,o,s,c,l,d,f,_,g,p,w,M){var L=S();try{F(e)(r,t,n,i,o,s,c,l,d,f,_,g,p,w,M)}catch(I){if(b(L),!(I instanceof E))throw I;k(1,0)}}var pn;function pc(){cn(),Cn()}function it(){if($e>0){tr=it;return}if(pc(),Rn(),$e>0){tr=it;return}function e(){T(!pn),pn=!0,u.calledRun=!0,!Ke&&(On(),vt?.(u),u.onRuntimeInitialized?.(),dr("onRuntimeInitialized"),T(!u._main,'compiled without a main, but one is present. if you added it from JS, use Module["onRuntimeInitialized"]'),Dn())}u.setStatus?(u.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>u.setStatus(""),1),e()},1)):e(),jr()}function mc(){var e=G,r=x,t=!1;G=x=n=>{t=!0};try{rt(0),["stdout","stderr"].forEach(n=>{var i=a.analyzePath("/dev/"+n);if(i){var o=i.object,s=o.rdev,c=Te.ttys[s];c?.output?.length&&(t=!0)}})}catch{}G=e,x=r,t&&Pe("stdio streams had content in them that was not flushed. you should set EXIT_RUNTIME to 1 (see the Emscripten FAQ), or make sure to emit a newline when you printf etc.")}function gc(){if(u.preInit)for(typeof u.preInit=="function"&&(u.preInit=[u.preInit]);u.preInit.length>0;)u.preInit.shift()();dr("preInit")}gc(),it(),rr?h=u:h=new Promise((e,r)=>{vt=e,Nr=r});for(let e of Object.keys(u))e in y||Object.defineProperty(y,e,{configurable:!0,get(){K(`Access to module property ('${e}') is no longer possible via the module constructor argument; Instead, use the result of the module constructor.`)}});return h}),gn=Tl;var cr=(y,h,u)=>Math.max(h,Math.min(u,y));function Ce(y,h,u){if(!Array.isArray(y)||y.length!==h||!y.every(Number.isFinite))throw new Error(`${u} must contain ${h} finite numbers`);return y.slice()}function ot(y,h){let u=Ce(y,3,"Target");if(u.some((v,m)=>vh[m][1]))throw new Error("Target is outside the workstation workspace");return u}function yn(y,h){let u=Math.hypot(...y);return u>h?y.map(v=>v*h/u):y.slice()}function Al(y,h){let u=h.length,v=y.map((m,A)=>[...m,h[A]]);for(let m=0;mMath.abs(v[A][m])&&(A=P);if(!Number.isFinite(v[A][m])||Math.abs(v[A][m])<1e-14)throw new Error("Controller solve is singular");[v[m],v[A]]=[v[A],v[m]];let O=v[m][m];for(let P=m;P<=u;P+=1)v[m][P]/=O;for(let P=0;Pm[u])}function wn({jacp:y,jacr:h,nv:u,dofIds:v,qpos:m,qposIds:A,target:O,current:P,rotationWorld:D,ctrlRange:B,config:$}){let W=yn(O.map((ie,G)=>ie-P[G]),$.translation_error_cap_m),Y=yn(D,$.rotation_error_cap_rad),we=$.orientation_weight,re=Array.from({length:6},(ie,G)=>v.map(x=>G<3?y[G*u+x]:we*h[(G-3)*u+x])),se=[...W,...Y.map(ie=>ie*we)],xe=re.map((ie,G)=>re.map((x,he)=>ie.reduce((ue,be,Ae)=>ue+be*x[Ae],0)+(G===he?$.damping**2:0))),Ee=Al(xe,se);return v.map((ie,G)=>{let x=re.reduce((ue,be,Ae)=>ue+be[G]*Ee[Ae],0),he=cr(m[A[G]]+cr(x,-$.max_joint_delta_rad,$.max_joint_delta_rad),B[G][0]+$.joint_margin_rad,B[G][1]-$.joint_margin_rad);if(!Number.isFinite(he))throw new Error("Controller produced a non-finite target");return he})}var lr=class{constructor(h=2048){this.capacity=h,this.values=[],this.index=0}add(h){Number.isFinite(h)&&(this.values.lengthv-m);return u[Math.min(u.length-1,Math.floor(h*(u.length-1)))]}};function Ue(y,h){if(typeof y!="string"||y.length>1024||y.startsWith("/")||y.split("/").some(v=>v==="..")||y.includes("\\"))throw new Error("Invalid local asset path");let u=new URL(y,h);if(u.origin!==h.origin||!["http:","https:"].includes(u.protocol))throw new Error("Workstation resources must be same-origin HTTP assets");return u}function Xe(y,h=67108864){if(!y||!Number.isSafeInteger(y.bytes)||y.bytes<0||y.bytes>h||typeof y.sha256!="string"||!/^[a-f0-9]{64}$/.test(y.sha256))throw new Error("Asset size or digest descriptor mismatch")}async function Or(y,h){if(Xe(h),y.length!==h.bytes)throw new Error("Asset size mismatch");if(Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",y)),v=>v.toString(16).padStart(2,"0")).join("")!==h.sha256)throw new Error("Asset checksum mismatch")}async function Pl(y,h){if(!y)throw new Error("Streaming resource responses are required");if(!Number.isSafeInteger(h)||h<0||h>201326592)throw new Error("Invalid resource limit");let u=y.getReader(),v=[],m=0;try{for(;;){let{done:P,value:D}=await u.read();if(P)break;if(m+=D.byteLength,m>h)throw await u.cancel(),new Error("Resource is too large");v.push(D)}}finally{u.releaseLock()}let A=new Uint8Array(m),O=0;for(let P of v)A.set(P,O),O+=P.byteLength;return A}var En="dvidia-robot-simulation-lab.static.hf.space",Cl="us.aws.cdn.hf.co",xl=new Set([408,429,502,503,504]),Ml=Object.freeze({"geometry.bin.gz":{bytes:3574720,sha256:"51365a5a661d8062e28c66abc6bdb843ee410811f84b49d62c5878c265b3631f"},"native-assets.bin.gz":{bytes:7318481,sha256:"9c960598f9b2c0c7459a8bdfc8a544513b4c6ffaff2c8787fa49f728774eb9e7"},"mujoco.wasm.gz":{bytes:2543112,sha256:"ad01772e00939bf6300a953b396d38aa9ec03c05fcda46c3c8d940d56f772b3b"}});function $l(y,h){if(y.protocol!=="https:"||y.host!==En||y.search||y.hash||!h)return null;let u=y.pathname.split("/").pop(),v=Ml[u];return!v||y.pathname!=="/workstation/v01/"+u||h.bytes!==v.bytes||h.sha256!==v.sha256?null:new URL("https://research.dvidia.org/runtime/workstation/"+v.sha256+"/"+u)}var le=class extends Error{constructor(h,u=!1){super(h),this.name="ResourceDownloadError",this.retryable=u}};function Rl(y,h){let u={maxBytes:h?.bytes??67108864,idleTimeoutMs:3e4,timeoutMs:12e4,maxAttempts:3,retryDelayMs:250,...y};for(let[v,m,A]of[["maxBytes",67108864,0],["idleTimeoutMs",12e4,1],["timeoutMs",12e4,1],["maxAttempts",3,1],["retryDelayMs",2e3,0]])if(!Number.isSafeInteger(u[v])||u[v]m)throw new Error(`Invalid resource transport option: ${v}`);if(h&&u.maxBytes{u=()=>A(h.reason),h.addEventListener("abort",u,{once:!0})});try{return await Promise.race([y,v])}finally{h.removeEventListener("abort",u)}}async function Ol(y,h,u,v){if(!y)throw new le("The server returned an empty resource");let m=y.getReader(),A=[],O=0,P=!1;try{for(;;){let $;try{$=await bn(m.read(),u)}catch(W){throw u.aborted?u.reason:new le(`Body download interrupted: ${W.message||"network error"}`,!0)}if($.done){P=!0;break}if(O+=$.value.byteLength,O>h)throw new le("Resource is too large");A.push($.value),$.value.byteLength&&v(O)}}finally{P||m.cancel().catch(()=>{}),m.releaseLock()}let D=new Uint8Array(O),B=0;for(let $ of A)D.set($,B),B+=$.byteLength;return D}async function Be(y,h,u={}){h&&Xe(h);let v=Rl(u,h),m=new URL(y);if(!["http:","https:"].includes(m.protocol)||m.username||m.password)throw new Error("Invalid resource URL");let A=m.protocol==="https:"&&m.host===En,O=$l(m,h),P=performance.now()+v.timeoutMs,D=m.pathname.split("/").pop()||"resource",B=h?.bytes??null,$=(Y,we,re=0)=>v.onProgress?.({path:m.pathname,phase:Y,attempt:we,receivedBytes:re,totalBytes:B}),W=()=>new le("Total download deadline exceeded");for(let Y=1;Y<=v.maxAttempts;Y+=1){let we=P-performance.now();if(we<=0)throw new Error(`Could not download ${D}: total download deadline exceeded`);let re=new AbortController,se=O!==null&&Y===1,xe=se?O:m,Ee=setTimeout(()=>re.abort(W()),we),ie,G=()=>{clearTimeout(ie),ie=setTimeout(()=>re.abort(new le("Download stalled without receiving data",!0)),v.idleTimeoutMs)};try{B=h?.bytes??null,$("downloading",Y),G();let x;try{x=await bn(fetch(xe,{credentials:"omit",referrerPolicy:"no-referrer",redirect:se?"manual":A?"follow":"error",signal:re.signal,...Y>1?{cache:"reload"}:{}}),re.signal)}catch(ur){throw re.signal.aborted?re.signal.reason:new le(`Network request failed: ${ur.message||"network error"}`,!0)}if(G(),se&&(x.type==="opaqueredirect"||x.redirected||x.status>=300&&x.status<400))throw x.body?.cancel().catch(()=>{}),new le("The pinned workstation mirror may not redirect");let he=new URL(x.url);if(se?he.href!==xe.href:he.origin!==m.origin&&!(A&&he.protocol==="https:"&&he.host===Cl))throw x.body?.cancel().catch(()=>{}),new le("Resource redirected outside the permitted workstation host");if(!x.ok)throw x.body?.cancel().catch(()=>{}),new le(`HTTP ${x.status}`,xl.has(x.status)||se&&[404,410].includes(x.status));if(Number(x.headers.get("content-length"))>v.maxBytes)throw x.body?.cancel().catch(()=>{}),new le("Resource is too large");let ue=x.headers.get("content-length"),be=x.headers.get("content-encoding");!h&&(!be||be==="identity")&&/^\d+$/.test(ue??"")&&Number.isSafeInteger(Number(ue))&&Number(ue)<=v.maxBytes&&(B=Number(ue),$("downloading",Y));let Ae=await Ol(x.body,h?.bytes??v.maxBytes,re.signal,ur=>{G(),$("downloading",Y,ur)});return h&&await Or(Ae,h),$("complete",Y,Ae.byteLength),Ae}catch(x){if(!(x instanceof le&&x.retryable&&YsetTimeout(be,ue))}finally{clearTimeout(Ee),clearTimeout(ie)}}}function Sn(y){if(!Array.isArray(y)||y.length>256)throw new Error("Invalid asset manifest");let h=0,u=new Set;for(let v of y){if(Xe(v),u.has(v.path))throw new Error("Duplicate native asset path");if(u.add(v.path),h+=v.bytes,h>201326592)throw new Error("Scene assets exceed worker memory budget")}return h}function kn(y,h){Xe(y);let u=Sn(h);if(y.compression!=="gzip"||y.path!=="native-assets.bin.gz"||!Number.isSafeInteger(y.uncompressed_bytes)||y.uncompressed_bytes!==u)throw new Error("Invalid native asset bundle descriptor");return u}async function Fn(y,h,u){try{let v=new Blob([y]).stream().pipeThrough(new DecompressionStream("gzip"));return await Pl(v,h)}catch(v){throw new Error(`Could not decode ${u}: ${v.message}`)}}async function Dl(y,h,u){let v=kn(h,u);await Or(y,h);let m=await Fn(y,v,h.path);if(m.byteLength!==v)throw new Error("Native asset bundle is truncated");let A=[],O=0;for(let P of u){let D=m.subarray(O,O+P.bytes);await Or(D,P),A.push({path:P.path,bytes:D}),O+=P.bytes}return A}async function Tn(y,h,u={}){Sn(y.assets);for(let m of y.assets)Ue(m.path,h);if(y.native_asset_bundle!==void 0){let m=y.native_asset_bundle;kn(m,y.assets);let A=await Be(Ue(m.path,h),m,u);return Dl(A,m,y.assets)}let v=[];for(let m of y.assets)v.push({path:m.path,bytes:await Be(Ue(m.path,h),m,u)});return v}async function An(y,h,u={}){let v=y.native_wasm;if(v!==void 0&&(Xe(v),v.path!=="mujoco.wasm"))throw new Error("Invalid native WASM descriptor");let m=y.wasm_bundle;if(m===void 0)return Be(Ue("mujoco.wasm",h),v,u);if(Xe(m),!v||m.path!=="mujoco.wasm.gz"||m.compression!=="gzip"||!Number.isSafeInteger(m.uncompressed_bytes)||m.uncompressed_bytes!==v.bytes)throw new Error("Invalid WASM bundle descriptor");let A=await Be(Ue(m.path,h),m,u),O=await Fn(A,v.bytes,m.path);try{await Or(O,v)}catch(P){throw new Error(`Decoded ${v.path} from ${m.path}: ${P.message}`)}return O}var Dr="3.15.0",jl=256,Il=.1,Nl=50,Ll=1e3/60;function Pn(y){if(!y||y.schema!=="dvidia.live-workstation/v1")throw new Error("Unsupported workstation schema");if(y.native_version!==Dr)throw new Error("Native and browser MuJoCo versions must match");if(y.timestep!==.002||y.control_dt!==.02)throw new Error("Unsupported physics/control timestep");if(!Array.isArray(y.assets)||y.assets.length>jl)throw new Error("Invalid asset manifest");if(!Array.isArray(y.bounds_xyz)||y.bounds_xyz.length!==3)throw new Error("Invalid workspace bounds");for(let m of y.bounds_xyz)if(Ce(m,2,"Workspace bounds"),m[0]>=m[1]||m[0]<-2||m[1]>2)throw new Error("Invalid workspace bounds");ot(y.initial_target_xyz,y.bounds_xyz);let h=Ce(y.orientation_wxyz,4,"Tool orientation");if(Math.abs(Math.hypot(...h)-1)>1e-8)throw new Error("Tool orientation must be normalized");for(let m of["joint_names","actuator_names"])if(!Array.isArray(y[m])||y[m].length!==6||!y[m].every(A=>typeof A=="string"&&A.length<100))throw new Error(`Invalid ${m}`);let u=y.controller;for(let m of["orientation_weight","translation_error_cap_m","rotation_error_cap_rad","damping","max_joint_delta_rad","joint_margin_rad","joint_rate_rad_s","gripper_rate_m_s"])if(!Number.isFinite(u?.[m])||u[m]<=0||u[m]>5)throw new Error(`Invalid controller ${m}`);if(Ce(u.gripper_range_m,2,"Gripper range"),u.gripper_range_m[0]!==0||u.gripper_range_m[1]!==.035)throw new Error("Unsupported gripper range");if(!Array.isArray(y.shoe_body_names)||y.shoe_body_names.length>12)throw new Error("Invalid shoe body list");let v=y.interaction_limits?.push_impulse_norm_max_ns;if(!Number.isFinite(v)||v<=0||v>.12)throw new Error("Invalid push impulse limit");return y}var st=class{constructor(h,u,v,m=()=>{}){if(this.mj=h,this.model=u,this.manifest=Pn(v),this.emit=m,u.nq!==15||u.nv!==14||u.nu!==7||u.neq!==1||u.nmocap!==0||u.opt.timestep!==v.timestep)throw new Error("Native PiPER scene contract mismatch");this.data=new h.MjData(u),this.buffers=[];let A=P=>{let D=new h.DoubleBuffer(P);return this.buffers.push(D),D};this.jacp=A(3*u.nv),this.jacr=A(3*u.nv),this.quaternion=A(4),this.rotation=A(3),this.contactForce=A(6);let O=(P,D)=>{let B=h.mj_name2id(u,h.mjtObj[P].value,D);if(B<0)throw new Error(`Missing native model element: ${D}`);return B};this.tcp=O("mjOBJ_SITE",v.tcp_site_name),this.joints=v.joint_names.map(P=>O("mjOBJ_JOINT",P)),this.actuators=v.actuator_names.map(P=>O("mjOBJ_ACTUATOR",P)),this.jawActuator=O("mjOBJ_ACTUATOR",v.gripper_actuator_names[0]),this.jawQpos=u.jnt_qposadr[O("mjOBJ_JOINT","joint7")],this.qposIds=this.joints.map(P=>u.jnt_qposadr[P]),this.dofIds=this.joints.map(P=>u.jnt_dofadr[P]),this.ctrlRange=this.actuators.map(P=>Array.from(u.actuator_ctrlrange.slice(P*2,P*2+2))),this.shoes=Object.fromEntries(v.shoe_body_names.map(P=>[P,O("mjOBJ_BODY",P)])),this.nativeWarnings=this.data.warning,this.nativeWarningEntries=Array.from({length:this.nativeWarnings.size()},(P,D)=>this.nativeWarnings.get(D)),this.dt=v.timestep,this.controlStride=Math.round(v.control_dt/this.dt),this.running=!0,this.benchmarking=!1,this.timer=null,this.statePending=!1,this.reset()}reset(){this.mj.mj_resetData(this.model,this.data);let h=Ce(this.manifest.home_qpos,this.model.nq,"Initial positions"),u=Ce(this.manifest.home_ctrl,this.model.nu,"Initial controls");this.data.qpos.set(h),this.data.ctrl.set(u),this.mj.mj_forward(this.model,this.data),this.target=this.manifest.initial_target_xyz.slice(),this.jaw=u[this.jawActuator],this.desiredJaw=this.jaw,this.desired=this.actuators.map(v=>u[v]),this.steps=0,this.pushes=new Map,this.warnings=[],this.stepSamples=new lr,this.controlSamples=new lr,this.startWall=performance.now(),this.lastWall=this.startWall,this.lastStateWall=0,this.activeWallMs=0,this.lagMs=0,this.accumulator=0,this.peakContacts=0,this.invalidCommands=0,this.statePending=!1,this.initialShoePositions=Object.fromEntries(Object.entries(this.shoes).map(([v,m])=>[v,Array.from(this.data.xpos.slice(3*m,3*m+3))]))}controller(){let h=performance.now(),u=Array.from(this.data.site_xmat.slice(this.tcp*9,this.tcp*9+9));this.mj.mj_jacSite(this.model,this.data,this.jacp,this.jacr,this.tcp),this.mj.mju_mat2Quat(this.quaternion,u),this.mj.mju_subQuat(this.rotation,this.manifest.orientation_wxyz,Array.from(this.quaternion.GetView()));let v=this.rotation.GetView(),m=[0,1,2].map(A=>u[A*3]*v[0]+u[A*3+1]*v[1]+u[A*3+2]*v[2]);this.desired=wn({jacp:this.jacp.GetView(),jacr:this.jacr.GetView(),nv:this.model.nv,dofIds:this.dofIds,qpos:this.data.qpos,qposIds:this.qposIds,target:this.target,current:this.data.site_xpos.slice(this.tcp*3,this.tcp*3+3),rotationWorld:m,ctrlRange:this.ctrlRange,config:this.manifest.controller}),this.desiredJaw=this.jaw,this.controlSamples.add(performance.now()-h)}step(){let h=performance.now();this.steps%this.controlStride===0&&this.controller();let u=this.manifest.controller,v=this.data.ctrl;this.actuators.forEach((m,A)=>{v[m]+=cr(this.desired[A]-v[m],-u.joint_rate_rad_s*this.dt,u.joint_rate_rad_s*this.dt)}),v[this.jawActuator]+=cr(this.desiredJaw-v[this.jawActuator],-u.gripper_rate_m_s*this.dt,u.gripper_rate_m_s*this.dt),this.data.xfrc_applied.fill(0);for(let[m,A]of this.pushes)A.remainingSteps<=0?this.pushes.delete(m):(this.data.xfrc_applied.set(A.force,m*6),A.remainingSteps-=1);if(this.mj.mj_step(this.model,this.data),this.data.xfrc_applied.fill(0),this.mj.mj_forward(this.model,this.data),this.steps+=1,this.peakContacts=Math.max(this.peakContacts,this.data.ncon),![...this.data.qpos,...this.data.qvel,...this.data.qacc,...this.data.ctrl].every(Number.isFinite))throw new Error("Non-finite native physics state; simulation paused");this.checkWarnings(),this.stepSamples.add(performance.now()-h)}checkWarnings(){for(let h=0;h0){let v=this.mj.mju_warningText(h,u.lastinfo);this.warnings.includes(v)||this.warnings.push(v)}}if(this.warnings.length)throw new Error(`Native solver warning; simulation paused: ${this.warnings[0]}`)}applyCommand(h){switch(h.type){case"target":this.target=ot(h.position,this.manifest.bounds_xyz);break;case"gripper":{let u=this.manifest.controller.gripper_range_m;if(!Number.isFinite(h.jaw)||h.jawu[1])throw new Error("Invalid gripper position");this.jaw=h.jaw;break}case"pause":if(typeof h.paused!="boolean")throw new Error("Pause requires a boolean");this.running=!h.paused,this.lastWall=performance.now(),this.accumulator=0;break;case"reset":this.reset();break;case"push":{let u=this.shoes[h.body];if(u===void 0)throw new Error("Push is restricted to a named shoe");let v=Ce(h.impulse,3,"Push impulse"),m=this.manifest.interaction_limits.push_impulse_norm_max_ns;if(Math.hypot(...v)>m+1e-9)throw new Error(`Push exceeds the ${m} N·s impulse limit`);this.pushes.set(u,{force:v.map(A=>A/this.dt),remainingSteps:1});break}default:throw new Error(`Unsupported command: ${String(h.type).slice(0,60)}`)}}state(){let h=Array.from(this.data.site_xpos.slice(this.tcp*3,this.tcp*3+3)),u=Object.fromEntries(Object.entries(this.shoes).map(([P,D])=>{let B=Array.from(this.data.xpos.slice(D*3,D*3+3));return[P,{position:B,height_change_m:B[2]-this.initialShoePositions[P][2]}]})),v=0,m=0,A=0,O=[];for(let P=0;P.001)}return{body_pos:Array.from(this.data.xpos),body_quat:Array.from(this.data.xquat),qpos:Array.from(this.data.qpos),qvel:Array.from(this.data.qvel),ctrl:Array.from(this.data.ctrl),tcp_position:h,target_position:this.target.slice(),jaw:this.jaw,actual_jaw:this.data.qpos[this.jawQpos],commanded_jaw:this.data.ctrl[this.jawActuator],sim_time:this.data.time,paused:!this.running,tracking_error_m:Math.hypot(...h.map((P,D)=>P-this.target[D])),contacts:this.data.ncon,contact_normal_force_total_n:v,contact_normal_force_max_n:m,shoes:u,active_contacts:A,contact_normal_forces_n:O,actuator_force:Array.from(this.data.actuator_force),metrics:{step_ms_p50:this.stepSamples.quantile(.5),step_ms_p95:this.stepSamples.quantile(.95),control_ms_p95:this.controlSamples.quantile(.95),rtf:this.activeWallMs>0?this.data.time*1e3/this.activeWallMs:0,lag_ms:this.lagMs,physics_steps:this.steps,active_wall_ms:this.activeWallMs,peak_contacts:this.peakContacts,invalid_commands:this.invalidCommands,samples_retained:this.stepSamples.values.length},warnings:this.warnings.slice(),engine:`MuJoCo ${Dr} WASM`,observation_origin:"privileged_live_simulator_state"}}start(){let h=()=>{let u=performance.now(),v=Math.max(0,(u-this.lastWall)/1e3);if(this.lastWall=u,this.running&&!this.benchmarking){this.activeWallMs+=v*1e3;let m=this.accumulator+v;this.accumulator=Math.min(m,Il),this.lagMs+=Math.max(0,m-this.accumulator)*1e3;let A=0;try{for(;this.accumulator>=this.dt&&A=Ll&&!this.benchmarking&&!this.statePending&&(this.publishState(),this.lastStateWall=u),this.timer=setTimeout(h,4)};this.lastWall=performance.now(),this.timer=setTimeout(h,0)}publishState(){this.statePending||(this.statePending=!0,this.emit({type:"state",state:this.state()}))}async benchmark(h){if(!Number.isInteger(h.steps)||h.steps<1||h.steps>3e4)throw new Error("Benchmark requires 1–30,000 physics steps");let u=h.commands??[];if(!Array.isArray(u)||u.length>1e3)throw new Error("Too many benchmark commands");if(u.some($=>!Number.isInteger($.step)||$.step<0||$.step>=h.steps||!["target","gripper","push"].includes($.type)))throw new Error("Invalid benchmark schedule");let v=this.running;this.benchmarking=!0,this.reset(),this.running=!1;let m=performance.now(),A=null,O=new Map;for(let $ of u)O.set($.step,[...O.get($.step)??[],$]);let P=[];try{for(let $=0;$setTimeout(W,0))}}catch($){A=$.message}let D=performance.now()-m;this.activeWallMs=D;let B=this.state();return this.benchmarking=!1,this.running=v&&!A,this.lastWall=performance.now(),this.accumulator=0,this.statePending=!1,{schema:"dvidia.live-workstation-benchmark/v1",engine_version:Dr,requested_steps:h.steps,completed_steps:this.steps,simulated_seconds:this.data.time,wall_seconds:D/1e3,real_time_factor:this.data.time*1e3/D,valid:!A&&!this.warnings.length,error:A,final_state:B,trace:P,timestep:this.dt,control_dt:this.manifest.control_dt,scene_sha256:this.manifest.native_scene.sha256,limitations:["Rigid synthetic shoe; material properties are uncalibrated.","Benchmark state is privileged simulator state."]}}dispose(){this.timer!==null&&clearTimeout(this.timer);for(let h of this.buffers)h.delete();this.data.delete(),this.model.delete()}},ne=null,at=!1;async function Ul(y){if(ne||at)throw new Error("The worker has already been initialized");at=!0;let h=null,u=null;try{let v=new URL(y.manifest_url,self.location.href);if(v.origin!==self.location.origin||!["http:","https:"].includes(v.protocol))throw new Error("Manifest must be same-origin");let m=await Be(v,void 0,{maxBytes:2*1024*1024});if(m.length>2*1024*1024)throw new Error("Manifest is too large");let A=Pn(JSON.parse(new TextDecoder().decode(m)));if(!A.native_scene||A.native_scene.path!==A.scene_url)throw new Error("Scene checksum descriptor is missing");self.postMessage({type:"progress",message:A.native_asset_bundle?"Loading the physics engine and one compressed native mesh bundle.":"Loading the physics engine and original native meshes."});let O={onProgress:W=>self.postMessage({type:"progress",download:W})},[P,D,B]=await Promise.all([An(A,v,O),Tn(A,v,O),Be(Ue(A.scene_url,v),A.native_scene,O)]),$=await gn({wasmBinary:P,printErr:W=>{ne&&ne.warnings.length<20&&ne.warnings.push(String(W).slice(0,300))}});if($.mj_versionString()!==Dr)throw new Error("Unexpected MuJoCo WASM version");self.postMessage({type:"progress",message:"Native mesh checksums verified. Compiling the local physics scene."}),u=new $.MjVFS;for(let W of D)u.addBuffer(W.path,W.bytes);h=$.MjModel.from_xml_string(new TextDecoder().decode(B),u),ne=new st($,h,A,W=>self.postMessage(W)),h=null,self.postMessage({type:"ready",manifest:A,state:ne.state()}),ne.start()}finally{u?.delete(),h?.delete(),at=!1}}typeof self<"u"&&typeof self.postMessage=="function"&&typeof document>"u"&&(self.onmessage=async y=>{let h=y.data;try{if(!h||typeof h!="object"||typeof h.type!="string")throw new Error("Invalid worker message");if(h.type==="init"){await Ul(h);return}if(!ne)throw new Error("Workstation is not initialized");if(h.type==="ack"){ne.statePending=!1;return}if(ne.benchmarking)throw new Error("Interactive commands are disabled during deterministic benchmarking");if(h.type==="benchmark"){let u=await ne.benchmark(h);self.postMessage({type:"benchmark_result",request_id:h.request_id,result:u})}else h.type==="state"||ne.applyCommand(h),ne.publishState()}catch(u){ne&&(ne.invalidCommands+=1),self.postMessage({type:"error",request_id:h?.request_id,message:String(u.message).slice(0,500)})}});export{st as WorkstationEngine}; diff --git a/src/dvidia_training/workstation_worker.js b/src/dvidia_training/workstation_worker.js new file mode 100644 index 0000000..60c3096 --- /dev/null +++ b/src/dvidia_training/workstation_worker.js @@ -0,0 +1,338 @@ +/* DVIDIA live PiPER workstation. MIT. MuJoCo 3.15.0 runs entirely in this worker. */ +import loadMujoco from '@mujoco/mujoco'; +import {boundedTarget, clamp, dampedTargets, finiteVector, RollingSamples} from './workstation_control.js'; +import {localResource, resourceBytes, loadNativeAssets, loadWasmBytes} from './workstation_assets.js'; + +const ENGINE_VERSION = '3.15.0'; +const MAX_ASSETS = 256; +const MAX_CATCHUP_SECONDS = 0.1; +const MAX_STEPS_PER_TICK = 50; +// The event loop may deliver fewer states than requested. Backpressure retains +// at most one queued state while physics continues independently at 500 Hz. +const STATE_INTERVAL_MS = 1000 / 60; + +function validateManifest(manifest) { + if (!manifest || manifest.schema !== 'dvidia.live-workstation/v1') throw new Error('Unsupported workstation schema'); + if (manifest.native_version !== ENGINE_VERSION) throw new Error('Native and browser MuJoCo versions must match'); + if (manifest.timestep !== 0.002 || manifest.control_dt !== 0.02) throw new Error('Unsupported physics/control timestep'); + if (!Array.isArray(manifest.assets) || manifest.assets.length > MAX_ASSETS) throw new Error('Invalid asset manifest'); + if (!Array.isArray(manifest.bounds_xyz) || manifest.bounds_xyz.length !== 3) throw new Error('Invalid workspace bounds'); + for (const bounds of manifest.bounds_xyz) { + finiteVector(bounds, 2, 'Workspace bounds'); + if (bounds[0] >= bounds[1] || bounds[0] < -2 || bounds[1] > 2) throw new Error('Invalid workspace bounds'); + } + boundedTarget(manifest.initial_target_xyz, manifest.bounds_xyz); + const orientation = finiteVector(manifest.orientation_wxyz, 4, 'Tool orientation'); + if (Math.abs(Math.hypot(...orientation) - 1) > 1e-8) throw new Error('Tool orientation must be normalized'); + for (const field of ['joint_names', 'actuator_names']) { + if (!Array.isArray(manifest[field]) || manifest[field].length !== 6 + || !manifest[field].every(name => typeof name === 'string' && name.length < 100)) throw new Error(`Invalid ${field}`); + } + const config = manifest.controller; + for (const name of ['orientation_weight', 'translation_error_cap_m', 'rotation_error_cap_rad', 'damping', + 'max_joint_delta_rad', 'joint_margin_rad', 'joint_rate_rad_s', 'gripper_rate_m_s']) { + if (!Number.isFinite(config?.[name]) || config[name] <= 0 || config[name] > 5) throw new Error(`Invalid controller ${name}`); + } + finiteVector(config.gripper_range_m, 2, 'Gripper range'); + if (config.gripper_range_m[0] !== 0 || config.gripper_range_m[1] !== 0.035) throw new Error('Unsupported gripper range'); + if (!Array.isArray(manifest.shoe_body_names) || manifest.shoe_body_names.length > 12) throw new Error('Invalid shoe body list'); + const pushLimit = manifest.interaction_limits?.push_impulse_norm_max_ns; + if (!Number.isFinite(pushLimit) || pushLimit <= 0 || pushLimit > .12) throw new Error('Invalid push impulse limit'); + return manifest; +} + +export class WorkstationEngine { + constructor(mujoco, model, manifest, emit = () => {}) { + this.mj = mujoco; this.model = model; this.manifest = validateManifest(manifest); this.emit = emit; + if (model.nq !== 15 || model.nv !== 14 || model.nu !== 7 || model.neq !== 1 || model.nmocap !== 0 + || model.opt.timestep !== manifest.timestep) throw new Error('Native PiPER scene contract mismatch'); + this.data = new mujoco.MjData(model); + this.buffers = []; + const buffer = size => { const value = new mujoco.DoubleBuffer(size); this.buffers.push(value); return value; }; + this.jacp = buffer(3 * model.nv); this.jacr = buffer(3 * model.nv); + this.quaternion = buffer(4); this.rotation = buffer(3); this.contactForce = buffer(6); + const id = (type, name) => { + const value = mujoco.mj_name2id(model, mujoco.mjtObj[type].value, name); + if (value < 0) throw new Error(`Missing native model element: ${name}`); + return value; + }; + this.tcp = id('mjOBJ_SITE', manifest.tcp_site_name); + this.joints = manifest.joint_names.map(name => id('mjOBJ_JOINT', name)); + this.actuators = manifest.actuator_names.map(name => id('mjOBJ_ACTUATOR', name)); + this.jawActuator = id('mjOBJ_ACTUATOR', manifest.gripper_actuator_names[0]); + this.jawQpos = model.jnt_qposadr[id('mjOBJ_JOINT', 'joint7')]; + this.qposIds = this.joints.map(joint => model.jnt_qposadr[joint]); + this.dofIds = this.joints.map(joint => model.jnt_dofadr[joint]); + this.ctrlRange = this.actuators.map(actuator => Array.from(model.actuator_ctrlrange.slice(actuator * 2, actuator * 2 + 2))); + this.shoes = Object.fromEntries(manifest.shoe_body_names.map(name => [name, id('mjOBJ_BODY', name)])); + // These are borrowed views owned by MjData in the pinned 3.15 bindings. + // Retain once; deleting either view independently corrupts native MjData. + this.nativeWarnings = this.data.warning; + this.nativeWarningEntries = Array.from({length: this.nativeWarnings.size()}, (_, index) => this.nativeWarnings.get(index)); + this.dt = manifest.timestep; this.controlStride = Math.round(manifest.control_dt / this.dt); + this.running = true; this.benchmarking = false; this.timer = null; this.statePending = false; + this.reset(); + } + + reset() { + this.mj.mj_resetData(this.model, this.data); + const qpos = finiteVector(this.manifest.home_qpos, this.model.nq, 'Initial positions'); + const controls = finiteVector(this.manifest.home_ctrl, this.model.nu, 'Initial controls'); + this.data.qpos.set(qpos); this.data.ctrl.set(controls); + this.mj.mj_forward(this.model, this.data); + this.target = this.manifest.initial_target_xyz.slice(); + this.jaw = controls[this.jawActuator]; + this.desiredJaw = this.jaw; + this.desired = this.actuators.map(index => controls[index]); + this.steps = 0; this.pushes = new Map(); this.warnings = []; + this.stepSamples = new RollingSamples(); this.controlSamples = new RollingSamples(); + this.startWall = performance.now(); this.lastWall = this.startWall; this.lastStateWall = 0; + this.activeWallMs = 0; this.lagMs = 0; this.accumulator = 0; + this.peakContacts = 0; this.invalidCommands = 0; + this.statePending = false; + this.initialShoePositions = Object.fromEntries(Object.entries(this.shoes).map(([name, body]) => [name, + Array.from(this.data.xpos.slice(3 * body, 3 * body + 3))])); + } + + controller() { + const started = performance.now(); + const matrix = Array.from(this.data.site_xmat.slice(this.tcp * 9, this.tcp * 9 + 9)); + this.mj.mj_jacSite(this.model, this.data, this.jacp, this.jacr, this.tcp); + this.mj.mju_mat2Quat(this.quaternion, matrix); + this.mj.mju_subQuat(this.rotation, this.manifest.orientation_wxyz, Array.from(this.quaternion.GetView())); + const localRotation = this.rotation.GetView(); + const rotationWorld = [0, 1, 2].map(row => matrix[row * 3] * localRotation[0] + + matrix[row * 3 + 1] * localRotation[1] + matrix[row * 3 + 2] * localRotation[2]); + this.desired = dampedTargets({jacp: this.jacp.GetView(), jacr: this.jacr.GetView(), nv: this.model.nv, + dofIds: this.dofIds, qpos: this.data.qpos, qposIds: this.qposIds, + target: this.target, current: this.data.site_xpos.slice(this.tcp * 3, this.tcp * 3 + 3), + rotationWorld, ctrlRange: this.ctrlRange, config: this.manifest.controller}); + this.desiredJaw = this.jaw; + this.controlSamples.add(performance.now() - started); + } + + step() { + const started = performance.now(); + if (this.steps % this.controlStride === 0) this.controller(); + const config = this.manifest.controller; + const ctrl = this.data.ctrl; + this.actuators.forEach((actuator, index) => { + ctrl[actuator] += clamp(this.desired[index] - ctrl[actuator], -config.joint_rate_rad_s * this.dt, config.joint_rate_rad_s * this.dt); + }); + ctrl[this.jawActuator] += clamp(this.desiredJaw - ctrl[this.jawActuator], -config.gripper_rate_m_s * this.dt, config.gripper_rate_m_s * this.dt); + this.data.xfrc_applied.fill(0); + for (const [body, push] of this.pushes) { + if (push.remainingSteps <= 0) this.pushes.delete(body); + else { this.data.xfrc_applied.set(push.force, body * 6); push.remainingSteps -= 1; } + } + this.mj.mj_step(this.model, this.data); + this.data.xfrc_applied.fill(0); + this.mj.mj_forward(this.model, this.data); + this.steps += 1; + this.peakContacts = Math.max(this.peakContacts, this.data.ncon); + if (![...this.data.qpos, ...this.data.qvel, ...this.data.qacc, ...this.data.ctrl].every(Number.isFinite)) { + throw new Error('Non-finite native physics state; simulation paused'); + } + this.checkWarnings(); + this.stepSamples.add(performance.now() - started); + } + + checkWarnings() { + for (let index = 0; index < this.nativeWarningEntries.length; index += 1) { + const warning = this.nativeWarningEntries[index]; + if (warning.number > 0) { + const text = this.mj.mju_warningText(index, warning.lastinfo); + if (!this.warnings.includes(text)) this.warnings.push(text); + } + } + if (this.warnings.length) throw new Error(`Native solver warning; simulation paused: ${this.warnings[0]}`); + } + + applyCommand(command) { + switch (command.type) { + case 'target': this.target = boundedTarget(command.position, this.manifest.bounds_xyz); break; + case 'gripper': { + const range = this.manifest.controller.gripper_range_m; + if (!Number.isFinite(command.jaw) || command.jaw < range[0] || command.jaw > range[1]) throw new Error('Invalid gripper position'); + this.jaw = command.jaw; break; + } + case 'pause': + if (typeof command.paused !== 'boolean') throw new Error('Pause requires a boolean'); + this.running = !command.paused; this.lastWall = performance.now(); this.accumulator = 0; break; + case 'reset': this.reset(); break; + case 'push': { + const body = this.shoes[command.body]; + if (body === undefined) throw new Error('Push is restricted to a named shoe'); + const impulse = finiteVector(command.impulse, 3, 'Push impulse'); + const limit = this.manifest.interaction_limits.push_impulse_norm_max_ns; + if (Math.hypot(...impulse) > limit + 1e-9) throw new Error(`Push exceeds the ${limit} N·s impulse limit`); + this.pushes.set(body, {force: impulse.map(value => value / this.dt), remainingSteps: 1}); break; + } + default: throw new Error(`Unsupported command: ${String(command.type).slice(0, 60)}`); + } + } + + state() { + const position = Array.from(this.data.site_xpos.slice(this.tcp * 3, this.tcp * 3 + 3)); + const shoes = Object.fromEntries(Object.entries(this.shoes).map(([name, body]) => { + const position = Array.from(this.data.xpos.slice(body * 3, body * 3 + 3)); + return [name, {position, height_change_m: position[2] - this.initialShoePositions[name][2]}]; + })); + let contactForceTotal = 0; let contactForceMax = 0; let activeContacts = 0; + const contactForces = []; + for (let contact = 0; contact < this.data.ncon; contact += 1) { + this.mj.mj_contactForce(this.model, this.data, contact, this.contactForce); + const normal = Math.max(0, this.contactForce.GetView()[0]); + contactForceTotal += normal; contactForceMax = Math.max(contactForceMax, normal); + contactForces.push(normal); activeContacts += Number(normal > .001); + } + return {body_pos: Array.from(this.data.xpos), body_quat: Array.from(this.data.xquat), + qpos: Array.from(this.data.qpos), qvel: Array.from(this.data.qvel), ctrl: Array.from(this.data.ctrl), + tcp_position: position, target_position: this.target.slice(), jaw: this.jaw, + actual_jaw: this.data.qpos[this.jawQpos], commanded_jaw: this.data.ctrl[this.jawActuator], sim_time: this.data.time, + paused: !this.running, tracking_error_m: Math.hypot(...position.map((value, axis) => value - this.target[axis])), + contacts: this.data.ncon, contact_normal_force_total_n: contactForceTotal, contact_normal_force_max_n: contactForceMax, shoes, + active_contacts: activeContacts, contact_normal_forces_n: contactForces, + actuator_force: Array.from(this.data.actuator_force), + metrics: {step_ms_p50: this.stepSamples.quantile(.5), step_ms_p95: this.stepSamples.quantile(.95), + control_ms_p95: this.controlSamples.quantile(.95), rtf: this.activeWallMs > 0 ? this.data.time * 1000 / this.activeWallMs : 0, + lag_ms: this.lagMs, physics_steps: this.steps, active_wall_ms: this.activeWallMs, + peak_contacts: this.peakContacts, invalid_commands: this.invalidCommands, + samples_retained: this.stepSamples.values.length}, + warnings: this.warnings.slice(), engine: `MuJoCo ${ENGINE_VERSION} WASM`, + observation_origin: 'privileged_live_simulator_state'}; + } + + start() { + const tick = () => { + const now = performance.now(); + const elapsed = Math.max(0, (now - this.lastWall) / 1000); this.lastWall = now; + if (this.running && !this.benchmarking) { + this.activeWallMs += elapsed * 1000; + const available = this.accumulator + elapsed; + this.accumulator = Math.min(available, MAX_CATCHUP_SECONDS); + this.lagMs += Math.max(0, available - this.accumulator) * 1000; + let steps = 0; + try { + while (this.accumulator >= this.dt && steps < MAX_STEPS_PER_TICK) { + this.step(); this.accumulator -= this.dt; steps += 1; + } + } catch (error) { this.running = false; this.emit({type: 'error', message: error.message}); } + } + if (now - this.lastStateWall >= STATE_INTERVAL_MS && !this.benchmarking && !this.statePending) { + this.publishState(); this.lastStateWall = now; + } + this.timer = setTimeout(tick, 4); + }; + this.lastWall = performance.now(); this.timer = setTimeout(tick, 0); + } + + publishState() { + if (this.statePending) return; + this.statePending = true; + this.emit({type: 'state', state: this.state()}); + } + + async benchmark(command) { + if (!Number.isInteger(command.steps) || command.steps < 1 || command.steps > 30000) throw new Error('Benchmark requires 1–30,000 physics steps'); + const commands = command.commands ?? []; + if (!Array.isArray(commands) || commands.length > 1000) throw new Error('Too many benchmark commands'); + if (commands.some(item => !Number.isInteger(item.step) || item.step < 0 || item.step >= command.steps + || !['target', 'gripper', 'push'].includes(item.type))) throw new Error('Invalid benchmark schedule'); + const wasRunning = this.running; this.benchmarking = true; + this.reset(); this.running = false; + const started = performance.now(); let error = null; + const schedule = new Map(); + for (const item of commands) schedule.set(item.step, [...(schedule.get(item.step) ?? []), item]); + const trace = []; + try { + for (let step = 0; step < command.steps; step += 1) { + for (const item of schedule.get(step) ?? []) this.applyCommand(item); + this.step(); + if (step % 50 === 0 || step === command.steps - 1) { + const state = this.state(); + trace.push({step, sim_time: state.sim_time, tcp_position: state.tcp_position, + tracking_error_m: state.tracking_error_m, contacts: state.contacts, shoes: state.shoes}); + } + // Yield to the worker event loop, retaining a bounded, deterministic physics schedule. + if (step % 250 === 249) await new Promise(resolve => setTimeout(resolve, 0)); + } + } catch (exception) { error = exception.message; } + const wallMs = performance.now() - started; + this.activeWallMs = wallMs; + const finalState = this.state(); + this.benchmarking = false; this.running = wasRunning && !error; + this.lastWall = performance.now(); this.accumulator = 0; this.statePending = false; + return {schema: 'dvidia.live-workstation-benchmark/v1', engine_version: ENGINE_VERSION, + requested_steps: command.steps, completed_steps: this.steps, simulated_seconds: this.data.time, + wall_seconds: wallMs / 1000, real_time_factor: this.data.time * 1000 / wallMs, + valid: !error && !this.warnings.length, error, final_state: finalState, trace, + timestep: this.dt, control_dt: this.manifest.control_dt, + scene_sha256: this.manifest.native_scene.sha256, + limitations: ['Rigid synthetic shoe; material properties are uncalibrated.', 'Benchmark state is privileged simulator state.']}; + } + + dispose() { + if (this.timer !== null) clearTimeout(this.timer); + for (const buffer of this.buffers) buffer.delete(); + this.data.delete(); this.model.delete(); + } +} + +let engine = null; +let initializing = false; + +async function initialize(message) { + if (engine || initializing) throw new Error('The worker has already been initialized'); + initializing = true; + let model = null; let vfs = null; + try { + const base = new URL(message.manifest_url, self.location.href); + if (base.origin !== self.location.origin || !['http:', 'https:'].includes(base.protocol)) throw new Error('Manifest must be same-origin'); + const manifestBytes = await resourceBytes(base, undefined, {maxBytes: 2 * 1024 * 1024}); + if (manifestBytes.length > 2 * 1024 * 1024) throw new Error('Manifest is too large'); + const manifest = validateManifest(JSON.parse(new TextDecoder().decode(manifestBytes))); + if (!manifest.native_scene || manifest.native_scene.path !== manifest.scene_url) throw new Error('Scene checksum descriptor is missing'); + self.postMessage({type: 'progress', message: manifest.native_asset_bundle + ? 'Loading the physics engine and one compressed native mesh bundle.' + : 'Loading the physics engine and original native meshes.'}); + const transport = {onProgress: download => self.postMessage({type: 'progress', download})}; + const [wasmBinary, assets, scene] = await Promise.all([ + loadWasmBytes(manifest, base, transport), + loadNativeAssets(manifest, base, transport), + resourceBytes(localResource(manifest.scene_url, base), manifest.native_scene, transport), + ]); + const mujoco = await loadMujoco({wasmBinary, + printErr: text => { if (engine && engine.warnings.length < 20) engine.warnings.push(String(text).slice(0, 300)); }}); + if (mujoco.mj_versionString() !== ENGINE_VERSION) throw new Error('Unexpected MuJoCo WASM version'); + self.postMessage({type: 'progress', message: 'Native mesh checksums verified. Compiling the local physics scene.'}); + vfs = new mujoco.MjVFS(); + for (const asset of assets) vfs.addBuffer(asset.path, asset.bytes); + model = mujoco.MjModel.from_xml_string(new TextDecoder().decode(scene), vfs); + engine = new WorkstationEngine(mujoco, model, manifest, data => self.postMessage(data)); + model = null; + self.postMessage({type: 'ready', manifest, state: engine.state()}); + engine.start(); + } finally { vfs?.delete(); model?.delete(); initializing = false; } +} + +if (typeof self !== 'undefined' && typeof self.postMessage === 'function' && typeof document === 'undefined') { + self.onmessage = async event => { + const message = event.data; + try { + if (!message || typeof message !== 'object' || typeof message.type !== 'string') throw new Error('Invalid worker message'); + if (message.type === 'init') { await initialize(message); return; } + if (!engine) throw new Error('Workstation is not initialized'); + if (message.type === 'ack') { engine.statePending = false; return; } + if (engine.benchmarking) throw new Error('Interactive commands are disabled during deterministic benchmarking'); + if (message.type === 'benchmark') { + const result = await engine.benchmark(message); + self.postMessage({type: 'benchmark_result', request_id: message.request_id, result}); + } else if (message.type === 'state') engine.publishState(); + else { engine.applyCommand(message); engine.publishState(); } + } catch (error) { + if (engine) engine.invalidCommands += 1; + self.postMessage({type: 'error', request_id: message?.request_id, message: String(error.message).slice(0, 500)}); + } + }; +} diff --git a/tests/browser/workstation_assets.mjs b/tests/browser/workstation_assets.mjs new file mode 100644 index 0000000..44e1630 --- /dev/null +++ b/tests/browser/workstation_assets.mjs @@ -0,0 +1,369 @@ +import assert from 'node:assert/strict'; +import {test} from 'node:test'; +import {createHash} from 'node:crypto'; +import {gzipSync} from 'node:zlib'; +import {unpackNativeAssets, loadNativeAssets, loadWasmBytes, resourceBytes, boundedStreamBytes, MAX_RESOURCE_BYTES} from '../../src/dvidia_training/workstation_assets.js'; + +const hash = bytes => createHash('sha256').update(bytes).digest('hex'); +const original = [new TextEncoder().encode('first exact mesh\n'), new Uint8Array([0, 2, 4, 255])]; +const assets = original.map((bytes, index) => ({path: `assets/${index}.obj`, bytes: bytes.length, sha256: hash(bytes)})); +const combined = Buffer.concat(original); +const pack = bytes => { + const packed = gzipSync(bytes); + return {packed, bundle: {path: 'native-assets.bin.gz', compression: 'gzip', bytes: packed.length, + sha256: hash(packed), uncompressed_bytes: combined.length}}; +}; +const base = new URL('https://example.org/workstation/workstation.json'); +const fast = {idleTimeoutMs: 100, timeoutMs: 1000, retryDelayMs: 0}; +const response = (body, url, init) => { + const value = new Response(body, init); + Object.defineProperty(value, 'url', {value: String(url)}); + return value; +}; +async function usingFetch(mock, run) { + const originalFetch = globalThis.fetch; + try { globalThis.fetch = mock; return await run(); } + finally { globalThis.fetch = originalFetch; } +} + +test('one gzip bundle restores original mesh bytes and ordered native paths', async () => { + const {packed, bundle} = pack(combined); + const restored = await unpackNativeAssets(packed, bundle, assets); + assert.deepEqual(restored.map(item => item.path), assets.map(item => item.path)); + restored.forEach((item, index) => assert.deepEqual(item.bytes, original[index])); +}); + +test('bundle and individual mesh checksums both gate model loading', async () => { + const {packed, bundle} = pack(combined); + await assert.rejects(unpackNativeAssets(packed, {...bundle, sha256: '0'.repeat(64)}, assets), /checksum/); + const corrupt = Buffer.from(combined); corrupt[1] ^= 1; + const resealed = pack(corrupt); + await assert.rejects(unpackNativeAssets(resealed.packed, resealed.bundle, assets), /checksum/); +}); + +test('truncated, oversized, trailing and malformed compressed payloads fail', async () => { + for (const bytes of [combined.subarray(0, -1), Buffer.concat([combined, Buffer.alloc(200000)]), Buffer.from('bad')]) { + const {packed, bundle} = pack(bytes); + await assert.rejects(unpackNativeAssets(packed, bundle, assets)); + } + const {packed, bundle} = pack(combined); + const truncated = packed.subarray(0, -8); + await assert.rejects(unpackNativeAssets(truncated, {...bundle, bytes: truncated.length, sha256: hash(truncated)}, assets)); + await assert.rejects(unpackNativeAssets(packed, {...bundle, uncompressed_bytes: MAX_RESOURCE_BYTES * 4}, assets)); +}); + +test('decoded streaming bound cancels excessive output before retaining it', async () => { + let cancelled = false; + const stream = new ReadableStream({start(controller) { controller.enqueue(new Uint8Array(20)); }, + cancel() { cancelled = true; }}); + await assert.rejects(boundedStreamBytes(stream, 10), /too large/); + assert.equal(cancelled, true); +}); + +test('loader requests only the bundle; old manifests retain raw-file loading', async () => { + const {packed, bundle} = pack(combined); + const originalFetch = globalThis.fetch; const calls = []; + try { + globalThis.fetch = async url => { + calls.push(url.pathname); + const index = assets.findIndex(asset => url.pathname.endsWith(asset.path)); + return response(index >= 0 ? original[index] : packed, url); + }; + const base = new URL('https://example.org/workstation/workstation.json'); + const result = await loadNativeAssets({assets, native_asset_bundle: bundle}, base); + assert.deepEqual(calls, ['/workstation/native-assets.bin.gz']); + assert.equal(result.length, 2); + calls.length = 0; + const legacy = await loadNativeAssets({assets}, base); + assert.deepEqual(calls, assets.map(asset => '/workstation/' + asset.path)); + legacy.forEach((item, index) => assert.deepEqual(item.bytes, original[index])); + await assert.rejects(loadNativeAssets({assets: [{...assets[0], path: '../escape'}], native_asset_bundle: bundle}, base)); + } finally { globalThis.fetch = originalFetch; } +}); + +test('interrupted body retries from the start and verifies only the completed download', async () => { + const progress = [], options = [], calls = []; + await usingFetch(async (url, init) => { + calls.push(url.pathname); options.push(init); + if (calls.length === 1) { + let reads = 0; + return response(new ReadableStream({pull(controller) { + if (reads++ === 0) controller.enqueue(original[0].subarray(0, 3)); + else controller.error(new TypeError('network error')); + }}), url); + } + return response(original[0], url); + }, async () => { + assert.deepEqual(await resourceBytes(new URL(assets[0].path, base), assets[0], + {...fast, onProgress: value => progress.push(value)}), original[0]); + }); + assert.equal(calls.length, 2); + assert.equal(options[0].credentials, 'omit'); assert.equal(options[0].redirect, 'error'); + assert.equal(options[1].cache, 'reload'); + assert(progress.some(value => value.phase === 'retrying' && value.attempt === 1)); + assert(progress.some(value => value.attempt === 2 && value.receivedBytes === 0)); + assert.equal(progress.at(-1).phase, 'complete'); + assert.equal(progress.at(-1).receivedBytes, original[0].length); +}); + +test('transient HTTP and fetch errors retry, terminal HTTP does not', async () => { + for (const status of [408, 429, 502, 503, 504, 'network']) { + let calls = 0; + await usingFetch(async url => { + if (++calls === 1) { + if (status === 'network') throw new TypeError('Failed to fetch'); + return response('Temporary outage', url, {status}); + } + return response(original[0], url); + }, async () => assert.deepEqual(await resourceBytes(new URL(assets[0].path, base), assets[0], fast), original[0])); + assert.equal(calls, 2, String(status)); + } + let calls = 0; + await usingFetch(async url => { calls++; return response('Missing', url, {status: 404}); }, async () => { + await assert.rejects(resourceBytes(new URL(assets[0].path, base), assets[0], fast), /0.obj.*HTTP 404/); + }); + assert.equal(calls, 1); +}); + +test('progress uses a valid content length only when it describes decoded transfer bytes', async () => { + for (const [headers, total] of [ + [{'content-length': String(original[0].length)}, original[0].length], + [{'content-length': '5', 'content-encoding': 'gzip'}, null], + [{'content-length': 'invalid'}, null], + ]) { + const progress = []; + await usingFetch(async url => response(original[0], url, {headers}), async () => { + await resourceBytes(new URL('geometry.bin.gz', base), undefined, + {...fast, maxBytes: 100, onProgress: value => progress.push(value)}); + }); + assert.equal(progress.at(-1).totalBytes, total); + } +}); + +test('idle timeout covers headers and a stalled body; attempts remain bounded', async () => { + for (const stage of ['headers', 'body']) { + let calls = 0, cancelled = 0; const signals = []; + const started = performance.now(); + await usingFetch(async (url, init) => { + calls++; signals.push(init.signal); + if (stage === 'headers') return new Promise(() => {}); + return response(new ReadableStream({cancel() { cancelled++; }}), url); + }, async () => { + await assert.rejects(resourceBytes(new URL('waiting.bin', base), undefined, + {...fast, idleTimeoutMs: 10}), /waiting.bin.*attempt 3\/3.*stalled/); + }); + assert.equal(calls, 3); assert(signals.every(signal => signal.aborted)); + if (stage === 'body') assert.equal(cancelled, 3); + assert(performance.now() - started < 1000); + } +}); + +test('total deadline stops a trickling response even while the idle timer resets', async () => { + let calls = 0, cancelled = 0, interval; + const started = performance.now(); + await usingFetch(async url => { + calls++; + return response(new ReadableStream({start(controller) { + interval = setInterval(() => controller.enqueue(new Uint8Array([1])), 3); + }, cancel() { cancelled++; clearInterval(interval); }}), url); + }, async () => { + await assert.rejects(resourceBytes(new URL('trickle.bin', base), undefined, + {...fast, timeoutMs: 35, idleTimeoutMs: 20}), /deadline exceeded/); + }); + assert.equal(calls, 1); assert.equal(cancelled, 1); assert(performance.now() - started < 1000); +}); + +test('size, hash and manifest violations never retry or relax byte bounds', async () => { + for (const [bytes, init, expected, message] of [ + [original[0].subarray(0, -1), {}, assets[0], /size mismatch/], + [new Uint8Array(original[0].length), {}, assets[0], /checksum mismatch/], + [new Uint8Array(original[0].length + 1), {}, assets[0], /too large/], + [original[0], {headers: {'content-length': String(MAX_RESOURCE_BYTES + 1)}}, assets[0], /too large/], + ]) { + let calls = 0; + await usingFetch(async url => { calls++; return response(bytes, url, init); }, async () => { + await assert.rejects(resourceBytes(new URL('bounded.bin', base), expected, fast), message); + }); + assert.equal(calls, 1); + } + let calls = 0; + await usingFetch(async () => { calls++; throw new Error('must not fetch'); }, async () => { + for (const options of [{maxBytes: MAX_RESOURCE_BYTES + 1}, {maxAttempts: 4}, {timeoutMs: 0}, {idleTimeoutMs: 0}]) { + await assert.rejects(resourceBytes(new URL('invalid.bin', base), undefined, options), /transport option/); + } + await assert.rejects(resourceBytes(new URL('invalid.bin', base), {...assets[0], bytes: -1}), /descriptor/); + }); + assert.equal(calls, 0); +}); + +test('oversized body is cancelled and limit errors are not retried', async () => { + let calls = 0, cancelled = false; + await usingFetch(async url => { + calls++; + return response(new ReadableStream({start(controller) { controller.enqueue(new Uint8Array(20)); }, + cancel() { cancelled = true; }}), url); + }, async () => { + await assert.rejects(resourceBytes(new URL('large.bin', base), undefined, {...fast, maxBytes: 10}), /too large/); + }); + assert.equal(calls, 1); assert.equal(cancelled, true); +}); + +test('only the exact public Space may follow its observed HTTPS CDN origin', async () => { + for (const [source, final, permitted] of [ + ['https://example.org/file', 'https://example.org/file', true], + ['https://example.org/file', 'https://us.aws.cdn.hf.co/file', false], + ['https://dvidia-robot-simulation-lab.static.hf.space/file', 'https://us.aws.cdn.hf.co/file', true], + ['https://dvidia-robot-simulation-lab.static.hf.space/file', 'https://other.static.hf.space/file', false], + ['https://dvidia-robot-simulation-lab.static.hf.space/file', 'http://us.aws.cdn.hf.co/file', false], + ['https://dvidia-robot-simulation-lab.static.hf.space.evil.example/file', 'https://us.aws.cdn.hf.co/file', false], + ]) { + let calls = 0; + await usingFetch(async (url, options) => { + calls++; + assert.equal(options.redirect, new URL(source).host === 'dvidia-robot-simulation-lab.static.hf.space' ? 'follow' : 'error'); + return response(original[0], final); + }, async () => { + if (permitted) assert.deepEqual(await resourceBytes(source, assets[0], fast), original[0]); + else await assert.rejects(resourceBytes(source, assets[0], fast), /permitted workstation host/); + }); + assert.equal(calls, 1); + } +}); + +const mirrorAssets = [ + {name: 'geometry.bin.gz', bytes: 3574720, sha256: '51365a5a661d8062e28c66abc6bdb843ee410811f84b49d62c5878c265b3631f'}, + {name: 'native-assets.bin.gz', bytes: 7318481, sha256: '9c960598f9b2c0c7459a8bdfc8a544513b4c6ffaff2c8787fa49f728774eb9e7'}, + {name: 'mujoco.wasm.gz', bytes: 2543112, sha256: 'ad01772e00939bf6300a953b396d38aa9ec03c05fcda46c3c8d940d56f772b3b'}, +]; +const spaceAsset = item => 'https://dvidia-robot-simulation-lab.static.hf.space/workstation/v01/' + item.name; +const mirrorAsset = item => 'https://research.dvidia.org/runtime/workstation/' + item.sha256 + '/' + item.name; + +test('three exact approved hosted assets use their content-addressed mirror first', async () => { + for (const item of mirrorAssets) { + const calls = []; + await usingFetch(async (url, options) => { + calls.push(String(url)); + assert.equal(options.credentials, 'omit'); assert.equal(options.referrerPolicy, 'no-referrer'); + assert.equal(options.redirect, 'manual'); + return response('Denied', url, {status: 403}); + }, async () => await assert.rejects(resourceBytes(spaceAsset(item), item, fast), /HTTP 403/)); + assert.deepEqual(calls, [mirrorAsset(item)]); + } +}); + +test('mirror routing requires exact origin, path, bytes and digest; other exports stay local', async () => { + const item = mirrorAssets[0]; + for (const [url, expected] of [ + [spaceAsset(item), undefined], + [spaceAsset(item), {...item, bytes: item.bytes + 1}], + [spaceAsset(item), {...item, sha256: '0'.repeat(64)}], + [spaceAsset(item) + '?revision=future', item], + [spaceAsset(item).replace('/v01/', '/v02/'), item], + [spaceAsset(item).replace('https:', 'http:'), item], + [spaceAsset(item).replace('.static.hf.space', '.static.hf.space.evil.example'), item], + [spaceAsset(item).replace('dvidia-robot-simulation-lab.static.hf.space', 'research.dvidia.org'), item], + ['http://127.0.0.1:8295/' + item.name, item], + ]) { + const calls = []; + await usingFetch(async requested => { + calls.push(String(requested)); return response('Missing', requested, {status: 404}); + }, async () => await assert.rejects(resourceBytes(url, expected, fast), /HTTP 404/)); + assert.deepEqual(calls, [url]); + } +}); + +test('mirror network or availability errors fall back to the original within the same attempt budget', async () => { + const item = mirrorAssets[2]; + for (const failure of ['network', 'body', 404, 410, 503]) { + const calls = []; + await usingFetch(async url => { + calls.push(String(url)); + if (calls.length === 1) { + if (failure === 'network') throw new TypeError('Failed to fetch'); + if (failure === 'body') return response(new ReadableStream({start(controller) { + controller.error(new TypeError('network error')); + }}), url); + return response('Unavailable', url, {status: failure}); + } + // The origin's own permanent failure must remain terminal after fallback. + return response('Missing', url, {status: 404}); + }, async () => await assert.rejects(resourceBytes(spaceAsset(item), item, fast), /attempt 2\/3.*HTTP 404/)); + assert.deepEqual(calls, [mirrorAsset(item), spaceAsset(item)], String(failure)); + } + const calls = []; + await usingFetch(async url => { calls.push(String(url)); throw new TypeError('Failed to fetch'); }, + async () => await assert.rejects(resourceBytes(spaceAsset(item), item, fast), /attempt 3\/3/)); + assert.deepEqual(calls, [mirrorAsset(item), spaceAsset(item), spaceAsset(item)]); +}); + +test('mirror integrity, size and redirect failures never fall back or relax verification', async () => { + const item = mirrorAssets[2]; + for (const [makeResponse, message] of [ + [url => response(new Uint8Array(item.bytes), url), /checksum mismatch/], + [url => response(new Uint8Array(1), url), /size mismatch/], + [url => response(new Uint8Array(item.bytes + 1), url), /too large/], + [url => response('Redirect', url, {status: 302}), /may not redirect/], + [url => { const value = response(null, url); Object.defineProperty(value, 'type', {value: 'opaqueredirect'}); return value; }, /may not redirect/], + [() => response(null, 'https://untrusted.example/geometry.bin.gz'), /permitted workstation host/], + [url => response(null, String(url) + '?changed=1'), /permitted workstation host/], + ]) { + const calls = []; + await usingFetch(async url => { calls.push(String(url)); return makeResponse(url); }, + async () => await assert.rejects(resourceBytes(spaceAsset(item), item, fast), message)); + assert.deepEqual(calls, [mirrorAsset(item)]); + } +}); + +const wasm = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0]); +const wasmManifest = () => { + const packed = gzipSync(wasm); + return {packed, manifest: {native_wasm: {path: 'mujoco.wasm', bytes: wasm.length, sha256: hash(wasm)}, + wasm_bundle: {path: 'mujoco.wasm.gz', compression: 'gzip', bytes: packed.length, + sha256: hash(packed), uncompressed_bytes: wasm.length}}}; +}; + +test('compressed WASM restores exact native bytes while legacy exports stay readable', async () => { + const {packed, manifest} = wasmManifest(); const calls = []; + await usingFetch(async url => { + calls.push(url.pathname); + return response(url.pathname.endsWith('.gz') ? packed : wasm, url); + }, async () => { + assert.deepEqual(await loadWasmBytes(manifest, base, fast), wasm); + assert.deepEqual(await loadWasmBytes({native_wasm: manifest.native_wasm}, base, fast), wasm); + assert.deepEqual(await loadWasmBytes({}, base, fast), wasm); + }); + assert.deepEqual(calls, ['/workstation/mujoco.wasm.gz', '/workstation/mujoco.wasm', '/workstation/mujoco.wasm']); +}); + +test('WASM checks compressed and decoded integrity, truncation, expansion and descriptors', async () => { + const {packed, manifest} = wasmManifest(); + const cases = [ + [packed, {...manifest, wasm_bundle: {...manifest.wasm_bundle, sha256: '0'.repeat(64)}}, /checksum/], + [packed, {...manifest, native_wasm: {...manifest.native_wasm, sha256: '0'.repeat(64)}}, /checksum/], + [packed.subarray(0, -4), manifest, /size mismatch/], + ]; + for (const decoded of [wasm.subarray(0, -1), new Uint8Array(10000)]) { + const changed = gzipSync(decoded); + cases.push([changed, {...manifest, wasm_bundle: {...manifest.wasm_bundle, bytes: changed.length, sha256: hash(changed)}}, + decoded.length > wasm.length ? /too large/ : /size mismatch/]); + } + const truncated = packed.subarray(0, -4); + cases.push([truncated, {...manifest, wasm_bundle: {...manifest.wasm_bundle, bytes: truncated.length, sha256: hash(truncated)}}, /./]); + for (const [bytes, input, error] of cases) { + let calls = 0; + await usingFetch(async url => { calls++; return response(bytes, url); }, async () => { + await assert.rejects(loadWasmBytes(input, base, fast), error); + }); + assert.equal(calls, 1); + } + let calls = 0; + await usingFetch(async () => { calls++; throw new Error('must not fetch'); }, async () => { + for (const input of [{wasm_bundle: manifest.wasm_bundle}, + {...manifest, wasm_bundle: {...manifest.wasm_bundle, uncompressed_bytes: 123}}, + {...manifest, native_wasm: {...manifest.native_wasm, path: 'other.wasm'}}, + {...manifest, wasm_bundle: {...manifest.wasm_bundle, path: 'other.gz'}}]) { + await assert.rejects(loadWasmBytes(input, base, fast), /descriptor/); + } + }); + assert.equal(calls, 0); +}); diff --git a/tests/browser/workstation_control.mjs b/tests/browser/workstation_control.mjs new file mode 100644 index 0000000..cb8e891 --- /dev/null +++ b/tests/browser/workstation_control.mjs @@ -0,0 +1,37 @@ +import assert from 'node:assert/strict'; +import {test} from 'node:test'; +import {boundedTarget, dampedTargets, limitNorm, RollingSamples, solveLinear} from '../../src/dvidia_training/workstation_control.js'; + +test('workspace inputs reject invalid vectors instead of clipping them silently', () => { + const bounds = [[.18, .54], [-.24, .24], [.055, .34]]; + assert.deepEqual(boundedTarget([.36, -.06, .27], bounds), [.36, -.06, .27]); + for (const value of [[NaN, 0, .1], [Infinity, 0, .1], [.3, .9, .1], [.3, 0], ['.3', 0, .1]]) { + assert.throws(() => boundedTarget(value, bounds)); + } +}); + +test('regularized solver and norm caps preserve direction', () => { + assert.deepEqual(solveLinear([[2, 0], [0, 4]], [6, 8]), [3, 2]); + assert.throws(() => solveLinear([[0, 0], [0, 0]], [1, 1])); + assert.deepEqual(limitNorm([3, 4, 0], 1), [.6, .8, 0]); +}); + +test('damped target solve respects native joint margins at singular configurations', () => { + const zero = new Float64Array(18); + const config = {translation_error_cap_m: .015, rotation_error_cap_rad: .05, orientation_weight: .25, + damping: .012, max_joint_delta_rad: .06, joint_margin_rad: .02}; + const targets = dampedTargets({jacp: zero, jacr: zero, nv: 6, + dofIds: [0, 1, 2, 3, 4, 5], qposIds: [0, 1, 2, 3, 4, 5], qpos: [1, -1, 0, 0, 0, 0], + target: [.5, .2, .3], current: [0, 0, 0], rotationWorld: [0, .2, 0], + ctrlRange: Array.from({length: 6}, () => [-1, 1]), config}); + assert.deepEqual(targets, [.98, -.98, 0, 0, 0, 0]); +}); + +test('timing telemetry uses bounded retention during long sessions', () => { + const samples = new RollingSamples(8); + for (let value = 0; value < 10000; value += 1) samples.add(value); + samples.add(NaN); + assert.equal(samples.values.length, 8); + assert.equal(samples.quantile(0), 9992); + assert.equal(samples.quantile(1), 9999); +}); diff --git a/tests/browser/workstation_download.cjs b/tests/browser/workstation_download.cjs new file mode 100644 index 0000000..f7dcf96 --- /dev/null +++ b/tests/browser/workstation_download.cjs @@ -0,0 +1,214 @@ +/* DVIDIA workstation transport recovery acceptance. MIT. + * Usage: node tests/browser/workstation_download.cjs URL NEW_OUTPUT_DIRECTORY + * Uses the real rendered scene and native MuJoCo worker. Only HTTP requests + * are fault-injected; no model, controller, state or physics responses are mocked. + */ +const assert = require('node:assert/strict'); +const fs = require('node:fs/promises'); +const path = require('node:path'); +const {chromium} = require(process.env.DVIDIA_PLAYWRIGHT_MODULE + || path.join(__dirname, '../../viewer/node_modules/playwright')); + +const ASSETS = ['geometry.bin.gz', 'native-assets.bin.gz', 'mujoco.wasm.gz']; +const MAX_ATTEMPTS = 3; +const cleanURL = value => { const url = new URL(value); return url.origin + url.pathname; }; +const assetName = value => new URL(value).pathname.split('/').pop(); +const getState = page => page.evaluate(() => window.__workstationState); + +async function instrument(context) { + await context.addInitScript(() => { + window.__downloadFaultEvidence = {loading: [], worker: []}; + let lastText; + new MutationObserver(() => { + const text = document.querySelector('#loading-message')?.textContent; + if (text && text !== lastText) { + lastText = text; + if (window.__downloadFaultEvidence.loading.length < 500) { + window.__downloadFaultEvidence.loading.push({ms: performance.now(), text}); + } + } + }).observe(document, {subtree: true, childList: true, characterData: true}); + const NativeWorker = window.Worker; + window.Worker = class extends NativeWorker { + constructor(...args) { + super(...args); + this.addEventListener('message', event => { + const message = event.data; + if (message?.state) window.__workstationState = message.state; + if (message?.type === 'progress' && message.download) { + // Retain every retry and completion, plus the start of each attempt. + const item = message.download; + if (item.phase !== 'downloading' || item.receivedBytes === 0) { + window.__downloadFaultEvidence.worker.push({ms: performance.now(), ...item}); + } + } + }); + } + }; + }); +} + +function capture(page) { + const evidence = {pageErrors: [], httpErrors: [], requestFailures: []}; + page.on('pageerror', error => evidence.pageErrors.push(error.message)); + page.on('response', response => { + if (response.status() >= 400) evidence.httpErrors.push({url: cleanURL(response.url()), status: response.status()}); + }); + page.on('requestfailed', request => evidence.requestFailures.push({ + url: cleanURL(request.url()), error: request.failure()?.errorText, + })); + return evidence; +} + +async function ready(page) { + await page.waitForFunction(() => ['true', 'error'].includes(document.querySelector('#stage')?.dataset.ready), + {}, {timeout: 120000}); + assert.equal(await page.locator('#stage').getAttribute('data-ready'), 'true', + await page.locator('#loading-message').textContent()); + await page.waitForFunction(() => window.__workstationState?.sim_time > .3); +} + +async function nativeControls(page, directory) { + const before = await getState(page); + await page.locator('#pause').click(); + await page.waitForFunction(() => window.__workstationState?.paused === true); + const paused = await getState(page); + await page.waitForTimeout(300); + assert.equal((await getState(page)).sim_time, paused.sim_time, 'Paused native simulation must stay still'); + await page.locator('#pause').click(); + await page.waitForFunction(() => window.__workstationState?.paused === false); + for (const [axis, value] of [['x', '370'], ['y', '-100'], ['z', '240']]) { + await page.locator('#target-' + axis).fill(value); + } + await page.locator('#apply-target').click(); + await page.waitForFunction(() => Math.abs(window.__workstationState.target_position[0] - .37) < 1e-8 + && Math.abs(window.__workstationState.target_position[1] + .1) < 1e-8); + await page.waitForFunction(() => window.__workstationState.tracking_error_m < .01, {}, {timeout: 15000}); + const reached = await getState(page); + assert(reached.qpos.some((value, index) => Math.abs(value - before.qpos[index]) > .01), + 'Native joints must move in response to the target'); + await page.locator('#gripper').evaluate(element => { + element.value = '20'; element.dispatchEvent(new Event('input', {bubbles: true})); + }); + await page.waitForFunction(() => Math.abs(window.__workstationState.jaw - .02) < 1e-8 + && Math.abs(window.__workstationState.actual_jaw - .02) < .002, {}, {timeout: 10000}); + const prePush = (await getState(page)).shoes.shoe_trainer_left.position; + await page.locator('#push').click(); + await page.waitForFunction(position => Math.hypot(...window.__workstationState.shoes.shoe_trainer_left.position + .map((value, index) => value - position[index])) > .001, prePush, {timeout: 10000}); + const afterPush = await getState(page); + const downloadPromise = page.waitForEvent('download'); + await page.locator('#receipt').click(); + const download = await downloadPromise; + await download.saveAs(path.join(directory, 'session.json')); + const receipt = JSON.parse(await fs.readFile(path.join(directory, 'session.json'), 'utf8')); + assert(receipt.commands.some(command => command.type === 'target')); + assert(receipt.commands.some(command => command.type === 'push' && command.impulse)); + assert(receipt.samples.length > 0 && receipt.samples.some(sample => sample.body_pos.length > 3)); + return {pauseStable: true, targetErrorM: reached.tracking_error_m, + actualJawM: afterPush.actual_jaw, shoeBefore: prePush, shoeAfter: afterPush.shoes.shoe_trainer_left.position, + receiptCommands: receipt.commands.length, receiptSamples: receipt.samples.length}; +} + +async function transientCase(browser, url, directory) { + const context = await browser.newContext({viewport: {width: 1440, height: 1100}, serviceWorkers: 'block'}); + await instrument(context); + const counts = Object.fromEntries(ASSETS.map(name => [name, 0])); + await context.route('**/*', async route => { + const name = assetName(route.request().url()); + if (Object.hasOwn(counts, name) && ++counts[name] === 1) return route.abort('failed'); + return route.continue(); + }); + const page = await context.newPage(); const network = capture(page); const started = performance.now(); + try { + const navigation = await page.goto(url, {waitUntil: 'domcontentloaded', timeout: 60000}); + assert(navigation?.ok()); + await ready(page); + const readyMs = performance.now() - started; + for (const name of ASSETS) assert.equal(counts[name], 2, name + ' must recover on exactly one retry'); + const progress = await page.evaluate(() => window.__downloadFaultEvidence); + for (const name of ['native-assets.bin.gz', 'mujoco.wasm.gz']) { + assert(progress.worker.some(item => item.phase === 'retrying' && item.path.endsWith('/' + name)), + name + ' worker retry must emit structured progress'); + } + assert(progress.loading.some(item => /retry/i.test(item.text) && item.text.includes('Scene geometry')), + 'Geometry retry must be visible in the loading status'); + const controls = await nativeControls(page, directory); + assert.deepEqual(network.pageErrors, []); assert.deepEqual(network.httpErrors, []); + await page.screenshot({path: path.join(directory, 'recovered.png'), fullPage: true}); + return {passed: true, fault: 'First request for each large binary aborted before headers', counts, + readyMs, progress, controls, network}; + } catch (error) { + await page.screenshot({path: path.join(directory, 'failure.png'), fullPage: true}).catch(() => {}); + throw Object.assign(error, {caseEvidence: {counts, network, + progress: await page.evaluate(() => window.__downloadFaultEvidence).catch(() => null)}}); + } finally { await context.close(); } +} + +async function terminalCase(browser, url, directory) { + const context = await browser.newContext({viewport: {width: 1440, height: 1100}, serviceWorkers: 'block'}); + await instrument(context); + let blocked = true, requests = 0; + await context.route('**/*', async route => { + if (assetName(route.request().url()) === 'geometry.bin.gz') { + requests += 1; + if (blocked) return route.abort('failed'); + } + return route.continue(); + }); + const page = await context.newPage(); const network = capture(page); + try { + const navigation = await page.goto(url, {waitUntil: 'domcontentloaded', timeout: 60000}); + assert(navigation?.ok()); + await page.waitForFunction(() => document.querySelector('#stage')?.dataset.ready === 'error', {}, {timeout: 120000}); + assert.equal(requests, MAX_ATTEMPTS, 'Persistent transport failure must stop after three attempts'); + const message = await page.locator('#loading-message').textContent(); + assert.match(message, /geometry\.bin\.gz/); + assert.match(message, /attempt 3\/3/); + assert(await page.locator('#retry-download').isVisible(), 'A retry control must remain visible after terminal failure'); + assert(await page.locator('#retry-download').isEnabled(), 'A retry control must remain enabled after terminal failure'); + const failedProgress = await page.evaluate(() => window.__downloadFaultEvidence); + await page.screenshot({path: path.join(directory, 'named-failure-and-retry.png'), fullPage: true}); + blocked = false; + const started = performance.now(); + await Promise.all([page.waitForEvent('domcontentloaded'), page.locator('#retry-download').click()]); + await ready(page); + assert.equal(requests, MAX_ATTEMPTS + 1, 'User retry must start one new successful geometry request'); + assert.deepEqual(network.pageErrors, []); assert.deepEqual(network.httpErrors, []); + await page.locator('#pause').click(); + await page.waitForFunction(() => window.__workstationState?.paused === true); + await page.screenshot({path: path.join(directory, 'manual-retry-recovered.png'), fullPage: true}); + return {passed: true, fault: 'Every geometry request aborted until explicit user retry', requests, + terminalMessage: message, retryEnabled: true, recoveredReadyMs: performance.now() - started, + failedProgress, recoveredNativeSimTime: (await getState(page)).sim_time, network}; + } catch (error) { + await page.screenshot({path: path.join(directory, 'failure.png'), fullPage: true}).catch(() => {}); + throw Object.assign(error, {caseEvidence: {requests, blocked, network, + progress: await page.evaluate(() => window.__downloadFaultEvidence).catch(() => null)}}); + } finally { await context.close(); } +} + +(async () => { + const [url, output] = process.argv.slice(2); + assert(url && output, 'Provide a workstation URL and a new output directory'); + assert(['http:', 'https:'].includes(new URL(url).protocol)); + await fs.mkdir(output, {recursive: true}); + // Refuse to silently overwrite a prior verdict, especially a recorded failure. + await fs.access(path.join(output, 'acceptance.json')).then(() => { + throw new Error('Use a fresh output directory; acceptance.json already exists'); + }, () => {}); + const browser = await chromium.launch({headless: true}); + const result = {passed: false, url: cleanURL(url), scope: 'Real-browser transport recovery with native MuJoCo physics; synthetic HTTP faults only.', cases: {}}; + try { + for (const [name, run] of [['transient', transientCase], ['terminal', terminalCase]]) { + const directory = path.join(output, name); await fs.mkdir(directory, {recursive: true}); + try { result.cases[name] = await run(browser, url, directory); } + catch (error) { result.cases[name] = {passed: false, error: error.message, ...error.caseEvidence}; throw error; } + } + result.passed = true; + } catch (error) { result.error = error.message; process.exitCode = 1; } + finally { + await fs.writeFile(path.join(output, 'acceptance.json'), JSON.stringify(result, null, 2) + '\n'); + console.log(JSON.stringify(result, null, 2)); await browser.close(); + } +})().catch(error => { console.error(error); process.exitCode = 1; }); diff --git a/tests/browser/workstation_live.cjs b/tests/browser/workstation_live.cjs new file mode 100644 index 0000000..2c64716 --- /dev/null +++ b/tests/browser/workstation_live.cjs @@ -0,0 +1,341 @@ +/* Actual-UI live physics acceptance and foreground stability benchmark. + * DVIDIA_PLAYWRIGHT_MODULE=/absolute/path/to/playwright DVIDIA_BENCH_SECONDS=600 + * node tests/browser/workstation_live.cjs URL OUTPUT_DIRECTORY + * Default renderer is explicitly software SwiftShader; never call it a device-GPU result. + */ +const assert = require('node:assert/strict'); +const fs = require('node:fs/promises'); +const path = require('node:path'); +const os = require('node:os'); +const {createHash} = require('node:crypto'); +const {chromium} = require(process.env.DVIDIA_PLAYWRIGHT_MODULE || path.join(__dirname, '../../viewer/node_modules/playwright')); + +const percentile = (values, fraction) => { + if (!values.length) return null; + const sorted = values.slice().sort((a, b) => a - b); + return sorted[Math.max(0, Math.ceil(sorted.length * fraction) - 1)]; +}; +const distribution = values => ({count: values.length, p50: percentile(values, .5), p95: percentile(values, .95), + p99: percentile(values, .99), min: values.length ? Math.min(...values) : null, max: values.length ? Math.max(...values) : null}); +const distance = (a, b) => Math.hypot(...a.map((value, index) => value - b[index])); + +function installProbe() { + const probe = window.__dvidiaLiveProbe = { + started_at: new Date().toISOString(), commands: [], states: [], latencies: [], errors: [], latest: null, + state_count: 0, commands_dropped: 0, states_dropped: 0, frame_samples_dropped: 0, + worker_count: 0, warnings: [], recent: [], raf_times: [], render_times: [], worker_times: [], + visibility_events: [], measuring: false, control_ack_count: 0, native_finite: true, + latest_sample_ms: -Infinity, state_schema: null, + }; + const bounded = (array, value, maximum, dropped) => { + if (array.length === maximum) { array.shift(); if (dropped) probe[dropped] += 1; } + array.push(value); + }; + const norm = (a, b) => Math.hypot(...a.map((value, index) => value - b[index])); + const same = (a, b) => a?.length === b?.length && a.every((value, index) => Math.abs(value - b[index]) < 1e-9); + const NativeWorker = window.Worker; + window.Worker = class extends NativeWorker { + constructor(...args) { + super(...args); probe.worker_count += 1; + this.addEventListener('message', event => { + const message = event.data; + if (message.type === 'error') bounded(probe.errors, {wall_ms: performance.now(), message: message.message}, 100); + if (!['ready', 'state'].includes(message.type) || !message.state) return; + const state = message.state; const now = performance.now(); + probe.latest = state; probe.state_count += 1; + probe.native_finite &&= ['qpos', 'qvel', 'ctrl', 'body_pos', 'body_quat'].every(key => state[key]?.every(Number.isFinite)); + for (const warning of state.warnings || []) if (!probe.warnings.includes(warning)) bounded(probe.warnings, warning, 100); + bounded(probe.recent, {wall_ms: now, tcp: state.tcp_position, target: state.target_position}, 30); + if (probe.measuring) bounded(probe.worker_times, now, 45000, 'frame_samples_dropped'); + if (now - probe.latest_sample_ms >= 100) { + bounded(probe.states, {wall_ms: now, sim_time: state.sim_time, paused: state.paused, + tcp_position: state.tcp_position, target_position: state.target_position, + qpos: state.qpos, qvel: state.qvel, ctrl: state.ctrl, actual_jaw: state.actual_jaw, + shoes: state.shoes, contacts: state.contacts, active_contacts: state.active_contacts, + contact_normal_force_total_n: state.contact_normal_force_total_n, + tracking_error_m: state.tracking_error_m, metrics: state.metrics, warnings: state.warnings}, 15000, 'states_dropped'); + probe.latest_sample_ms = now; + } + for (const latency of probe.latencies) { + if (latency.superseded_at_ms !== null || now - latency.command_wall_ms > 5000 + || now < latency.command_wall_ms || !same(state.target_position, latency.target)) continue; + if (latency.target_echo_ms === null) latency.target_echo_ms = now - latency.command_wall_ms; + if (latency.physical_response_ms === null && latency.command_distance_m > .005) { + const projected = state.tcp_position.reduce((sum, value, index) => sum + + (value - latency.baseline_tcp[index]) * (latency.target[index] - latency.baseline_tcp[index]), 0) / latency.command_distance_m; + if (projected >= .001) { + latency.physical_response_ms = now - latency.command_wall_ms; + latency.response_tcp = state.tcp_position; + latency.response_sim_time = state.sim_time; + } + } + } + }); + } + postMessage(message, ...rest) { + const now = performance.now(); + if (message?.type === 'ack') probe.control_ack_count += 1; + if (message && !['ack', 'state'].includes(message.type)) { + bounded(probe.commands, {wall_ms: now, sim_time: probe.latest?.sim_time ?? null, ...structuredClone(message)}, 2000, 'commands_dropped'); + if (message.type === 'target' && probe.latest) { + for (const previous of probe.latencies) { + if (previous.physical_response_ms === null && previous.superseded_at_ms === null) previous.superseded_at_ms = now; + } + const baseline = probe.latest.tcp_position.slice(); + const recent = probe.recent.filter(state => now - state.wall_ms < 350); + const baselineSpread = Math.max(0, ...recent.map(state => norm(state.tcp, baseline))); + bounded(probe.latencies, {command_wall_ms: now, baseline_sim_time: probe.latest.sim_time, + target: message.position.slice(), baseline_tcp: baseline, command_distance_m: norm(message.position, baseline), + baseline_spread_m: baselineSpread, + baseline_stable: recent.length >= 5 && baselineSpread < .0005, + target_echo_ms: null, physical_response_ms: null, superseded_at_ms: null}, 300); + } + } + return super.postMessage(message, ...rest); + } + }; + document.addEventListener('visibilitychange', () => bounded(probe.visibility_events, + {wall_ms: performance.now(), visibility: document.visibilityState}, 100)); + const frame = timestamp => { + if (probe.measuring) bounded(probe.raf_times, timestamp, 90000, 'frame_samples_dropped'); + requestAnimationFrame(frame); + }; + requestAnimationFrame(frame); + const observeCanvas = () => { + const canvas = document.querySelector('#canvas'); + if (!canvas) { setTimeout(observeCanvas, 20); return; } + new MutationObserver(records => { + if (probe.measuring && records.some(record => record.attributeName === 'data-render-count')) { + bounded(probe.render_times, performance.now(), 90000, 'frame_samples_dropped'); + } + }).observe(canvas, {attributes: true, attributeFilter: ['data-render-count']}); + }; + observeCanvas(); + probe.begin = () => { + probe.measuring = true; probe.measure_start_ms = performance.now(); + probe.measure_start_sim = probe.latest.sim_time; + probe.measure_start_lag_ms = probe.latest.metrics.lag_ms; + probe.measure_start_steps = probe.latest.metrics.physics_steps; + probe.measure_start_render_count = Number(document.querySelector('#canvas').dataset.renderCount || 0); + probe.raf_times = []; probe.render_times = []; probe.worker_times = []; + }; + probe.end = () => { + probe.measuring = false; probe.measure_end_ms = performance.now(); + probe.measure_end_sim = probe.latest.sim_time; + probe.measure_end_lag_ms = probe.latest.metrics.lag_ms; + probe.measure_end_steps = probe.latest.metrics.physics_steps; + probe.measure_end_render_count = Number(document.querySelector('#canvas').dataset.renderCount || 0); + return {start: probe.measure_start_ms, end: probe.measure_end_ms}; + }; +} + +async function setTarget(page, target) { + for (const [index, axis] of ['X', 'Y', 'Z'].entries()) { + await page.getByRole('spinbutton', {name: `Tool target ${axis} in millimeters`}).fill(String(target[index] * 1000)); + } + await page.getByRole('button', {name: 'Apply target', exact: true}).click(); + await page.waitForFunction(value => window.__dvidiaLiveProbe.latest.target_position.every((coordinate, axis) => Math.abs(coordinate - value[axis]) < 1e-9), target); +} + +async function main() { + const [url, output] = process.argv.slice(2); + assert(url && output, 'Usage: node tests/browser/workstation_live.cjs URL OUTPUT_DIRECTORY'); + const seconds = Number(process.env.DVIDIA_BENCH_SECONDS || 20); + assert(Number.isFinite(seconds) && seconds >= 10 && seconds <= 1200, 'Benchmark duration must be 10–1200 seconds'); + const headless = process.env.DVIDIA_BENCH_HEADLESS !== '0'; + const software = process.env.DVIDIA_BENCH_RENDERER !== 'device'; + const channel = process.env.DVIDIA_BROWSER_CHANNEL || undefined; + await fs.mkdir(output, {recursive: true}); + const errors = [], consoleErrors = [], unexpectedRequests = [], failedRequests = [], responseErrors = [], requestOrigins = new Set(); + const origin = new URL(url).origin; + const allowedCDN = host => /^(?:[a-z0-9-]+\.)*cdn\.hf\.co$/.test(host) + || /^cdn-lfs(?:-[a-z0-9-]+)?\.hf\.co$/.test(host) || host === 'cas-bridge.xethub.hf.co'; + const browser = await chromium.launch({headless, channel, + args: software ? ['--use-angle=swiftshader', '--enable-unsafe-swiftshader'] : []}); + let page; let probe; let summary; + const controls = {}; + try { + page = await browser.newPage({viewport: {width: 1440, height: 1080}, deviceScaleFactor: 1, acceptDownloads: true}); + page.on('pageerror', error => errors.push(error.message)); + page.on('console', event => { if (event.type() === 'error') consoleErrors.push(event.text()); }); + page.on('requestfailed', request => failedRequests.push({url: request.url().split('?')[0], failure: request.failure()?.errorText})); + page.on('response', response => { if (response.status() >= 400) responseErrors.push({url: response.url().split('?')[0], status: response.status()}); }); + page.on('request', request => { + const target = new URL(request.url()); + if (['blob:', 'data:'].includes(target.protocol)) return; + requestOrigins.add(target.origin); + if (target.origin !== origin && !allowedCDN(target.hostname)) unexpectedRequests.push(target.origin + target.pathname); + }); + await page.addInitScript(installProbe); + const loadStarted = performance.now(); + await page.goto(url, {waitUntil: 'domcontentloaded'}); + await page.bringToFront(); + await page.waitForFunction(() => document.querySelector('#stage')?.dataset.ready === 'true', {}, {timeout: 120000}); + const loadMs = performance.now() - loadStarted; + await page.waitForFunction(() => window.__dvidiaLiveProbe.latest?.sim_time >= 1); + assert.equal(await page.evaluate(() => document.visibilityState), 'visible'); + const manifestResponse = await page.request.get(new URL('workstation.json', url).href); + assert(manifestResponse.ok()); + const manifestBytes = await manifestResponse.body(); const manifest = JSON.parse(manifestBytes); + const manifestSha256 = createHash('sha256').update(manifestBytes).digest('hex'); + const renderer = await page.evaluate(() => { + const gl = document.querySelector('#canvas').getContext('webgl2'); + const debug = gl.getExtension('WEBGL_debug_renderer_info'); + return {vendor: debug ? gl.getParameter(debug.UNMASKED_VENDOR_WEBGL) : gl.getParameter(gl.VENDOR), + renderer: debug ? gl.getParameter(debug.UNMASKED_RENDERER_WEBGL) : gl.getParameter(gl.RENDERER), + version: gl.getParameter(gl.VERSION), shading_language: gl.getParameter(gl.SHADING_LANGUAGE_VERSION), + user_agent: navigator.userAgent, hardware_concurrency: navigator.hardwareConcurrency, + device_memory_gib: navigator.deviceMemory ?? null}; + }); + + // Numeric controls provide a keyboard-accessible alternative to the drag gizmo. + const before = await page.evaluate(() => window.__dvidiaLiveProbe.latest.tcp_position); + await setTarget(page, [.38, .02, .25]); + await page.waitForFunction(initial => Math.hypot(...window.__dvidiaLiveProbe.latest.tcp_position.map((value, index) => value - initial[index])) > .003, before, {timeout: 5000}); + controls.target_motion_m = distance(before, await page.evaluate(() => window.__dvidiaLiveProbe.latest.tcp_position)); + controls.target_apply = true; + const slider = page.getByRole('slider', {name: 'Finger travel target'}); + await slider.focus(); await page.keyboard.press('Home'); + await page.waitForFunction(() => window.__dvidiaLiveProbe.latest.actual_jaw < .01, {}, {timeout: 5000}); + controls.gripper_closed_m = await page.evaluate(() => window.__dvidiaLiveProbe.latest.actual_jaw); + await page.keyboard.press('End'); + await page.waitForFunction(() => window.__dvidiaLiveProbe.latest.actual_jaw > .025, {}, {timeout: 5000}); + controls.gripper_open_m = await page.evaluate(() => window.__dvidiaLiveProbe.latest.actual_jaw); + await page.getByRole('button', {name: 'Pause', exact: true}).click(); + await page.waitForFunction(() => window.__dvidiaLiveProbe.latest.paused); + const pausedTime = await page.evaluate(() => window.__dvidiaLiveProbe.latest.sim_time); + await page.waitForTimeout(400); + assert.equal(await page.evaluate(() => window.__dvidiaLiveProbe.latest.sim_time), pausedTime); + controls.pause_preserved_sim_time = true; + await page.getByRole('button', {name: 'Reset', exact: true}).click(); + await page.waitForFunction(() => window.__dvidiaLiveProbe.latest.sim_time === 0 && window.__dvidiaLiveProbe.latest.paused); + controls.reset_restored_qpos = await page.evaluate(home => window.__dvidiaLiveProbe.latest.qpos.every((value, index) => Math.abs(value - home[index]) < 1e-12), manifest.home_qpos); + assert(controls.reset_restored_qpos); + await page.getByRole('button', {name: 'Resume', exact: true}).click(); + await page.waitForFunction(() => !window.__dvidiaLiveProbe.latest.paused && window.__dvidiaLiveProbe.latest.sim_time > .5); + const shoe = manifest.shoe_body_names[0]; + const shoeBefore = await page.evaluate(name => window.__dvidiaLiveProbe.latest.shoes[name].position, shoe); + await page.getByRole('button', {name: 'Nudge shoe', exact: true}).click(); + await page.waitForFunction(({name, initial}) => Math.hypot(...window.__dvidiaLiveProbe.latest.shoes[name].position.map((value, index) => value - initial[index])) > .0005, + {name: shoe, initial: shoeBefore}, {timeout: 4000}); + controls.nudge_displacement_m = distance(shoeBefore, await page.evaluate(name => window.__dvidiaLiveProbe.latest.shoes[name].position, shoe)); + controls.nudge_physical_response = true; + + // Isolate stability/throughput from initialization, resets and acceptance actions. + await page.getByRole('button', {name: 'Pause', exact: true}).click(); + await page.waitForFunction(() => window.__dvidiaLiveProbe.latest.paused); + await page.getByRole('button', {name: 'Reset', exact: true}).click(); + await page.waitForFunction(() => window.__dvidiaLiveProbe.latest.sim_time === 0 && window.__dvidiaLiveProbe.latest.paused); + await page.getByRole('button', {name: 'Resume', exact: true}).click(); + await page.waitForFunction(() => window.__dvidiaLiveProbe.latest.sim_time > .6); + await page.evaluate(() => window.__dvidiaLiveProbe.begin()); + const stabilityStart = performance.now(); + const targets = [[.38, .02, .25], [.32, -.12, .20], [.40, .10, .28], manifest.initial_target_xyz]; + let nextTarget = 0; let lastLog = 0; + while ((performance.now() - stabilityStart) / 1000 < seconds) { + const elapsed = (performance.now() - stabilityStart) / 1000; + if (elapsed >= nextTarget * 10) { + await setTarget(page, targets[nextTarget % targets.length]); + nextTarget += 1; + } + if (elapsed - lastLog >= 60) { + const status = await page.evaluate(() => ({sim: window.__dvidiaLiveProbe.latest.sim_time, + states: window.__dvidiaLiveProbe.state_count, errors: window.__dvidiaLiveProbe.errors.length})); + console.log(JSON.stringify({progress_seconds: Math.round(elapsed), ...status})); lastLog = elapsed; + } + await page.waitForTimeout(Math.min(500, Math.max(1, (seconds - elapsed) * 1000))); + assert.equal(await page.evaluate(() => document.visibilityState), 'visible', 'Stability benchmark must remain foreground'); + assert.equal(await page.evaluate(() => window.__dvidiaLiveProbe.errors.length), 0, 'Worker reported an error'); + } + await page.evaluate(() => window.__dvidiaLiveProbe.end()); + probe = await page.evaluate(() => { + const source = window.__dvidiaLiveProbe; + return Object.fromEntries(Object.entries(source).filter(([, value]) => typeof value !== 'function')); + }); + assert(probe.latest.metrics.samples_retained <= 2048, 'Worker timing retention must remain bounded'); + assert(probe.states.length <= 15000 && probe.commands.length <= 2000, 'Harness retention must remain bounded'); + const downloadPending = page.waitForEvent('download'); + await page.getByRole('button', {name: 'Download session data', exact: true}).click(); + const download = await downloadPending; + const receiptPath = path.join(output, 'session-receipt.json'); await download.saveAs(receiptPath); + const receipt = JSON.parse(await fs.readFile(receiptPath, 'utf8')); + assert.equal(receipt.source.manifest_sha256, manifestSha256); + assert(receipt.samples.length <= 3000 && receipt.commands.length <= 2000); + controls.receipt_export = true; + controls.receipt_retention = receipt.recording; + await page.screenshot({path: path.join(output, 'final-workstation.png'), fullPage: true}); + const wallSeconds = (probe.measure_end_ms - probe.measure_start_ms) / 1000; + const simSeconds = probe.measure_end_sim - probe.measure_start_sim; + const intervals = values => values.slice(1).map((value, index) => value - values[index]); + const stableLatencies = probe.latencies.filter(item => item.baseline_stable && item.command_distance_m > .005); + const measuredStates = probe.states.filter(state => state.wall_ms >= probe.measure_start_ms && state.wall_ms <= probe.measure_end_ms); + const actualSoftware = /swiftshader|llvmpipe|software/i.test(renderer.renderer); + const renderFps = (probe.measure_end_render_count - probe.measure_start_render_count) / wallSeconds; + const numericalValidity = probe.native_finite && !probe.errors.length && !probe.warnings.length; + const acceptancePassed = numericalValidity && !errors.length && !consoleErrors.length && !unexpectedRequests.length + && !failedRequests.length && Object.values(controls).every(value => value !== false) && stableLatencies.some(item => item.physical_response_ms !== null); + summary = {schema: 'dvidia.workstation-browser-benchmark/v1', passed: acceptancePassed, + passed_scope: 'Functional UI acceptance and numerical validity; performance targets are reported separately.', + functional_acceptance_passed: acceptancePassed, + quantile_method: 'Nearest-rank empirical quantiles; sample counts are reported for each distribution.', + run_started_at: probe.started_at, url, manifest_sha256: manifestSha256, + native_scene_sha256: manifest.native_scene.sha256, engine: probe.latest.engine, + browser: browser.version(), browser_channel: channel ?? 'playwright-chromium', headless, + requested_renderer: software ? 'SwiftShader software' : 'device default', renderer, + renderer_classification: actualSoftware ? 'software renderer; not a device GPU benchmark' : 'renderer reported above; hardware backing not independently established', + host: {os: `${os.platform()} ${os.release()} ${os.arch()}`, cpu: os.cpus()[0]?.model, + logical_cpus: os.cpus().length, ram_bytes: os.totalmem()}, + viewport: {width: 1440, height: 1080, device_scale_factor: 1}, load_to_ready_ms: loadMs, + controls, numerical_validity: numericalValidity, + performance_targets: {render_30_to_60_fps_met: renderFps >= 30 && renderFps <= 60.5, + real_time_physics_met: simSeconds / wallSeconds >= .99, + note: 'Performance depends on the recorded renderer, device and browser; failed targets do not change functional acceptance.'}, + stability: {requested_wall_seconds: seconds, measured_wall_seconds: wallSeconds, simulated_seconds: simSeconds, + real_time_factor: simSeconds / wallSeconds, physics_steps: probe.measure_end_steps - probe.measure_start_steps, + lag_added_ms: probe.measure_end_lag_ms - probe.measure_start_lag_ms, + foreground_throughout: !probe.visibility_events.some(event => event.wall_ms >= probe.measure_start_ms + && event.wall_ms <= probe.measure_end_ms && event.visibility !== 'visible'), + foreground_definition: 'document.visibilityState remained visible in the isolated browser; headless runs have no OS-visible window.', + warning_count: probe.warnings.length, native_state_samples: measuredStates.length, + cyclic_target_interval_seconds: 10, cyclic_target_commands: nextTarget}, + rendering: {render_invocations: probe.measure_end_render_count - probe.measure_start_render_count, + render_invocations_per_second: renderFps, render_interval_ms: distribution(intervals(probe.render_times)), + raf_callbacks_per_second: probe.raf_times.length / wallSeconds, raf_interval_ms: distribution(intervals(probe.raf_times)), + worker_states_per_second: probe.worker_times.length / wallSeconds, worker_state_interval_ms: distribution(intervals(probe.worker_times)), + target_30_to_60_render_fps_met: renderFps >= 30 && renderFps <= 60.5, + note: 'RAF cadence, Three.js render invocations and worker-state delivery are separate measurements. Render invocations do not measure GPU presentation completion.'}, + response_latency: {measurement: 'Main-thread command post to first received target echo, separately from first >=1 mm TCP movement projected toward the target.', + stable_baseline: 'At least 5 recent states within 350 ms, spread below 0.5 mm; commanded distance exceeds 5 mm.', + response_timeout_ms: 5000, superseded_commands: 'Unfinished responses remain missing when a newer target is issued.', + all_target_commands: probe.latencies.length, stable_baseline_commands: stableLatencies.length, + target_echo_ms: distribution(stableLatencies.map(item => item.target_echo_ms).filter(Number.isFinite)), + physical_response_ms: distribution(stableLatencies.map(item => item.physical_response_ms).filter(Number.isFinite)), + missing_physical_response: stableLatencies.filter(item => item.physical_response_ms === null).length}, + observed_worker_timing: {step_ms_p95: distribution(measuredStates.map(state => state.metrics.step_ms_p95)), + control_ms_p95: distribution(measuredStates.map(state => state.metrics.control_ms_p95)), + note: 'Distribution of worker rolling p95 snapshots, not an all-step timing distribution.'}, + memory: {browser_heap: await page.evaluate(() => performance.memory ? {used_js_heap_size: performance.memory.usedJSHeapSize, + total_js_heap_size: performance.memory.totalJSHeapSize, js_heap_size_limit: performance.memory.jsHeapSizeLimit} : null), + receipt_samples: receipt.samples.length, receipt_sample_limit: 3000, receipt_samples_dropped: receipt.recording.samples_dropped, + harness_states_retained: probe.states.length, harness_state_limit: 15000, harness_states_dropped: probe.states_dropped, + harness_frame_samples_dropped: probe.frame_samples_dropped, worker_timing_samples_retained: probe.latest.metrics.samples_retained}, + request_origins: [...requestOrigins], errors, console_errors: consoleErrors, failed_requests: failedRequests, + response_errors: responseErrors, + unexpected_requests: unexpectedRequests, warnings: probe.warnings, + limitations: ['Rigid synthetic shoe with uncalibrated materials.', 'No shoe-grasp or real-robot skill success claim.', + 'Browser instrumentation adds overhead; software rendering results do not establish device-GPU performance.']}; + await fs.writeFile(path.join(output, 'browser-benchmark.json'), JSON.stringify(summary, null, 2) + '\n'); + await fs.writeFile(path.join(output, 'browser-raw-samples.json'), JSON.stringify(probe, null, 2) + '\n'); + console.log(JSON.stringify(summary, null, 2)); + if (!acceptancePassed) process.exitCode = 1; + } catch (error) { + if (page) { + probe = await page.evaluate(() => window.__dvidiaLiveProbe ? Object.fromEntries(Object.entries(window.__dvidiaLiveProbe) + .filter(([, value]) => typeof value !== 'function')) : null).catch(() => null); + await fs.writeFile(path.join(output, 'browser-failure.json'), JSON.stringify({passed: false, error: error.stack, + errors, consoleErrors, unexpectedRequests, failedRequests, responseErrors, probe}, null, 2) + '\n'); + } + throw error; + } finally { await browser.close(); } +} +main().catch(error => { console.error(error); process.exitCode = 1; }); diff --git a/tests/browser/workstation_parity.mjs b/tests/browser/workstation_parity.mjs new file mode 100644 index 0000000..8d8fcf7 --- /dev/null +++ b/tests/browser/workstation_parity.mjs @@ -0,0 +1,108 @@ +/* Reproducible native/WASM parity, including force-only shoe perturbation. */ +import assert from 'node:assert/strict'; +import {readFile, writeFile, mkdtemp, rm} from 'node:fs/promises'; +import {createHash} from 'node:crypto'; +import os from 'node:os'; +import path from 'node:path'; +import {fileURLToPath, pathToFileURL} from 'node:url'; +import {build} from '../../viewer/node_modules/esbuild/lib/main.js'; +import loadMujoco from '../../viewer/node_modules/@mujoco/mujoco/mujoco.js'; +import {unpackNativeAssets} from '../../src/dvidia_training/workstation_assets.js'; + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..'); +const [sceneArg, fixtureArg, outputArg] = process.argv.slice(2); +if (!sceneArg || !fixtureArg || !outputArg) throw new Error('Usage: node tests/browser/workstation_parity.mjs SCENE FIXTURE OUTPUT'); +const scene = path.resolve(sceneArg); +const manifestRaw = await readFile(path.join(scene, 'workstation.json')); +const manifest = JSON.parse(manifestRaw); +const fixture = JSON.parse(await readFile(fixtureArg, 'utf8')); +const xml = await readFile(path.join(scene, 'scene.xml')); +const digest = bytes => createHash('sha256').update(bytes).digest('hex'); +assert.equal(digest(xml), fixture.native_scene_sha256, 'Fixture and WASM must use identical XML'); +assert.equal(digest(manifestRaw), fixture.manifest_sha256, 'Fixture and WASM must use identical settings'); +assert.equal(fixture.valid, true, 'Native simulation must be valid'); +const temporary = await mkdtemp(path.join(os.tmpdir(), 'dvidia-workstation-parity-')); +let engine; +try { + const compiled = path.join(temporary, 'worker.mjs'); + await build({entryPoints: [path.join(root, 'src/dvidia_training/workstation_worker.js')], outfile: compiled, + bundle: true, platform: 'node', format: 'esm', nodePaths: [path.join(root, 'viewer/node_modules')]}); + const {WorkstationEngine} = await import(pathToFileURL(compiled)); + const mj = await loadMujoco({wasmBinary: await readFile(path.join(root, 'viewer/node_modules/@mujoco/mujoco/mujoco.wasm'))}); + const vfs = new mj.MjVFS(); + let model; + try { + if (manifest.native_asset_bundle) { + const assets = await unpackNativeAssets(await readFile(path.join(scene, manifest.native_asset_bundle.path)), + manifest.native_asset_bundle, manifest.assets); + for (const asset of assets) vfs.addBuffer(asset.path, asset.bytes); + } else for (const asset of manifest.assets) { + const bytes = await readFile(path.join(scene, asset.path)); + assert.equal(bytes.length, asset.bytes); assert.equal(digest(bytes), asset.sha256); + vfs.addBuffer(asset.path, new Uint8Array(bytes)); + } + model = mj.MjModel.from_xml_string(xml.toString('utf8'), vfs); + } finally { vfs.delete(); } + engine = new WorkstationEngine(mj, model, manifest); + const max = {qpos: 0, qvel: 0, ctrl: 0, tcp_position: 0, shoe_position: 0}; + let differingContacts = 0; let differingActiveContacts = 0; let error = null; let completed = 0; + const contactDifferences = []; + const schedule = new Map(); + for (const command of fixture.commands) schedule.set(command.step, [...(schedule.get(command.step) ?? []), command]); + const started = performance.now(); + const samples = []; const fullStepMs = []; + try { + for (let index = 0; index < fixture.physics_steps; index += 1) { + for (const command of schedule.get(index) ?? []) engine.applyCommand(command); + const stepStarted = performance.now(); + engine.step(); completed += 1; + fullStepMs.push(performance.now() - stepStarted); + if ((index + 1) % fixture.control_stride !== 0) continue; + const native = fixture.trace[(index + 1) / fixture.control_stride - 1]; + const state = engine.state(); + const fields = {qpos: state.qpos, qvel: state.qvel, ctrl: state.ctrl, + tcp_position: state.tcp_position, shoe_position: state.shoes[manifest.shoe_body_names[0]].position}; + for (const [name, values] of Object.entries(fields)) { + assert.equal(values.length, native[name].length); + max[name] = Math.max(max[name], ...values.map((value, item) => Math.abs(value - native[name][item]))); + } + if (state.contacts !== native.contacts) differingContacts += 1; + if (state.active_contacts !== native.active_contacts) differingActiveContacts += 1; + if (state.contacts !== native.contacts || state.active_contacts !== native.active_contacts) { + contactDifferences.push({completed_steps: index + 1, native_contacts: native.contacts, wasm_contacts: state.contacts, + native_active_contacts: native.active_contacts, wasm_active_contacts: state.active_contacts, + native_normal_forces_n: native.contact_normal_forces_n, wasm_normal_forces_n: state.contact_normal_forces_n}); + } + samples.push({completed_steps: index + 1, tcp_position: state.tcp_position, + shoe_position: fields.shoe_position, contacts: state.contacts, active_contacts: state.active_contacts, + tracking_error_m: state.tracking_error_m}); + } + } catch (exception) { error = exception.message; } + const wallSeconds = (performance.now() - started) / 1000; + const thresholds = {qpos: 1e-6, qvel: 1e-5, ctrl: 1e-6, tcp_position: 1e-6, shoe_position: 1e-6}; + const orderedStepMs = fullStepMs.slice().sort((a, b) => a - b); + const quantile = fraction => orderedStepMs[Math.floor((orderedStepMs.length - 1) * fraction)] ?? null; + const numericallyValid = !error && completed === fixture.physics_steps && engine.warnings.length === 0; + const numericalParityPassed = numericallyValid && Object.entries(max).every(([field, value]) => value <= thresholds[field]); + const parityPassed = numericalParityPassed && differingContacts === 0; + const result = {schema: 'dvidia.workstation-wasm-parity/v1', valid: numericallyValid, error, + strict_parity_passed: parityPassed, numerical_parity_passed: numericalParityPassed, + active_contact_count_parity_passed: differingActiveContacts === 0, + engine: mj.mj_versionString(), node: process.version, platform: `${os.platform()} ${os.release()} ${os.arch()}`, + hardware: {cpu: os.cpus()[0]?.model ?? null, logical_cpus: os.cpus().length, total_memory_bytes: os.totalmem()}, + native_scene_sha256: fixture.native_scene_sha256, manifest_sha256: fixture.manifest_sha256, + simulated_seconds: completed * manifest.timestep, completed_steps: completed, + compared_states: samples.length, maximum_absolute_errors: max, thresholds, + differing_contact_count_states: differingContacts, warnings: engine.warnings, + differing_active_contact_count_states: differingActiveContacts, active_contact_threshold_n: .001, + contact_differences: contactDifferences, + wall_seconds: wallSeconds, real_time_factor: completed * manifest.timestep / wallSeconds, + step_ms_p50: quantile(.5), step_ms_p95: quantile(.95), step_ms_p99: quantile(.99), step_ms_max: quantile(1), + control_ms_p95: engine.controlSamples.quantile(.95), + timing_window: 'All 15,000 physics steps including startup; all 1,500 control updates. Comparison overhead included in wall time.', + process_memory: process.memoryUsage(), trace: samples, + scope: 'Native-versus-WASM deterministic controller/physics parity; not a shoe grasp success benchmark or real-robot validation.'}; + await writeFile(outputArg, JSON.stringify(result, null, 2) + '\n'); + console.log(JSON.stringify(Object.fromEntries(Object.entries(result).filter(([key]) => !['trace', 'contact_differences'].includes(key))), null, 2)); + if (!parityPassed) process.exitCode = 1; +} finally { engine?.dispose(); await rm(temporary, {recursive: true, force: true}); } diff --git a/tests/browser/workstation_ui.cjs b/tests/browser/workstation_ui.cjs new file mode 100644 index 0000000..11f4606 --- /dev/null +++ b/tests/browser/workstation_ui.cjs @@ -0,0 +1,82 @@ +/* Live workstation browser acceptance. + * Usage: node tests/browser/workstation_ui.cjs URL NEW_OUTPUT_DIRECTORY + * Set DVIDIA_PLAYWRIGHT_MODULE when Playwright is installed outside this repo. + * This measures functional interactions, not hardware or rendering performance. + */ +const assert=require('node:assert/strict'); +const fs=require('node:fs/promises'); +const path=require('node:path'); +const {chromium}=require(process.env.DVIDIA_PLAYWRIGHT_MODULE||path.join(__dirname,'../../viewer/node_modules/playwright')); +async function pixels(page){ + await page.evaluate(()=>new Promise(r=>requestAnimationFrame(()=>requestAnimationFrame(r)))); + const image=await page.locator('#canvas').screenshot(); + return await page.evaluate(async data=>{const im=new Image();im.src='data:image/png;base64,'+data;await im.decode();const c=document.createElement('canvas');c.width=im.width;c.height=im.height;const ctx=c.getContext('2d');ctx.drawImage(im,0,0);const p=ctx.getImageData(0,0,c.width,c.height).data;let wood=0,navy=0;const red=[];for(let y=0;y120&&r-g>6&&g-b>15)wood++;if(r<100&&g<140&&b<160&&b-r>4)navy++;if(r>150&&g<95&&b<95)red.push([x,y]);}return {wood,navy,width:c.width,height:c.height,red};},image.toString('base64')); +} +async function state(page){return page.evaluate(()=>window.__workstationState);} +(async()=>{ + const [url,output]=process.argv.slice(2); + assert(url&&output,'Provide the workstation URL and a new output directory.'); + assert(['http:','https:'].includes(new URL(url).protocol),'Use HTTP or HTTPS.'); + await fs.mkdir(output,{recursive:true}); + const file=name=>path.join(output,name); + const browser=await chromium.launch({headless:true}); + const page=await browser.newPage({viewport:{width:1440,height:1100},deviceScaleFactor:1}); + const errors=[],responses=[];page.on('pageerror',e=>errors.push(e.message));page.on('response',r=>{if(r.status()>=400)responses.push([r.url(),r.status()])}); + await page.addInitScript(()=>{const Native=window.Worker;window.Worker=class extends Native{constructor(...args){super(...args);this.addEventListener('message',e=>{if(e.data?.state)window.__workstationState=e.data.state;});}};}); + try { + const navigation=await page.goto(url,{waitUntil:'domcontentloaded'}); + assert(navigation?.ok(),'Workstation document must load successfully.'); + await page.waitForFunction(()=>['true','error'].includes(document.querySelector('#stage')?.dataset.ready),{},{timeout:120000}); + assert.equal(await page.locator('#stage').getAttribute('data-ready'),'true',await page.locator('#loading-message').textContent()); + await page.waitForFunction(()=>window.__workstationState?.sim_time>.3); + const before=await state(page); + await page.locator('#pause').click();await page.waitForFunction(()=>window.__workstationState?.paused===true); + const stopped=await state(page);await page.waitForTimeout(400);assert.equal((await state(page)).sim_time,stopped.sim_time); + const px=await pixels(page);assert(px.wood>1000&&px.navy>150,'Actual native scene must render');assert(px.red.length>10,'Translation gizmo must render'); + const sorted=px.red.sort((a,b)=>b[0]-a[0]);const right=sorted.slice(0,Math.min(20,sorted.length));const gx=right.reduce((s,p)=>s+p[0],0)/right.length,gy=right.reduce((s,p)=>s+p[1],0)/right.length; + const box=await page.locator('#canvas').boundingBox();const start=(await state(page)).target_position; + await page.mouse.move(box.x+gx,box.y+gy);await page.mouse.down();await page.mouse.move(box.x+gx+35,box.y+gy+7,{steps:12});await page.mouse.up(); + await page.waitForFunction(old=>window.__workstationState.target_position.some((n,i)=>Math.abs(n-old[i])>.001),start,{timeout:10000}); + const dragged=(await state(page)).target_position; + await page.locator('#pause').click();await page.waitForFunction(()=>window.__workstationState?.paused===false); + for(const [axis,value]of [['x','370'],['y','-100'],['z','240']])await page.locator('#target-'+axis).fill(value); + await page.locator('#target-z').blur();await page.waitForTimeout(300);assert.deepEqual(await Promise.all(['x','y','z'].map(a=>page.locator('#target-'+a).inputValue())),['370','-100','240'],'Blurred coordinate drafts survive live states');await page.locator('#apply-target').click(); + await page.waitForFunction(()=>Math.abs(window.__workstationState.target_position[1]+.1)<1e-8&&Math.abs(window.__workstationState.target_position[0]-.37)<1e-8); + await page.waitForFunction(()=>window.__workstationState.tracking_error_m<.01,{},{timeout:15000}); + const reached=await state(page);assert(reached.qpos.some((n,i)=>Math.abs(n-before.qpos[i])>.01),'Actual joint positions must change'); + await page.locator('#gripper').evaluate(e=>{e.value='20';e.dispatchEvent(new Event('input',{bubbles:true}));}); + await page.waitForFunction(()=>Math.abs(window.__workstationState.jaw-.02)<1e-8); + await page.waitForFunction(()=>Math.abs(window.__workstationState.actual_jaw-.02)<.002,{},{timeout:10000}); + const prePush=(await state(page)).shoes.shoe_trainer_left.position; + await page.locator('#push').click(); + await page.waitForFunction(p=>Math.hypot(...window.__workstationState.shoes.shoe_trainer_left.position.map((n,i)=>n-p[i]))>.001,prePush,{timeout:10000}); + const postPush=(await state(page)).shoes.shoe_trainer_left.position; + await page.locator('#collision').click();assert.equal(await page.locator('#collision').getAttribute('aria-pressed'),'true');await page.locator('#collision').click(); + await page.locator('#gizmo').click();assert.equal(await page.locator('#gizmo').getAttribute('aria-pressed'),'false');await page.locator('#gizmo').click(); + await page.locator('[data-camera=top]').click();await page.locator('[data-camera=front]').click();await page.locator('#home-camera').click(); + const download=page.waitForEvent('download');await page.locator('#receipt').click();const artifact=await download;await artifact.saveAs(file('session.json'));const receipt=JSON.parse(await fs.readFile(file('session.json'),'utf8'));assert(receipt.commands.some(c=>c.type==='target'));assert(receipt.commands.some(c=>c.type==='push'&&c.impulse));assert(receipt.samples.length>0&&receipt.samples.some(s=>s.body_pos.length>3)); + await page.locator('#reset').click();await page.waitForFunction(()=>window.__workstationState.sim_time<1&&Math.abs(window.__workstationState.target_position[1]+.06)<1e-8); + // A bounded XYZ box does not guarantee the fixed-orientation tool can reach + // every point. Verify the UI stops saying Approaching for the known high case. + for(const [axis,value]of [['x','360'],['y','-60'],['z','320']])await page.locator('#target-'+axis).fill(value); + await page.locator('#apply-target').click(); + await page.waitForFunction(()=>Math.abs(window.__workstationState.target_position[2]-.32)<1e-8); + const highStart=(await state(page)).sim_time; + await page.waitForFunction(start=>window.__workstationState.sim_time>=start+4.1&&document.querySelector('#tool-state').dataset.state==='limited',highStart,{timeout:30000}); + const high=await state(page); + assert(high.tracking_error_m>.005,'The unreached status requires measured error above 5 mm'); + assert.match(await page.locator('#tool-state').innerText(),/Target not reached/); + const highTarget={target:high.target_position,error_m:high.tracking_error_m,simulated_seconds:high.sim_time-highStart,status:await page.locator('#tool-state').innerText()}; + await page.screenshot({path:file('target-not-reached.png'),fullPage:true}); + await page.locator('#reset').click(); + await page.waitForFunction(()=>window.__workstationState.sim_time<1&&Math.abs(window.__workstationState.target_position[2]-.27)<1e-8); + await page.waitForFunction(()=>document.querySelector('#tool-state').dataset.state!=='limited'); + await page.waitForTimeout(500); + await page.locator('#pause').click();await page.waitForFunction(()=>window.__workstationState.paused===true); + const layouts=[]; + for(const width of[1440,390,320]){await page.setViewportSize({width,height:width===1440?1100:900});await page.locator('#home-camera').click();const p=await pixels(page);assert(p.wood>1000&&p.navy>30);const caption=await page.locator('#scene-caption').boundingBox();const sceneTools=await page.locator('#gizmo').boundingBox();assert(caption.x+caption.width<=sceneTools.x-8,'Scene caption must not run under display controls at '+width);const overflow=await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth+1);assert.equal(overflow,false,'No horizontal overflow '+width);await page.screenshot({path:file('workstation-'+width+'.png'),fullPage:true});layouts.push({width,pixels:{wood:p.wood,navy:p.navy},overflow});} + assert.deepEqual(errors,[]);assert.deepEqual(responses,[]); + const result={passed:true,url,scope:'Headless browser visual and interaction acceptance; not a hardware performance benchmark.',pointerDrag:{start,dragged},targetResponse:{criterion:'Native joints changed and error fell below 10 mm; not a final precision qualification.',error_m:reached.tracking_error_m,tcp:reached.tcp_position},shoeNudge:{before:prePush,after:postPush},pauseStable:true,blurredCoordinateDraftsPreserved:true,highTarget,receiptCommands:receipt.commands.length,receiptSamples:receipt.samples.length,layouts,errors,responses}; + await fs.writeFile(file('acceptance.json'),JSON.stringify(result,null,2)+'\n');console.log(JSON.stringify(result,null,2)); + }finally{await browser.close();} +})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/tests/test_workstation.py b/tests/test_workstation.py new file mode 100644 index 0000000..ee95092 --- /dev/null +++ b/tests/test_workstation.py @@ -0,0 +1,312 @@ +"""Native motion and portable browser-physics artifact contracts.""" +from hashlib import sha256 +import gzip +import json +import os +from pathlib import Path +import tempfile +import unittest + +from dvidia_training import workstation as ws, reference_sim as sim, robot_profiles + + +class WorkstationInputs(unittest.TestCase): + def test_native_asset_bundle_preserves_exact_bytes_and_rejects_corruption(self): + raw=b'exact pinned mesh bytes\n' + asset={'path':'assets/example.obj','bytes':len(raw),'sha256':sha256(raw).hexdigest()} + def fixture(value): + packed=gzip.compress(value,mtime=0) + bundle={'path':'native-assets.bin.gz','compression':'gzip','bytes':len(packed), + 'sha256':sha256(packed).hexdigest(),'uncompressed_bytes':len(raw)} + return bundle,{asset['path']:raw,bundle['path']:packed} + bundle,payload=fixture(raw) + self.assertEqual(ws._unpack_native_assets(bundle,[asset],payload),raw) + for value in (raw[:-1],raw+b'excess',b'x'*len(raw)): + damaged,blobs=fixture(value) + with self.subTest(value=value),self.assertRaises(ValueError): + ws._unpack_native_assets(damaged,[asset],blobs) + with self.assertRaises(ValueError): + ws._unpack_native_assets({**bundle,'sha256':'0'*64},[asset],payload) + with self.assertRaises(ValueError): + ws._unpack_native_assets({**bundle,'uncompressed_bytes':ws.MAX_TOTAL_BYTES+1},[asset],payload) + truncated=payload[bundle['path']][:-8] + with self.assertRaises(ValueError): + ws._unpack_native_assets({**bundle,'bytes':len(truncated),'sha256':sha256(truncated).hexdigest()}, + [asset],{**payload,bundle['path']:truncated}) + + def test_vectors_reject_nonfinite_and_ambiguous_values(self): + for value in (None, '1,2,3', [True, 0, 0], [float('nan'), 0, 0], [0, 0], [100, 0, 0], [10**1000, 0, 0]): + with self.subTest(value=value), self.assertRaises(ValueError): + ws._vec(value, 3, 'target') + + def test_protocol_is_bounded_authored_tracking_with_no_grasp_claim(self): + plan = ws.protocol() + self.assertEqual(len(plan['actions']), 6) + self.assertEqual(plan['timestep'], .002) + for action in plan['actions']: + self.assertEqual(action['control_steps'], 100) + self.assertTrue(all(low <= item <= high for item, (low, high) in zip(action['target'], ws.BOUNDS))) + self.assertIn('not reported outcomes', ws.protocol.__doc__) + + +@unittest.skipUnless(os.environ.get('DVIDIA_ROBOT_PROFILE_ASSETS'), 'Set DVIDIA_ROBOT_PROFILE_ASSETS to the pinned asset root') +class NativeWorkstationTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.assets = Path(os.environ['DVIDIA_ROBOT_PROFILE_ASSETS']) + cls.mj, cls.np = sim._native_imports() + cls.model = ws.build_model(cls.assets) + cls.temporary = tempfile.TemporaryDirectory() + cls.root = Path(cls.temporary.name) + cls.runtime = cls.root/'runtime' + cls.runtime.mkdir() + for source in ws.RUNTIME_FILES.values(): + (cls.runtime/source).write_bytes(b'\0asm\x01\0\0\0' if source.endswith('.wasm') else b'fixture runtime\n') + cls.output = cls.root/'export' + cls.exported = ws.export(cls.assets, cls.output, runtime_directory=cls.runtime) + + @classmethod + def tearDownClass(cls): + cls.temporary.cleanup() + + def test_upstream_actuators_mass_inertia_and_joint_contracts_are_unchanged(self): + baseline = robot_profiles.build_model('piper', self.assets, timestep=.002) + model = self.model + self.assertEqual((model.nq, model.nv, model.nu, model.neq, model.nmocap), (15, 14, 7, 1, 0)) + for key in ('actuator_ctrlrange', 'actuator_forcerange', 'actuator_gainprm', 'actuator_biasprm', 'actuator_trnid'): + self.np.testing.assert_array_equal(getattr(model, key), getattr(baseline, key)) + for key in ('body_mass', 'body_inertia', 'body_gravcomp'): + self.np.testing.assert_array_equal(getattr(model, key)[:baseline.nbody], getattr(baseline, key)) + self.np.testing.assert_array_equal(model.jnt_range[:8], baseline.jnt_range) + _, shoe = ws._ids(model) + self.assertAlmostEqual(model.body_mass[shoe], .3) + self.assertEqual(int(model.jnt_type[model.body_jntadr[shoe]]), int(self.mj.mjtJoint.mjJNT_FREE)) + self.assertEqual(model.body_gravcomp[shoe], 0) + + def test_reset_is_deterministic_and_has_no_hidden_settling_or_attachment(self): + first, second = ws.initialize(self.model), ws.initialize(self.model) + self.np.testing.assert_array_equal(first.qpos, second.qpos) + self.assertEqual(first.time, 0) + self.assertFalse(self.np.any(first.qvel)) + self.assertFalse(self.np.any(first.xfrc_applied)) + self.assertFalse(self.np.any(first.qfrc_applied)) + self.assertEqual(first.ncon, 0) + self.assertLess(ws.state(self.model, first, ws.HOME_TARGET)['position_error_m'], 1e-7) + + def test_target_uses_rate_limited_actuators_and_real_dynamics(self): + model, data = self.model, ws.initialize(self.model) + previous_ctrl, previous_qpos = data.ctrl.copy(), data.qpos.copy() + desired = ws.controller_action(model, data, [.32, -.145, .18], .035) + self.np.testing.assert_array_equal(data.qpos, previous_qpos) + self.np.testing.assert_array_equal(data.ctrl, previous_ctrl) + control = {} + ws.run_control(model, data, control, [.32, -.145, .18], .035, 1) + self.assertLessEqual(float(self.np.max(self.np.abs(data.ctrl[:6]-previous_ctrl[:6]))), .0030000001) + self.assertGreater(float(self.np.linalg.norm(data.qpos[:6]-previous_qpos[:6])), 0) + self.assertGreater(float(self.np.linalg.norm(data.qpos[:6]-desired[:6])), .01) + for _ in range(199): + ws.run_control(model, data, control, [.32, -.145, .18], .035, 10) + self.assertLess(ws.state(model, data, [.32, -.145, .18])['position_error_m'], .005) + self.assertTrue(all(item.number == 0 for item in data.warning)) + + def test_control_chunking_keeps_the_physics_clock(self): + model = self.model + first, second = ws.initialize(model), ws.initialize(model) + a, b = {}, {} + for _ in range(20): + ws.run_control(model, first, a, [.32, -.145, .18], .02, 10) + for chunk in (3, 2, 5): + ws.run_control(model, second, b, [.32, -.145, .18], .02, chunk) + self.np.testing.assert_array_equal(first.qpos, second.qpos) + self.np.testing.assert_array_equal(first.ctrl, second.ctrl) + self.assertEqual(a, b) + + def test_shoe_settles_with_gravity_and_true_support_force(self): + model, data = self.model, ws.initialize(self.model) + _, shoe = ws._ids(model) + self.assertAlmostEqual(data.xpos[shoe, 2], .012) + for _ in range(50): + ws.step(model, data, ws.HOME_TARGET, .035) + self.assertLess(abs(data.xpos[shoe, 2]), .0005) + force = 0. + table = self.mj.mj_name2id(model, self.mj.mjtObj.mjOBJ_GEOM, 'workstation_table_top') + for index in range(data.ncon): + contact = data.contact[index] + if table in (contact.geom1, contact.geom2): + other = contact.geom2 if contact.geom1 == table else contact.geom1 + if model.geom_bodyid[other] == shoe: + wrench = self.np.zeros(6) + self.mj.mj_contactForce(model, data, index, wrench) + force += wrench[0] + self.assertAlmostEqual(force, .3*9.81, delta=.02) + self.assertFalse(self.np.any(data.xfrc_applied)) + free = ws.build_model(self.assets) + free.geom_contype[table] = free.geom_conaffinity[table] = 0 + falling = ws.initialize(free) + for _ in range(10): + ws.step(free, falling, ws.HOME_TARGET, .035) + self.assertLess(falling.xpos[shoe, 2], -.10) + + def test_impulse_is_a_bounded_single_tick_and_clears_afterward(self): + model, data = self.model, ws.initialize(self.model) + for _ in range(50): + ws.step(model, data, ws.HOME_TARGET, .035) + before = ws.state(model, data)['shoe_position'] + ws.step(model, data, ws.HOME_TARGET, .035, impulse_xyz=[0, .12, 0]) + for _ in range(20): + ws.step(model, data, ws.HOME_TARGET, .035) + after = ws.state(model, data)['shoe_position'] + self.assertGreater(float(self.np.linalg.norm(self.np.asarray(after)-before)), .001) + self.assertFalse(self.np.any(data.xfrc_applied)) + for impulse in ([.1, .1, 0], [0, .121, 0], [0, float('nan'), 0]): + before = data.qpos.copy() + with self.assertRaises(ValueError): + ws.step(model, data, ws.HOME_TARGET, .035, impulse_xyz=impulse) + self.np.testing.assert_array_equal(data.qpos, before) + + def test_invalid_targets_jaws_and_step_counts_fail_before_motion(self): + data = ws.initialize(self.model) + before = data.qpos.copy() + for args in [([.6, 0, .2], .035, 10), (list(ws.HOME_TARGET), .04, 10), + (list(ws.HOME_TARGET), .035, True), (list(ws.HOME_TARGET), .035, 0), + (list(ws.HOME_TARGET), .035, 101)]: + with self.assertRaises(ValueError): + ws.run_control(self.model, data, {}, *args) + self.np.testing.assert_array_equal(data.qpos, before) + + def test_export_xml_recompiles_to_identical_model_and_home(self): + result = ws.inspect_export(self.output) + manifest = json.loads((self.output/'workstation.json').read_text()) + self.assertEqual(result['compiled_model_sha256'], sim.model_digest(self.model)) + self.assertEqual(manifest['interaction_limits']['push_impulse_norm_max_ns'], .12) + self.assertEqual(manifest['interaction_limits']['push_duration_s'], .002) + blobs = {item['path']:(self.output/item['path']).read_bytes() for item in manifest['assets']} + native = self.mj.MjModel.from_xml_string((self.output/'scene.xml').read_text(), assets=blobs) + self.assertEqual(sim.model_digest(native), sim.model_digest(self.model)) + self.np.testing.assert_array_equal(ws.initialize(native).qpos, manifest['home_qpos']) + self.assertEqual(json.loads((self.output/'model.json').read_text())['scope'], ws.SCOPE) + self.assertTrue((self.output/'index.html').exists()) + self.assertFalse((self.output/'workstation.html').exists()) + with self.assertRaises(ValueError): + ws.export(self.assets, self.output, runtime_directory=self.runtime) + + def test_legacy_export_without_delivery_bundle_remains_inspectable(self): + import shutil + directory=self.root/'legacy-export' + shutil.copytree(self.output,directory) + manifest=json.loads((directory/'workstation.json').read_text()) + del manifest['native_asset_bundle'] + self._reseal(directory,'workstation.json',ws._json(manifest)) + (directory/'native-assets.bin.gz').unlink() + seal=json.loads((directory/'workstation-integrity.json').read_text()) + del seal['files']['native-assets.bin.gz'] + (directory/'workstation-integrity.json').write_bytes(ws._json(seal)) + self.assertEqual(ws.inspect_export(directory)['compiled_model_sha256'],sim.model_digest(self.model)) + + def test_compressed_wasm_matches_original_and_old_exports_remain_readable(self): + import shutil + manifest=json.loads((self.output/'workstation.json').read_text()) + raw=(self.output/'mujoco.wasm').read_bytes() + self.assertEqual(gzip.decompress((self.output/'mujoco.wasm.gz').read_bytes()),raw) + self.assertEqual(manifest['native_wasm']['sha256'],sha256(raw).hexdigest()) + directory=self.root/'legacy-wasm' + shutil.copytree(self.output,directory) + del manifest['native_wasm'];del manifest['wasm_bundle'] + self._reseal(directory,'workstation.json',ws._json(manifest)) + (directory/'mujoco.wasm.gz').unlink() + seal=json.loads((directory/'workstation-integrity.json').read_text()) + del seal['files']['mujoco.wasm.gz'] + (directory/'workstation-integrity.json').write_bytes(ws._json(seal)) + self.assertEqual(ws.inspect_export(directory)['compiled_model_sha256'],sim.model_digest(self.model)) + + def test_compressed_geometry_digest_is_verified_and_legacy_metadata_remains_readable(self): + import shutil + directory=self.root/'geometry-digest' + shutil.copytree(self.output,directory) + scene=json.loads((directory/'model.json').read_text()) + self.assertEqual(scene['geometry_binary']['compressed_sha256'], + sha256((directory/'geometry.bin.gz').read_bytes()).hexdigest()) + for incorrect in ('0'*64,None): + scene['geometry_binary']['compressed_sha256']=incorrect + self._reseal(directory,'model.json',ws._json(scene)) + with self.assertRaisesRegex(ValueError,'compressed geometry checksum'): + ws.inspect_export(directory) + del scene['geometry_binary']['compressed_sha256'] + self._reseal(directory,'model.json',ws._json(scene)) + self.assertEqual(ws.inspect_export(directory)['compiled_model_sha256'],sim.model_digest(self.model)) + + def test_resealed_wasm_bundle_must_decode_to_original_engine(self): + import shutil + directory=self.root/'bad-wasm-bundle' + shutil.copytree(self.output,directory) + original=(directory/'mujoco.wasm').read_bytes() + packed=gzip.compress(b'x'*len(original),mtime=0) + self._reseal(directory,'mujoco.wasm.gz',packed) + manifest=json.loads((directory/'workstation.json').read_text()) + manifest['wasm_bundle'].update(bytes=len(packed),sha256=sha256(packed).hexdigest()) + self._reseal(directory,'workstation.json',ws._json(manifest)) + with self.assertRaisesRegex(ValueError,'original engine'): + ws.inspect_export(directory) + + def test_inspection_rejects_bundle_corruption_even_after_resealing(self): + import shutil + directory=self.root/'bad-bundle' + shutil.copytree(self.output,directory) + packed=gzip.compress(b'incorrect native mesh bytes',mtime=0) + self._reseal(directory,'native-assets.bin.gz',packed) + manifest=json.loads((directory/'workstation.json').read_text()) + manifest['native_asset_bundle'].update(bytes=len(packed),sha256=sha256(packed).hexdigest()) + self._reseal(directory,'workstation.json',ws._json(manifest)) + with self.assertRaises(ValueError):ws.inspect_export(directory) + + def _reseal(self, path, name, raw): + (path/name).write_bytes(raw) + sealpath = path/'workstation-integrity.json' + seal = json.loads(sealpath.read_text()) + seal['files'][name] = {'bytes':len(raw), 'sha256':sha256(raw).hexdigest()} + sealpath.write_bytes(ws._json(seal)) + + def test_export_inspection_rejects_resealed_geometry_provenance_and_xml_imports(self): + import shutil + cases = ['metadata', 'geometry', 'provenance', 'xml', 'license', 'asset'] + for case in cases: + directory = self.root/case + shutil.copytree(self.output, directory) + if case in ('metadata', 'provenance'): + value = json.loads((directory/'workstation.json').read_text()) + if case == 'metadata':value['home_qpos'][0] += .1 + else:value['provenance']['commit'] = '0'*40 + self._reseal(directory, 'workstation.json', ws._json(value)) + elif case == 'geometry': + value = json.loads((directory/'model.json').read_text()) + value['geoms'][0]['size'][0] += .1 + self._reseal(directory, 'model.json', ws._json(value)) + elif case == 'xml': + raw = (directory/'scene.xml').read_bytes().replace(b'
', b'') + self._reseal(directory, 'scene.xml', raw) + value = json.loads((directory/'workstation.json').read_text()) + value['native_scene'] = {'path':'scene.xml', 'bytes':len(raw), 'sha256':sha256(raw).hexdigest()} + self._reseal(directory, 'workstation.json', ws._json(value)) + else: + name = 'licenses/agilex_piper/LICENSE' if case == 'license' else 'assets/base_link.stl' + self._reseal(directory, name, b'changed') + with self.subTest(case=case), self.assertRaises(ValueError): + ws.inspect_export(directory) + + def test_export_rejects_symlinks_unknown_files_and_missing_runtime_without_partial_output(self): + import shutil + directory = self.root/'symlink' + shutil.copytree(self.output, directory) + (directory/'extra').symlink_to(self.runtime) + with self.assertRaises(ValueError):ws.inspect_export(directory) + missing_runtime = self.root/'missing-runtime' + missing_runtime.mkdir() + destination = self.root/'must-not-exist' + with self.assertRaises((ValueError, OSError)): + ws.export(self.assets, destination, runtime_directory=missing_runtime) + self.assertFalse(destination.exists()) + self.assertFalse(list(self.root.glob('.dvidia-workstation-*'))) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_workstation_benchmark.py b/tests/test_workstation_benchmark.py new file mode 100644 index 0000000..870f028 --- /dev/null +++ b/tests/test_workstation_benchmark.py @@ -0,0 +1,41 @@ +"""Benchmark failure retention is part of the publication contract.""" +from pathlib import Path +import json +import tempfile +import unittest +from unittest.mock import patch + +from dvidia_training import workstation_benchmark as bench + + +class WorkstationBenchmarkTests(unittest.TestCase): + def test_protocol_retains_all_targets_and_negative_control(self): + plan=bench.protocol(10) + self.assertEqual(len(plan['attempts']),20) + self.assertEqual(sum(case['kind']=='tracking' for case in plan['attempts']),16) + self.assertEqual(sum(case['kind']=='gravity_control' for case in plan['attempts']),1) + for invalid in (True,0,9,601,10.5): + with self.subTest(value=invalid),self.assertRaises(ValueError):bench.protocol(invalid) + + def test_all_failed_model_loads_still_produce_complete_report(self): + try: + bench.sim._native_imports() + except ImportError: + self.skipTest('Optional native runtime is not installed') + with tempfile.TemporaryDirectory() as temporary: + output=Path(temporary)/'evidence' + with patch.object(bench.ws,'build_model',side_effect=ValueError('deliberate missing asset fixture')): + result=bench.benchmark('fixture',output,stability_seconds=10) + self.assertEqual(result['attempts'],20) + self.assertEqual(result['valid_attempts'],0) + self.assertEqual(result['tracking']['unmeasured_attempts'],16) + self.assertIsNone(result['tracking']['worst_position_error_m']) + self.assertIsNone(result['timing']['compute_ms_max']) + self.assertEqual(result['timing']['intervals'],0) + attempts=json.loads((output/'attempts.json').read_text()) + self.assertEqual(len(attempts),20) + self.assertTrue(all(not item['passed'] and item['errors'] for item in attempts)) + self.assertTrue((output/'integrity.json').is_file()) + + +if __name__=='__main__':unittest.main() diff --git a/third_party/mujoco/LICENSE.txt b/third_party/mujoco/LICENSE.txt new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/third_party/mujoco/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/third_party/mujoco/README.md b/third_party/mujoco/README.md new file mode 100644 index 0000000..5a28608 --- /dev/null +++ b/third_party/mujoco/README.md @@ -0,0 +1 @@ +MuJoCo 3.15.0 is distributed under Apache-2.0. License and dependency notices are retained from the matching official Python distribution, including a conservative superset of native dependencies. The browser binary comes from the pinned official @mujoco/mujoco npm distribution. DVIDIA does not modify that binary. diff --git a/third_party/mujoco/THIRD_PARTY_NOTICES.txt b/third_party/mujoco/THIRD_PARTY_NOTICES.txt new file mode 100644 index 0000000..1dcd9a4 --- /dev/null +++ b/third_party/mujoco/THIRD_PARTY_NOTICES.txt @@ -0,0 +1,4675 @@ +## Third-party licenses + +Pre-built [wheels](https://packaging.python.org/en/latest/specifications/ +binary-distribution-format/#binary-distribution-format) contain binaries that +incorporate third-party open source software, which are redistributed under the +following licenses. + +### Abseil C++ Common Libraries + +``` +Copyright 2016 Google Inc. +Copyright 2017 The Abseil Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +``` + +### cereal + +``` +Copyright (c) 2013-2022, Randolph Voorhies, Shane Grant +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 copyright holder 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 HOLDER 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. +``` + +### Collisions + +``` +Copyright (c) 2015 Svetoslav Kolev + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +``` + +### Eigen + +We build with the `EIGEN_MPL2_ONLY` preprocessor macro set. + +``` +Eigen is primarily MPL2 licensed. See COPYING.MPL2 and these links: + http://www.mozilla.org/MPL/2.0/ + http://www.mozilla.org/MPL/2.0/FAQ.html + +Some files contain third-party code under BSD or LGPL licenses, whence the other +COPYING.* files here. + +All the LGPL code is either LGPL 2.1-only, or LGPL 2.1-or-later. +For this reason, the COPYING.LGPL file contains the LGPL 2.1 text. + +If you want to guarantee that the Eigen code that you are #including is licensed +under the MPL2 and possibly more permissive licenses (like BSD), #define this +preprocessor symbol: + EIGEN_MPL2_ONLY +For example, with most compilers, you could add this to your project CXXFLAGS: + -DEIGEN_MPL2_ONLY +This will cause a compilation error to be generated if you #include any code that is +LGPL licensed. + + +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at https://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. +``` + +### {fmt} + +``` +Copyright (c) 2012 - present, Victor Zverovich and {fmt} contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--- Optional exception to the license --- + +As an exception, if, as a result of your compiling your source code, portions +of this Software are embedded into a machine-executable object form of such +source code, you may redistribute such embedded portions in such object form +without including the above copyright and permission notices. +``` + +### GLAD + +``` +The glad generated code itself is CC0. The source files for the generated code +are under various licenses from Khronos. + +-------------------------------------------------------------------------------- + +Copyright 2013-2020 The Khronos Group Inc. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and/or associated documentation files (the +"Materials"), to deal in the Materials without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Materials, and to +permit persons to whom the Materials are furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Materials. + +THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. +``` + +### GLFW + +``` +Copyright (c) 2002-2006 Marcus Geelnard + +Copyright (c) 2006-2019 Camilla Löwy + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would + be appreciated but is not required. + +2. Altered source versions must be plainly marked as such, and must not + be misrepresented as being the original software. + +3. This notice may not be removed or altered from any source + distribution. +``` + +### libccd + +``` +Copyright (c)2010-2012 Daniel Fiser , +Intelligent and Mobile Robotics Group, Department of Cybernetics, +Faculty of Electrical Engineering, Czech Technical University in Prague. +All rights reserved. + + +This work was supported by SYMBRION and REPLICATOR projects. +The SYMBRION project is funded by European Commission within the work +"Future and Emergent Technologies Proactive" under grant agreement no. +216342. +The REPLICATOR project is funded within the work programme "Cognitive +Systems, Interaction, Robotics" under grant agreement no. 216240. +http://www.symbrion.eu/ +http://www.replicators.eu/ + + +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 University 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 HOLDER 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. +``` + +### LLVM runtime libraries (`compiler_rt`, `libc++`, `libc++abi`, `libunwind`) + +``` +The LLVM Project is under the Apache License v2.0 with LLVM Exceptions. +You may obtain a copy of the Apache 2.0 License at + + https://www.apache.org/licenses/LICENSE-2.0 + +---- LLVM Exceptions to the Apache 2.0 License ---- + +As an exception, if, as a result of your compiling your source code, portions +of this Software are embedded into an Object form of such source code, you +may redistribute such embedded portions in such Object form without complying +with the conditions of Sections 4(a), 4(b) and 4(d) of the License. + +In addition, if you combine or link compiled forms of this Software with +software that is licensed under the GPLv2 ("Combined Software") and if a +court of competent jurisdiction determines that the patent provision (Section +3), the indemnity provision (Section 9) or other Section of the License +conflicts with the conditions of the GPLv2, you may retroactively and +prospectively choose to deem waived or otherwise exclude such Section(s) of +the License, but only in their entirety and only with respect to the Combined +Software. +``` + +### LodePNG + +``` +Copyright (c) 2005-2018 Lode Vandevenne + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +``` + +### MarchingCubeCpp + +``` +The MIT License (MIT) + +Copyright (c) 2020 Axel Paris + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +``` + +### OpenGL Mathematics + +``` +The MIT License + +Copyright (c) 2005 - G-Truc Creation + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +``` + +### pybind11 + +``` +Copyright (c) 2016 Wenzel Jakob , All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. 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. + +3. Neither the name of the copyright holder 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 HOLDER 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. + +Please also refer to the file .github/CONTRIBUTING.md, which clarifies licensing of +external contributions to this project including patches, pull requests, etc. +``` + +### Qhull + +``` + Qhull, Copyright (c) 1993-2020 + + C.B. Barber + Arlington, MA + + and + + The National Science and Technology Research Center for + Computation and Visualization of Geometric Structures + (The Geometry Center) + University of Minnesota + + email: qhull@qhull.org + +This software includes Qhull from C.B. Barber and The Geometry Center. +Files derived from Qhull 1.0 are copyrighted by the Geometry Center. The +remaining files are copyrighted by C.B. Barber. Qhull is free software +and may be obtained via http from www.qhull.org. It may be freely copied, +modified, and redistributed under the following conditions: + +1. All copyright notices must remain intact in all files. + +2. A copy of this text file must be distributed along with any copies + of Qhull that you redistribute; this includes copies that you have + modified, or copies of programs or other software products that + include Qhull. + +3. If you modify Qhull, you must include a notice giving the + name of the person performing the modification, the date of + modification, and the reason for such modification. + +4. When distributing modified versions of Qhull, or other software + products that include Qhull, you must provide notice that the original + source code may be obtained as noted above. + +5. There is no warranty or other guarantee of fitness for Qhull, it is + provided solely "as is". Bug reports or fixes may be sent to + qhull_bug@qhull.org; the authors may or may not act on them as + they desire. +``` + +### TinyOBJLoader + +``` +The MIT License (MIT) + +Copyright (c) 2012-2019 Syoyo Fujita and many contributors. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +``` + +### TinyXML2 + +``` +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any +damages arising from the use of this software. + +Permission is granted to anyone to use this software for any +purpose, including commercial applications, and to alter it and +redistribute it freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must +not claim that you wrote the original software. If you use this +software in a product, an acknowledgment in the product documentation +would be appreciated but is not required. + +2. Altered source versions must be plainly marked as such, and +must not be misrepresented as being the original software. + +3. This notice may not be removed or altered from any source +distribution. +``` + +### miniz + +``` +Copyright 2013-2014 RAD Game Tools and Valve Software +Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC + +All Rights Reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +``` + +### Dear ImGui + +``` +The MIT License (MIT) + +Copyright (c) 2014-2025 Omar Cornut + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +``` + +### ImPlot + +``` +MIT License + +Copyright (c) 2020 Evan Pezent + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +``` + +### Open Sans Font + +``` +Copyright 2020 The Open Sans Project Authors (https://github.com/googlefonts/opensans) + +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font +creation efforts of academic and linguistic communities, and to +provide a free and open framework in which fonts may be shared and +improved in partnership with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply to +any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software +components as distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, +deleting, or substituting -- in part or in whole -- any of the +components of the Original Version, by changing formats or by porting +the Font Software to a new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, +modify, redistribute, and sell modified and unmodified copies of the +Font Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, in +Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the +corresponding Copyright Holder. This restriction only applies to the +primary font name as presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created using +the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE FONT SOFTWARE. +``` + +### Font Awesome Font + +``` +Copyright (c) 2016 Dave Gandy (http://fontawesome.io) + +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font +creation efforts of academic and linguistic communities, and to +provide a free and open framework in which fonts may be shared and +improved in partnership with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply to +any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software +components as distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, +deleting, or substituting -- in part or in whole -- any of the +components of the Original Version, by changing formats or by porting +the Font Software to a new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, +modify, redistribute, and sell modified and unmodified copies of the +Font Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, in +Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the +corresponding Copyright Holder. This restriction only applies to the +primary font name as presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created using +the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE FONT SOFTWARE. +``` + +### Filament + +``` +Copyright 2023 The Android Open Source Project + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +``` + +### SDL2 + +``` +Copyright (C) 1997-2025 Sam Lantinga + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. +2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. +3. This notice may not be removed or altered from any source distribution. +``` + +### Zstandard + +``` +BSD License + +For Zstandard software + +Copyright (c) Meta Platforms, Inc. and affiliates. 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 Facebook, nor Meta, 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 HOLDER 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. +``` + +### SMOL-V + +``` +MIT License + +Copyright (c) 2016-2018 Aras Pranckevicius + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +``` + + +### libwebp + +``` +Copyright 2010 Google LLC + +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 Google 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 +HOLDER 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. + +Additional IP Rights Grant (Patents) +------------------------------------ + +"These implementations" means the copyrightable works that implement the WebM +codecs distributed by Google as part of the WebM Project. + +Google hereby grants to you a perpetual, worldwide, non-exclusive, no-charge, +royalty-free, irrevocable (except as stated in this section) patent license to +make, have made, use, offer to sell, sell, import, transfer, and otherwise +run, modify and propagate the contents of these implementations of WebM, where +such license applies only to those patent claims, both currently owned by +Google and acquired in the future, licensable by Google that are necessarily +infringed by these implementations of WebM. This grant does not include claims +that would be infringed only as a consequence of further modification of these +implementations. If you or your agent or exclusive licensee institute or order +or agree to the institution of patent litigation or any other patent +enforcement activity against any entity (including a cross-claim or +counterclaim in a lawsuit) alleging that any of these implementations of WebM +or any code incorporated within any of these implementations of WebM +constitute direct or contributory patent infringement, or inducement of +patent infringement, then any patent rights granted to you under this License +for these implementations of WebM shall terminate as of the date such +litigation is filed. +``` + + +### Basis Universal + +``` +All files except those noted below: +apg_bmp.h +apg_bmp.c +zstd/* + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +------------------ + +File: webgl/gltf/GLTFLoader.js + +Copyright 2019 the three.js authors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +------------------ + +Files: +apg_bmp.h +apg_bmp.c + +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or +distribute this software, either in source code form or as a compiled +binary, for any purpose, commercial or non-commercial, and by any +means. + +In jurisdictions that recognize copyright laws, the author or authors +of this software dedicate any and all copyright interest in the +software to the public domain. We make this dedication for the benefit +of the public at large and to the detriment of our heirs and +successors. We intend this dedication to be an overt act of +relinquishment in perpetuity of all present and future rights to this +software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR +OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + +For more information, please refer to + +------------------ + +Copyright (c) + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. + +------------------ +zstd/* + +BSD License + +For Zstandard software + +Copyright (c) 2016-present, Facebook, Inc. 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 Facebook 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 HOLDER 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. +``` + + +### Glslang + +``` +Here, glslang proper means core GLSL parsing, HLSL parsing, and SPIR-V code +generation. Glslang proper requires use of a number of licenses, one that covers +preprocessing and others that covers non-preprocessing. + +Bison was removed long ago. You can build glslang from the source grammar, +using tools of your choice, without using bison or any bison files. + +Other parts, outside of glslang proper, include: + +- gl_types.h, only needed for OpenGL-like reflection, and can be left out of + a parse and codegen project. See it for its license. + +- update_glslang_sources.py, which is not part of the project proper and does + not need to be used. + +- Google tests and SPIR-V tools, and anything in the external subdirectory + are external and optional; see them for their respective licenses. + +-------------------------------------------------------------------------------- + +The core of glslang-proper, minus the preprocessor is licenced as follows: + +-------------------------------------------------------------------------------- +3-Clause BSD License +-------------------------------------------------------------------------------- + +// +// Copyright (C) 2015-2018 Google, Inc. +// Copyright (C) +// +// 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 3Dlabs Inc. Ltd. 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 HOLDERS 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. +// + + +-------------------------------------------------------------------------------- +2-Clause BSD License +-------------------------------------------------------------------------------- + +Copyright 2020 The Khronos Group Inc + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. 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. + +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 HOLDER 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. + + +-------------------------------------------------------------------------------- +The MIT License +-------------------------------------------------------------------------------- + +Copyright 2020 The Khronos Group Inc + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +-------------------------------------------------------------------------------- +APACHE LICENSE, VERSION 2.0 +-------------------------------------------------------------------------------- + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +-------------------------------------------------------------------------------- +GPL 3 with special bison exception +-------------------------------------------------------------------------------- + + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + +Bison Exception + +As a special exception, you may create a larger work that contains part or all +of the Bison parser skeleton and distribute that work under terms of your +choice, so long as that work isn't itself a parser generator using the skeleton +or a modified version thereof as a parser skeleton. Alternatively, if you +modify or redistribute the parser skeleton itself, you may (at your option) +remove this special exception, which will cause the skeleton and the resulting +Bison output files to be licensed under the GNU General Public License without +this special exception. + +This special exception was added by the Free Software Foundation in version +2.2 of Bison. + + END OF TERMS AND CONDITIONS + +-------------------------------------------------------------------------------- +================================================================================ +-------------------------------------------------------------------------------- + +The preprocessor has the core licenses stated above, plus additional licences: + +/****************************************************************************\ +Copyright (c) 2002, NVIDIA Corporation. + +NVIDIA Corporation("NVIDIA") supplies this software to you in +consideration of your agreement to the following terms, and your use, +installation, modification or redistribution of this NVIDIA software +constitutes acceptance of these terms. If you do not agree with these +terms, please do not use, install, modify or redistribute this NVIDIA +software. + +In consideration of your agreement to abide by the following terms, and +subject to these terms, NVIDIA grants you a personal, non-exclusive +license, under NVIDIA's copyrights in this original NVIDIA software (the +"NVIDIA Software"), to use, reproduce, modify and redistribute the +NVIDIA Software, with or without modifications, in source and/or binary +forms; provided that if you redistribute the NVIDIA Software, you must +retain the copyright notice of NVIDIA, this notice and the following +text and disclaimers in all such redistributions of the NVIDIA Software. +Neither the name, trademarks, service marks nor logos of NVIDIA +Corporation may be used to endorse or promote products derived from the +NVIDIA Software without specific prior written permission from NVIDIA. +Except as expressly stated in this notice, no other rights or licenses +express or implied, are granted by NVIDIA herein, including but not +limited to any patent rights that may be infringed by your derivative +works or by other works in which the NVIDIA Software may be +incorporated. No hardware is licensed hereunder. + +THE NVIDIA SOFTWARE IS BEING PROVIDED ON AN "AS IS" BASIS, WITHOUT +WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, +INCLUDING WITHOUT LIMITATION, WARRANTIES OR CONDITIONS OF TITLE, +NON-INFRINGEMENT, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR +ITS USE AND OPERATION EITHER ALONE OR IN COMBINATION WITH OTHER +PRODUCTS. + +IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY SPECIAL, INDIRECT, +INCIDENTAL, EXEMPLARY, CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, LOST PROFITS; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF +USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) OR ARISING IN ANY WAY +OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE +NVIDIA SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, +TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF +NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +\****************************************************************************/ + +/* +** Copyright (c) 2014-2016 The Khronos Group Inc. +** +** Permission is hereby granted, free of charge, to any person obtaining a copy +** of this software and/or associated documentation files (the "Materials"), +** to deal in the Materials without restriction, including without limitation +** the rights to use, copy, modify, merge, publish, distribute, sublicense, +** and/or sell copies of the Materials, and to permit persons to whom the +** Materials are furnished to do so, subject to the following conditions: +** +** The above copyright notice and this permission notice shall be included in +** all copies or substantial portions of the Materials. +** +** MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS KHRONOS +** STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS SPECIFICATIONS AND +** HEADER INFORMATION ARE LOCATED AT https://www.khronos.org/registry/ +** +** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +** OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +** THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +** FROM,OUT OF OR IN CONNECTION WITH THE MATERIALS OR THE USE OR OTHER DEALINGS +** IN THE MATERIALS. +*/ +``` + + +### libpng + +``` +COPYRIGHT NOTICE, DISCLAIMER, and LICENSE +========================================= + +PNG Reference Library License version 2 +--------------------------------------- + + * Copyright (c) 1995-2026 The PNG Reference Library Authors. + * Copyright (c) 2018-2026 Cosmin Truta. + * Copyright (c) 2000-2002, 2004, 2006-2018 Glenn Randers-Pehrson. + * Copyright (c) 1996-1997 Andreas Dilger. + * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc. + +The software is supplied "as is", without warranty of any kind, +express or implied, including, without limitation, the warranties +of merchantability, fitness for a particular purpose, title, and +non-infringement. In no event shall the Copyright owners, or +anyone distributing the software, be liable for any damages or +other liability, whether in contract, tort or otherwise, arising +from, out of, or in connection with the software, or the use or +other dealings in the software, even if advised of the possibility +of such damage. + +Permission is hereby granted to use, copy, modify, and distribute +this software, or portions hereof, for any purpose, without fee, +subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you + must not claim that you wrote the original software. If you + use this software in a product, an acknowledgment in the product + documentation would be appreciated, but is not required. + + 2. Altered source versions must be plainly marked as such, and must + not be misrepresented as being the original software. + + 3. This Copyright notice may not be removed or altered from any + source or altered source distribution. + + +PNG Reference Library License version 1 (for libpng 0.5 through 1.6.35) +----------------------------------------------------------------------- + +libpng versions 1.0.7, July 1, 2000, through 1.6.35, July 15, 2018 are +Copyright (c) 2000-2002, 2004, 2006-2018 Glenn Randers-Pehrson, are +derived from libpng-1.0.6, and are distributed according to the same +disclaimer and license as libpng-1.0.6 with the following individuals +added to the list of Contributing Authors: + + Simon-Pierre Cadieux + Eric S. Raymond + Mans Rullgard + Cosmin Truta + Gilles Vollant + James Yu + Mandar Sahastrabuddhe + Google Inc. + Vadim Barkov + +and with the following additions to the disclaimer: + + There is no warranty against interference with your enjoyment of + the library or against infringement. There is no warranty that our + efforts or the library will fulfill any of your particular purposes + or needs. This library is provided with all faults, and the entire + risk of satisfactory quality, performance, accuracy, and effort is + with the user. + +Some files in the "contrib" directory and some configure-generated +files that are distributed with libpng have other copyright owners, and +are released under other open source licenses. + +libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are +Copyright (c) 1998-2000 Glenn Randers-Pehrson, are derived from +libpng-0.96, and are distributed according to the same disclaimer and +license as libpng-0.96, with the following individuals added to the +list of Contributing Authors: + + Tom Lane + Glenn Randers-Pehrson + Willem van Schaik + +libpng versions 0.89, June 1996, through 0.96, May 1997, are +Copyright (c) 1996-1997 Andreas Dilger, are derived from libpng-0.88, +and are distributed according to the same disclaimer and license as +libpng-0.88, with the following individuals added to the list of +Contributing Authors: + + John Bowler + Kevin Bracey + Sam Bushell + Magnus Holmgren + Greg Roelofs + Tom Tanner + +Some files in the "scripts" directory have other copyright owners, +but are released under this license. + +libpng versions 0.5, May 1995, through 0.88, January 1996, are +Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc. + +For the purposes of this copyright and license, "Contributing Authors" +is defined as the following set of individuals: + + Andreas Dilger + Dave Martindale + Guy Eric Schalnat + Paul Schmidt + Tim Wegner + +The PNG Reference Library is supplied "AS IS". The Contributing +Authors and Group 42, Inc. disclaim all warranties, expressed or +implied, including, without limitation, the warranties of +merchantability and of fitness for any purpose. The Contributing +Authors and Group 42, Inc. assume no liability for direct, indirect, +incidental, special, exemplary, or consequential damages, which may +result from the use of the PNG Reference Library, even if advised of +the possibility of such damage. + +Permission is hereby granted to use, copy, modify, and distribute this +source code, or portions hereof, for any purpose, without fee, subject +to the following restrictions: + + 1. The origin of this source code must not be misrepresented. + + 2. Altered versions must be plainly marked as such and must not + be misrepresented as being the original source. + + 3. This Copyright notice may not be removed or altered from any + source or altered source distribution. + +The Contributing Authors and Group 42, Inc. specifically permit, +without fee, and encourage the use of this source code as a component +to supporting the PNG file format in commercial products. If you use +this source code in a product, acknowledgment is not required but would +be appreciated. +``` + + +### zlib + +``` +(extracted from README, except for match.S) + +Copyright notice: + + (C) 1995-2013 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + +If you use the zlib library in a product, we would appreciate *not* receiving +lengthy legal documents to sign. The sources are provided for free but without +warranty of any kind. The library has been entirely written by Jean-loup +Gailly and Mark Adler; it does not include third-party code. + +If you redistribute modified sources, we would appreciate that you include in +the file ChangeLog history information documenting your changes. Please read +the FAQ for more information on the distribution of modified source versions. + +(extracted from match.S, for match.S only) + +Copyright (C) 1998, 2007 Brian Raiter + +This software is provided 'as-is', without any express or implied +warranty. In no event will the author be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. +2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. +3. This notice may not be removed or altered from any source distribution. +``` + + +### robin-map + +``` +MIT License + +Copyright (c) 2017 Thibaut Goetghebuer-Planchon + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +``` + + +### SPIRV-Cross + +``` +========== +LICENSE +========== + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +========== +LICENSES/Apache-2.0.txt +========== + +Apache License + +Version 2.0, January 2004 + +http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, +AND DISTRIBUTION + + 1. Definitions. + + + +"License" shall mean the terms and conditions for use, reproduction, and distribution +as defined by Sections 1 through 9 of this document. + + + +"Licensor" shall mean the copyright owner or entity authorized by the copyright +owner that is granting the License. + + + +"Legal Entity" shall mean the union of the acting entity and all other entities +that control, are controlled by, or are under common control with that entity. +For the purposes of this definition, "control" means (i) the power, direct +or indirect, to cause the direction or management of such entity, whether +by contract or otherwise, or (ii) ownership of fifty percent (50%) or more +of the outstanding shares, or (iii) beneficial ownership of such entity. + + + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions +granted by this License. + + + +"Source" form shall mean the preferred form for making modifications, including +but not limited to software source code, documentation source, and configuration +files. + + + +"Object" form shall mean any form resulting from mechanical transformation +or translation of a Source form, including but not limited to compiled object +code, generated documentation, and conversions to other media types. + + + +"Work" shall mean the work of authorship, whether in Source or Object form, +made available under the License, as indicated by a copyright notice that +is included in or attached to the work (an example is provided in the Appendix +below). + + + +"Derivative Works" shall mean any work, whether in Source or Object form, +that is based on (or derived from) the Work and for which the editorial revisions, +annotations, elaborations, or other modifications represent, as a whole, an +original work of authorship. For the purposes of this License, Derivative +Works shall not include works that remain separable from, or merely link (or +bind by name) to the interfaces of, the Work and Derivative Works thereof. + + + +"Contribution" shall mean any work of authorship, including the original version +of the Work and any modifications or additions to that Work or Derivative +Works thereof, that is intentionally submitted to Licensor for inclusion in +the Work by the copyright owner or by an individual or Legal Entity authorized +to submit on behalf of the copyright owner. For the purposes of this definition, +"submitted" means any form of electronic, verbal, or written communication +sent to the Licensor or its representatives, including but not limited to +communication on electronic mailing lists, source code control systems, and +issue tracking systems that are managed by, or on behalf of, the Licensor +for the purpose of discussing and improving the Work, but excluding communication +that is conspicuously marked or otherwise designated in writing by the copyright +owner as "Not a Contribution." + + + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf +of whom a Contribution has been received by Licensor and subsequently incorporated +within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this +License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, +no-charge, royalty-free, irrevocable copyright license to reproduce, prepare +Derivative Works of, publicly display, publicly perform, sublicense, and distribute +the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, +each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, +no-charge, royalty-free, irrevocable (except as stated in this section) patent +license to make, have made, use, offer to sell, sell, import, and otherwise +transfer the Work, where such license applies only to those patent claims +licensable by such Contributor that are necessarily infringed by their Contribution(s) +alone or by combination of their Contribution(s) with the Work to which such +Contribution(s) was submitted. If You institute patent litigation against +any entity (including a cross-claim or counterclaim in a lawsuit) alleging +that the Work or a Contribution incorporated within the Work constitutes direct +or contributory patent infringement, then any patent licenses granted to You +under this License for that Work shall terminate as of the date such litigation +is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or +Derivative Works thereof in any medium, with or without modifications, and +in Source or Object form, provided that You meet the following conditions: + +(a) You must give any other recipients of the Work or Derivative Works a copy +of this License; and + +(b) You must cause any modified files to carry prominent notices stating that +You changed the files; and + +(c) You must retain, in the Source form of any Derivative Works that You distribute, +all copyright, patent, trademark, and attribution notices from the Source +form of the Work, excluding those notices that do not pertain to any part +of the Derivative Works; and + +(d) If the Work includes a "NOTICE" text file as part of its distribution, +then any Derivative Works that You distribute must include a readable copy +of the attribution notices contained within such NOTICE file, excluding those +notices that do not pertain to any part of the Derivative Works, in at least +one of the following places: within a NOTICE text file distributed as part +of the Derivative Works; within the Source form or documentation, if provided +along with the Derivative Works; or, within a display generated by the Derivative +Works, if and wherever such third-party notices normally appear. The contents +of the NOTICE file are for informational purposes only and do not modify the +License. You may add Your own attribution notices within Derivative Works +that You distribute, alongside or as an addendum to the NOTICE text from the +Work, provided that such additional attribution notices cannot be construed +as modifying the License. + +You may add Your own copyright statement to Your modifications and may provide +additional or different license terms and conditions for use, reproduction, +or distribution of Your modifications, or for any such Derivative Works as +a whole, provided Your use, reproduction, and distribution of the Work otherwise +complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any +Contribution intentionally submitted for inclusion in the Work by You to the +Licensor shall be under the terms and conditions of this License, without +any additional terms or conditions. Notwithstanding the above, nothing herein +shall supersede or modify the terms of any separate license agreement you +may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, +trademarks, service marks, or product names of the Licensor, except as required +for reasonable and customary use in describing the origin of the Work and +reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to +in writing, Licensor provides the Work (and each Contributor provides its +Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, either express or implied, including, without limitation, any warranties +or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR +A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness +of using or redistributing the Work and assume any risks associated with Your +exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether +in tort (including negligence), contract, or otherwise, unless required by +applicable law (such as deliberate and grossly negligent acts) or agreed to +in writing, shall any Contributor be liable to You for damages, including +any direct, indirect, special, incidental, or consequential damages of any +character arising as a result of this License or out of the use or inability +to use the Work (including but not limited to damages for loss of goodwill, +work stoppage, computer failure or malfunction, or any and all other commercial +damages or losses), even if such Contributor has been advised of the possibility +of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work +or Derivative Works thereof, You may choose to offer, and charge a fee for, +acceptance of support, warranty, indemnity, or other liability obligations +and/or rights consistent with this License. However, in accepting such obligations, +You may act only on Your own behalf and on Your sole responsibility, not on +behalf of any other Contributor, and only if You agree to indemnify, defend, +and hold each Contributor harmless for any liability incurred by, or claims +asserted against, such Contributor by reason of your accepting any such warranty +or additional liability. END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +To apply the Apache License to your work, attach the following boilerplate +notice, with the fields enclosed by brackets "[]" replaced with your own identifying +information. (Don't include the brackets!) The text should be enclosed in +the appropriate comment syntax for the file format. We also recommend that +a file or class name and description of purpose be included on the same "printed +page" as the copyright notice for easier identification within third-party +archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); + +you may not use this file except in compliance with the License. + +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software + +distributed under the License is distributed on an "AS IS" BASIS, + +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +See the License for the specific language governing permissions and + +limitations under the License. + + +========== +LICENSES/CC-BY-4.0.txt +========== + +Creative Commons Attribution 4.0 International Creative Commons Corporation +("Creative Commons") is not a law firm and does not provide legal services +or legal advice. Distribution of Creative Commons public licenses does not +create a lawyer-client or other relationship. Creative Commons makes its licenses +and related information available on an "as-is" basis. Creative Commons gives +no warranties regarding its licenses, any material licensed under their terms +and conditions, or any related information. Creative Commons disclaims all +liability for damages resulting from their use to the fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and conditions +that creators and other rights holders may use to share original works of +authorship and other material subject to copyright and certain other rights +specified in the public license below. The following considerations are for +informational purposes only, are not exhaustive, and do not form part of our +licenses. + +Considerations for licensors: Our public licenses are intended for use by +those authorized to give the public permission to use material in ways otherwise +restricted by copyright and certain other rights. Our licenses are irrevocable. +Licensors should read and understand the terms and conditions of the license +they choose before applying it. Licensors should also secure all rights necessary +before applying our licenses so that the public can reuse the material as +expected. Licensors should clearly mark any material not subject to the license. +This includes other CC-licensed material, or material used under an exception +or limitation to copyright. More considerations for licensors : wiki.creativecommons.org/Considerations_for_licensors + +Considerations for the public: By using one of our public licenses, a licensor +grants the public permission to use the licensed material under specified +terms and conditions. If the licensor's permission is not necessary for any +reason–for example, because of any applicable exception or limitation to copyright–then +that use is not regulated by the license. Our licenses grant only permissions +under copyright and certain other rights that a licensor has authority to +grant. Use of the licensed material may still be restricted for other reasons, +including because others have copyright or other rights in the material. A +licensor may make special requests, such as asking that all changes be marked +or described. Although not required by our licenses, you are encouraged to +respect those requests where reasonable. More considerations for the public +: wiki.creativecommons.org/Considerations_for_licensees Creative Commons Attribution +4.0 International Public License + +By exercising the Licensed Rights (defined below), You accept and agree to +be bound by the terms and conditions of this Creative Commons Attribution +4.0 International Public License ("Public License"). To the extent this Public +License may be interpreted as a contract, You are granted the Licensed Rights +in consideration of Your acceptance of these terms and conditions, and the +Licensor grants You such rights in consideration of benefits the Licensor +receives from making the Licensed Material available under these terms and +conditions. + +Section 1 – Definitions. + +a. Adapted Material means material subject to Copyright and Similar Rights +that is derived from or based upon the Licensed Material and in which the +Licensed Material is translated, altered, arranged, transformed, or otherwise +modified in a manner requiring permission under the Copyright and Similar +Rights held by the Licensor. For purposes of this Public License, where the +Licensed Material is a musical work, performance, or sound recording, Adapted +Material is always produced where the Licensed Material is synched in timed +relation with a moving image. + +b. Adapter's License means the license You apply to Your Copyright and Similar +Rights in Your contributions to Adapted Material in accordance with the terms +and conditions of this Public License. + +c. Copyright and Similar Rights means copyright and/or similar rights closely +related to copyright including, without limitation, performance, broadcast, +sound recording, and Sui Generis Database Rights, without regard to how the +rights are labeled or categorized. For purposes of this Public License, the +rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. + +d. Effective Technological Measures means those measures that, in the absence +of proper authority, may not be circumvented under laws fulfilling obligations +under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, +and/or similar international agreements. + +e. Exceptions and Limitations means fair use, fair dealing, and/or any other +exception or limitation to Copyright and Similar Rights that applies to Your +use of the Licensed Material. + +f. Licensed Material means the artistic or literary work, database, or other +material to which the Licensor applied this Public License. + +g. Licensed Rights means the rights granted to You subject to the terms and +conditions of this Public License, which are limited to all Copyright and +Similar Rights that apply to Your use of the Licensed Material and that the +Licensor has authority to license. + +h. Licensor means the individual(s) or entity(ies) granting rights under this +Public License. + +i. Share means to provide material to the public by any means or process that +requires permission under the Licensed Rights, such as reproduction, public +display, public performance, distribution, dissemination, communication, or +importation, and to make material available to the public including in ways +that members of the public may access the material from a place and at a time +individually chosen by them. + +j. Sui Generis Database Rights means rights other than copyright resulting +from Directive 96/9/EC of the European Parliament and of the Council of 11 +March 1996 on the legal protection of databases, as amended and/or succeeded, +as well as other essentially equivalent rights anywhere in the world. + +k. You means the individual or entity exercising the Licensed Rights under +this Public License. Your has a corresponding meaning. + +Section 2 – Scope. + + a. License grant. + +1. Subject to the terms and conditions of this Public License, the Licensor +hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, +irrevocable license to exercise the Licensed Rights in the Licensed Material +to: + + A. reproduce and Share the Licensed Material, in whole or in part; and + + B. produce, reproduce, and Share Adapted Material. + +2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions +and Limitations apply to Your use, this Public License does not apply, and +You do not need to comply with its terms and conditions. + + 3. Term. The term of this Public License is specified in Section 6(a). + +4. Media and formats; technical modifications allowed. The Licensor authorizes +You to exercise the Licensed Rights in all media and formats whether now known +or hereafter created, and to make technical modifications necessary to do +so. The Licensor waives and/or agrees not to assert any right or authority +to forbid You from making technical modifications necessary to exercise the +Licensed Rights, including technical modifications necessary to circumvent +Effective Technological Measures. For purposes of this Public License, simply +making modifications authorized by this Section 2(a)(4) never produces Adapted +Material. + + 5. Downstream recipients. + +A. Offer from the Licensor – Licensed Material. Every recipient of the Licensed +Material automatically receives an offer from the Licensor to exercise the +Licensed Rights under the terms and conditions of this Public License. + +B. No downstream restrictions. You may not offer or impose any additional +or different terms or conditions on, or apply any Effective Technological +Measures to, the Licensed Material if doing so restricts exercise of the Licensed +Rights by any recipient of the Licensed Material. + +6. No endorsement. Nothing in this Public License constitutes or may be construed +as permission to assert or imply that You are, or that Your use of the Licensed +Material is, connected with, or sponsored, endorsed, or granted official status +by, the Licensor or others designated to receive attribution as provided in +Section 3(a)(1)(A)(i). + + b. Other rights. + +1. Moral rights, such as the right of integrity, are not licensed under this +Public License, nor are publicity, privacy, and/or other similar personality +rights; however, to the extent possible, the Licensor waives and/or agrees +not to assert any such rights held by the Licensor to the limited extent necessary +to allow You to exercise the Licensed Rights, but not otherwise. + +2. Patent and trademark rights are not licensed under this Public License. + +3. To the extent possible, the Licensor waives any right to collect royalties +from You for the exercise of the Licensed Rights, whether directly or through +a collecting society under any voluntary or waivable statutory or compulsory +licensing scheme. In all other cases the Licensor expressly reserves any right +to collect such royalties. + +Section 3 – License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the following +conditions. + + a. Attribution. + +1. If You Share the Licensed Material (including in modified form), You must: + +A. retain the following if it is supplied by the Licensor with the Licensed +Material: + +i. identification of the creator(s) of the Licensed Material and any others +designated to receive attribution, in any reasonable manner requested by the +Licensor (including by pseudonym if designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of warranties; + +v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; + +B. indicate if You modified the Licensed Material and retain an indication +of any previous modifications; and + +C. indicate the Licensed Material is licensed under this Public License, and +include the text of, or the URI or hyperlink to, this Public License. + +2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner +based on the medium, means, and context in which You Share the Licensed Material. +For example, it may be reasonable to satisfy the conditions by providing a +URI or hyperlink to a resource that includes the required information. + +3. If requested by the Licensor, You must remove any of the information required +by Section 3(a)(1)(A) to the extent reasonably practicable. + +4. If You Share Adapted Material You produce, the Adapter's License You apply +must not prevent recipients of the Adapted Material from complying with this +Public License. + +Section 4 – Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that apply to +Your use of the Licensed Material: + +a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, +reuse, reproduce, and Share all or a substantial portion of the contents of +the database; + +b. if You include all or a substantial portion of the database contents in +a database in which You have Sui Generis Database Rights, then the database +in which You have Sui Generis Database Rights (but not its individual contents) +is Adapted Material; and + +c. You must comply with the conditions in Section 3(a) if You Share all or +a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not replace +Your obligations under this Public License where the Licensed Rights include +other Copyright and Similar Rights. + +Section 5 – Disclaimer of Warranties and Limitation of Liability. + +a. Unless otherwise separately undertaken by the Licensor, to the extent possible, +the Licensor offers the Licensed Material as-is and as-available, and makes +no representations or warranties of any kind concerning the Licensed Material, +whether express, implied, statutory, or other. This includes, without limitation, +warranties of title, merchantability, fitness for a particular purpose, non-infringement, +absence of latent or other defects, accuracy, or the presence or absence of +errors, whether or not known or discoverable. Where disclaimers of warranties +are not allowed in full or in part, this disclaimer may not apply to You. + +b. To the extent possible, in no event will the Licensor be liable to You +on any legal theory (including, without limitation, negligence) or otherwise +for any direct, special, indirect, incidental, consequential, punitive, exemplary, +or other losses, costs, expenses, or damages arising out of this Public License +or use of the Licensed Material, even if the Licensor has been advised of +the possibility of such losses, costs, expenses, or damages. Where a limitation +of liability is not allowed in full or in part, this limitation may not apply +to You. + +c. The disclaimer of warranties and limitation of liability provided above +shall be interpreted in a manner that, to the extent possible, most closely +approximates an absolute disclaimer and waiver of all liability. + +Section 6 – Term and Termination. + +a. This Public License applies for the term of the Copyright and Similar Rights +licensed here. However, if You fail to comply with this Public License, then +Your rights under this Public License terminate automatically. + +b. Where Your right to use the Licensed Material has terminated under Section +6(a), it reinstates: + +1. automatically as of the date the violation is cured, provided it is cured +within 30 days of Your discovery of the violation; or + + 2. upon express reinstatement by the Licensor. + +c. For the avoidance of doubt, this Section 6(b) does not affect any right +the Licensor may have to seek remedies for Your violations of this Public +License. + +d. For the avoidance of doubt, the Licensor may also offer the Licensed Material +under separate terms or conditions or stop distributing the Licensed Material +at any time; however, doing so will not terminate this Public License. + + e. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. + +Section 7 – Other Terms and Conditions. + +a. The Licensor shall not be bound by any additional or different terms or +conditions communicated by You unless expressly agreed. + +b. Any arrangements, understandings, or agreements regarding the Licensed +Material not stated herein are separate from and independent of the terms +and conditions of this Public License. + +Section 8 – Interpretation. + +a. For the avoidance of doubt, this Public License does not, and shall not +be interpreted to, reduce, limit, restrict, or impose conditions on any use +of the Licensed Material that could lawfully be made without permission under +this Public License. + +b. To the extent possible, if any provision of this Public License is deemed +unenforceable, it shall be automatically reformed to the minimum extent necessary +to make it enforceable. If the provision cannot be reformed, it shall be severed +from this Public License without affecting the enforceability of the remaining +terms and conditions. + +c. No term or condition of this Public License will be waived and no failure +to comply consented to unless expressly agreed to by the Licensor. + +d. Nothing in this Public License constitutes or may be interpreted as a limitation +upon, or waiver of, any privileges and immunities that apply to the Licensor +or You, including from the legal processes of any jurisdiction or authority. + +Creative Commons is not a party to its public licenses. Notwithstanding, Creative +Commons may elect to apply one of its public licenses to material it publishes +and in those instances will be considered the "Licensor." The text of the +Creative Commons public licenses is dedicated to the public domain under the +CC0 Public Domain Dedication. Except for the limited purpose of indicating +that material is shared under a Creative Commons public license or as otherwise +permitted by the Creative Commons policies published at creativecommons.org/policies, +Creative Commons does not authorize the use of the trademark "Creative Commons" +or any other trademark or logo of Creative Commons without its prior written +consent including, without limitation, in connection with any unauthorized +modifications to any of its public licenses or any other arrangements, understandings, +or agreements concerning use of licensed material. For the avoidance of doubt, +this paragraph does not form part of the public licenses. + +Creative Commons may be contacted at creativecommons.org. + + +========== +LICENSES/LicenseRef-KhronosFreeUse.txt +========== + +Copyright (c) 2014-2020 The Khronos Group Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and/or associated documentation files (the "Materials"), +to deal in the Materials without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Materials, and to permit persons to whom the +Materials are furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Materials. + +MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS KHRONOS +STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS SPECIFICATIONS AND +HEADER INFORMATION ARE LOCATED AT https://www.khronos.org/registry/ + +THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM,OUT OF OR IN CONNECTION WITH THE MATERIALS OR THE USE OR OTHER DEALINGS +IN THE MATERIALS. + + +========== +LICENSES/MIT.txt +========== + +MIT License Copyright (c) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice (including the next +paragraph) shall be included in all copies or substantial portions of the +Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS +OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF +OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +``` + + +### SPIRV-Headers + +``` +Files: All files except for those called out below. +Copyright (c) 2015-2024 The Khronos Group Inc. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and/or associated documentation files (the +"Materials"), to deal in the Materials without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Materials, and to +permit persons to whom the Materials are furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Materials. + +MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS +KHRONOS STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS +SPECIFICATIONS AND HEADER INFORMATION ARE LOCATED AT + https://www.khronos.org/registry/ + +THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. + +--- + +Files: include/spirv/spir-v.xml +Copyright (c) 2015-2024 The Khronos Group Inc. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and/or associated documentation files (the +"Materials"), to deal in the Materials without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Materials, and to +permit persons to whom the Materials are furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Materials. + +THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. + +--- + +Files: tools/buildHeaders/jsoncpp/* +The JsonCpp library's source code, including accompanying documentation, +tests and demonstration applications, are licensed under the following +conditions... + +The author (Baptiste Lepilleur) explicitly disclaims copyright in all +jurisdictions which recognize such a disclaimer. In such jurisdictions, +this software is released into the Public Domain. + +In jurisdictions which do not recognize Public Domain property (e.g. Germany as of +2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur, and is +released under the terms of the MIT License (see below). + +In jurisdictions which recognize Public Domain property, the user of this +software may choose to accept it either as 1) Public Domain, 2) under the +conditions of the MIT License (see below), or 3) under the terms of dual +Public Domain/MIT License conditions described here, as they choose. + +The MIT License is about as close to Public Domain as a license can get, and is +described in clear, concise terms at: + + http://en.wikipedia.org/wiki/MIT_License + +The full text of the MIT License follows: + +======================================================================== +Copyright (c) 2007-2010 Baptiste Lepilleur + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, copy, +modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS +BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +======================================================================== + +--- + +Files: **.md, WORKSPACE, .git** + +Attribution 4.0 International + +======================================================================= + +Creative Commons Corporation ("Creative Commons") is not a law firm and +does not provide legal services or legal advice. Distribution of +Creative Commons public licenses does not create a lawyer-client or +other relationship. Creative Commons makes its licenses and related +information available on an "as-is" basis. Creative Commons gives no +warranties regarding its licenses, any material licensed under their +terms and conditions, or any related information. Creative Commons +disclaims all liability for damages resulting from their use to the +fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and +conditions that creators and other rights holders may use to share +original works of authorship and other material subject to copyright +and certain other rights specified in the public license below. The +following considerations are for informational purposes only, are not +exhaustive, and do not form part of our licenses. + + Considerations for licensors: Our public licenses are + intended for use by those authorized to give the public + permission to use material in ways otherwise restricted by + copyright and certain other rights. Our licenses are + irrevocable. Licensors should read and understand the terms + and conditions of the license they choose before applying it. + Licensors should also secure all rights necessary before + applying our licenses so that the public can reuse the + material as expected. Licensors should clearly mark any + material not subject to the license. This includes other CC- + licensed material, or material used under an exception or + limitation to copyright. More considerations for licensors: + wiki.creativecommons.org/Considerations_for_licensors + + Considerations for the public: By using one of our public + licenses, a licensor grants the public permission to use the + licensed material under specified terms and conditions. If + the licensor's permission is not necessary for any reason--for + example, because of any applicable exception or limitation to + copyright--then that use is not regulated by the license. Our + licenses grant only permissions under copyright and certain + other rights that a licensor has authority to grant. Use of + the licensed material may still be restricted for other + reasons, including because others have copyright or other + rights in the material. A licensor may make special requests, + such as asking that all changes be marked or described. + Although not required by our licenses, you are encouraged to + respect those requests where reasonable. More considerations + for the public: + wiki.creativecommons.org/Considerations_for_licensees + +======================================================================= + +Creative Commons Attribution 4.0 International Public License + +By exercising the Licensed Rights (defined below), You accept and agree +to be bound by the terms and conditions of this Creative Commons +Attribution 4.0 International Public License ("Public License"). To the +extent this Public License may be interpreted as a contract, You are +granted the Licensed Rights in consideration of Your acceptance of +these terms and conditions, and the Licensor grants You such rights in +consideration of benefits the Licensor receives from making the +Licensed Material available under these terms and conditions. + + +Section 1 -- Definitions. + + a. Adapted Material means material subject to Copyright and Similar + Rights that is derived from or based upon the Licensed Material + and in which the Licensed Material is translated, altered, + arranged, transformed, or otherwise modified in a manner requiring + permission under the Copyright and Similar Rights held by the + Licensor. For purposes of this Public License, where the Licensed + Material is a musical work, performance, or sound recording, + Adapted Material is always produced where the Licensed Material is + synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright + and Similar Rights in Your contributions to Adapted Material in + accordance with the terms and conditions of this Public License. + + c. Copyright and Similar Rights means copyright and/or similar rights + closely related to copyright including, without limitation, + performance, broadcast, sound recording, and Sui Generis Database + Rights, without regard to how the rights are labeled or + categorized. For purposes of this Public License, the rights + specified in Section 2(b)(1)-(2) are not Copyright and Similar + Rights. + + d. Effective Technological Measures means those measures that, in the + absence of proper authority, may not be circumvented under laws + fulfilling obligations under Article 11 of the WIPO Copyright + Treaty adopted on December 20, 1996, and/or similar international + agreements. + + e. Exceptions and Limitations means fair use, fair dealing, and/or + any other exception or limitation to Copyright and Similar Rights + that applies to Your use of the Licensed Material. + + f. Licensed Material means the artistic or literary work, database, + or other material to which the Licensor applied this Public + License. + + g. Licensed Rights means the rights granted to You subject to the + terms and conditions of this Public License, which are limited to + all Copyright and Similar Rights that apply to Your use of the + Licensed Material and that the Licensor has authority to license. + + h. Licensor means the individual(s) or entity(ies) granting rights + under this Public License. + + i. Share means to provide material to the public by any means or + process that requires permission under the Licensed Rights, such + as reproduction, public display, public performance, distribution, + dissemination, communication, or importation, and to make material + available to the public including in ways that members of the + public may access the material from a place and at a time + individually chosen by them. + + j. Sui Generis Database Rights means rights other than copyright + resulting from Directive 96/9/EC of the European Parliament and of + the Council of 11 March 1996 on the legal protection of databases, + as amended and/or succeeded, as well as other essentially + equivalent rights anywhere in the world. + + k. You means the individual or entity exercising the Licensed Rights + under this Public License. Your has a corresponding meaning. + + +Section 2 -- Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, + the Licensor hereby grants You a worldwide, royalty-free, + non-sublicensable, non-exclusive, irrevocable license to + exercise the Licensed Rights in the Licensed Material to: + + a. reproduce and Share the Licensed Material, in whole or + in part; and + + b. produce, reproduce, and Share Adapted Material. + + 2. Exceptions and Limitations. For the avoidance of doubt, where + Exceptions and Limitations apply to Your use, this Public + License does not apply, and You do not need to comply with + its terms and conditions. + + 3. Term. The term of this Public License is specified in Section + 6(a). + + 4. Media and formats; technical modifications allowed. The + Licensor authorizes You to exercise the Licensed Rights in + all media and formats whether now known or hereafter created, + and to make technical modifications necessary to do so. The + Licensor waives and/or agrees not to assert any right or + authority to forbid You from making technical modifications + necessary to exercise the Licensed Rights, including + technical modifications necessary to circumvent Effective + Technological Measures. For purposes of this Public License, + simply making modifications authorized by this Section 2(a) + (4) never produces Adapted Material. + + 5. Downstream recipients. + + a. Offer from the Licensor -- Licensed Material. Every + recipient of the Licensed Material automatically + receives an offer from the Licensor to exercise the + Licensed Rights under the terms and conditions of this + Public License. + + b. No downstream restrictions. You may not offer or impose + any additional or different terms or conditions on, or + apply any Effective Technological Measures to, the + Licensed Material if doing so restricts exercise of the + Licensed Rights by any recipient of the Licensed + Material. + + 6. No endorsement. Nothing in this Public License constitutes or + may be construed as permission to assert or imply that You + are, or that Your use of the Licensed Material is, connected + with, or sponsored, endorsed, or granted official status by, + the Licensor or others designated to receive attribution as + provided in Section 3(a)(1)(A)(i). + + b. Other rights. + + 1. Moral rights, such as the right of integrity, are not + licensed under this Public License, nor are publicity, + privacy, and/or other similar personality rights; however, to + the extent possible, the Licensor waives and/or agrees not to + assert any such rights held by the Licensor to the limited + extent necessary to allow You to exercise the Licensed + Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this + Public License. + + 3. To the extent possible, the Licensor waives any right to + collect royalties from You for the exercise of the Licensed + Rights, whether directly or through a collecting society + under any voluntary or waivable statutory or compulsory + licensing scheme. In all other cases the Licensor expressly + reserves any right to collect such royalties. + + +Section 3 -- License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the +following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified + form), You must: + + a. retain the following if it is supplied by the Licensor + with the Licensed Material: + + i. identification of the creator(s) of the Licensed + Material and any others designated to receive + attribution, in any reasonable manner requested by + the Licensor (including by pseudonym if + designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of + warranties; + + v. a URI or hyperlink to the Licensed Material to the + extent reasonably practicable; + + b. indicate if You modified the Licensed Material and + retain an indication of any previous modifications; and + + c. indicate the Licensed Material is licensed under this + Public License, and include the text of, or the URI or + hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any + reasonable manner based on the medium, means, and context in + which You Share the Licensed Material. For example, it may be + reasonable to satisfy the conditions by providing a URI or + hyperlink to a resource that includes the required + information. + + 3. If requested by the Licensor, You must remove any of the + information required by Section 3(a)(1)(A) to the extent + reasonably practicable. + + 4. If You Share Adapted Material You produce, the Adapter's + License You apply must not prevent recipients of the Adapted + Material from complying with this Public License. + + +Section 4 -- Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that +apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right + to extract, reuse, reproduce, and Share all or a substantial + portion of the contents of the database; + + b. if You include all or a substantial portion of the database + contents in a database in which You have Sui Generis Database + Rights, then the database in which You have Sui Generis Database + Rights (but not its individual contents) is Adapted Material; and + + c. You must comply with the conditions in Section 3(a) if You Share + all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not +replace Your obligations under this Public License where the Licensed +Rights include other Copyright and Similar Rights. + + +Section 5 -- Disclaimer of Warranties and Limitation of Liability. + + a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE + EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS + AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF + ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, + IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, + WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR + PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, + ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT + KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT + ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. + + b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE + TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, + NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, + INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, + COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR + USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR + DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR + IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. + + c. The disclaimer of warranties and limitation of liability provided + above shall be interpreted in a manner that, to the extent + possible, most closely approximates an absolute disclaimer and + waiver of all liability. + + +Section 6 -- Term and Termination. + + a. This Public License applies for the term of the Copyright and + Similar Rights licensed here. However, if You fail to comply with + this Public License, then Your rights under this Public License + terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under + Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided + it is cured within 30 days of Your discovery of the + violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any + right the Licensor may have to seek remedies for Your violations + of this Public License. + + c. For the avoidance of doubt, the Licensor may also offer the + Licensed Material under separate terms or conditions or stop + distributing the Licensed Material at any time; however, doing so + will not terminate this Public License. + + d. Sections 1, 5, 6, 7, and 8 survive termination of this Public + License. + + +Section 7 -- Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different + terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the + Licensed Material not stated herein are separate from and + independent of the terms and conditions of this Public License. + + +Section 8 -- Interpretation. + + a. For the avoidance of doubt, this Public License does not, and + shall not be interpreted to, reduce, limit, restrict, or impose + conditions on any use of the Licensed Material that could lawfully + be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is + deemed unenforceable, it shall be automatically reformed to the + minimum extent necessary to make it enforceable. If the provision + cannot be reformed, it shall be severed from this Public License + without affecting the enforceability of the remaining terms and + conditions. + + c. No term or condition of this Public License will be waived and no + failure to comply consented to unless expressly agreed to by the + Licensor. + + d. Nothing in this Public License constitutes or may be interpreted + as a limitation upon, or waiver of, any privileges and immunities + that apply to the Licensor or You, including from the legal + processes of any jurisdiction or authority. + + +======================================================================= + +Creative Commons is not a party to its public +licenses. Notwithstanding, Creative Commons may elect to apply one of +its public licenses to material it publishes and in those instances +will be considered the “Licensor.” The text of the Creative Commons +public licenses is dedicated to the public domain under the CC0 Public +Domain Dedication. Except for the limited purpose of indicating that +material is shared under a Creative Commons public license or as +otherwise permitted by the Creative Commons policies published at +creativecommons.org/policies, Creative Commons does not authorize the +use of the trademark "Creative Commons" or any other trademark or logo +of Creative Commons without its prior written consent including, +without limitation, in connection with any unauthorized modifications +to any of its public licenses or any other arrangements, +understandings, or agreements concerning use of licensed material. For +the avoidance of doubt, this paragraph does not form part of the +public licenses. + +Creative Commons may be contacted at creativecommons.org. +``` + + +### SPIRV-Tools + +``` +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +``` + + +### TinyEXR + +``` +Copyright (c) 2014 - 2018, Syoyo Fujita and many contributors. +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 ------------------------------------------------- + +BEGIN ASL-2.0.txt + +// Copyright 2017 The Wuffs Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +END ASL-2.0.txt + +------------------ + +BEGIN third_party/tinyexr/APACHE2_LICENSE.txt + + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +END third_party/tinyexr/APACHE2_LICENSE.txt +``` + + +### Vulkan Memory Allocator + +``` +Copyright (c) 2017-2019 Advanced Micro Devices, Inc. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +``` diff --git a/viewer/build-workstation.mjs b/viewer/build-workstation.mjs new file mode 100644 index 0000000..d87273a --- /dev/null +++ b/viewer/build-workstation.mjs @@ -0,0 +1,29 @@ +import {createRequire} from 'node:module'; +import {fileURLToPath} from 'node:url'; +import {readFile, writeFile, copyFile} from 'node:fs/promises'; +import path from 'node:path'; +const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..'); +const require=createRequire(path.join(root,'viewer/package.json')); +const {build}=require('esbuild'); +const source=path.join(root,'src/dvidia_training'); +const modules=path.join(root,'viewer/node_modules'); +const packageInfo=JSON.parse(await readFile(path.join(modules,'@mujoco/mujoco/package.json'),'utf8')); +if(packageInfo.version!=='3.15.0')throw new Error('The live workstation requires the pinned MuJoCo 3.15.0 runtime.'); +const options={bundle:true,minify:true,target:['es2022'],platform:'browser', + nodePaths:[modules],legalComments:'none',charset:'utf8', + alias:{three:path.join(modules,'three/build/three.module.js'), + 'three/addons/controls/OrbitControls.js':path.join(modules,'three/examples/jsm/controls/OrbitControls.js'), + 'three/addons/controls/TransformControls.js':path.join(modules,'three/examples/jsm/controls/TransformControls.js'), + '@mujoco/mujoco':path.join(modules,'@mujoco/mujoco/mujoco.js')}}; +await build({...options,entryPoints:[path.join(source,'workstation.js')], + outfile:path.join(source,'workstation.bundle.js'),format:'esm', + banner:{js:'/* DVIDIA live workstation. MIT. Three.js r180 MIT. See workstation.third-party.txt. */'}}); +await build({...options,entryPoints:[path.join(source,'workstation_worker.js')], + outfile:path.join(source,'workstation_worker.bundle.js'),format:'esm',external:['module'], + banner:{js:'/* DVIDIA live workstation worker. MIT. MuJoCo 3.15.0 Apache-2.0. See workstation.third-party.txt. */'}}); +await copyFile(path.join(modules,'@mujoco/mujoco/mujoco.wasm'),path.join(source,'mujoco.wasm')); +const notices=await readFile(path.join(source,'reference_replay.third-party.txt'),'utf8'); +const engineLicense=await readFile(path.join(root,'third_party/mujoco/LICENSE.txt'),'utf8'); +const engineNotices=await readFile(path.join(root,'third_party/mujoco/THIRD_PARTY_NOTICES.txt'),'utf8'); +await writeFile(path.join(source,'workstation.third-party.txt'),notices+'\n\nMuJoCo 3.15.0, Google DeepMind\nhttps://github.com/google-deepmind/mujoco/tree/3.15.0\nOfficial WASM distribution, unmodified binary; JavaScript bundled/minified by esbuild.\n\n'+engineLicense+'\n\n'+engineNotices); +console.log('Built live workstation UI, worker and pinned MuJoCo 3.15.0 WASM.'); diff --git a/viewer/package-lock.json b/viewer/package-lock.json index fcf44a8..24ef791 100644 --- a/viewer/package-lock.json +++ b/viewer/package-lock.json @@ -9,7 +9,9 @@ "version": "0.1.0", "license": "MIT", "devDependencies": { + "@mujoco/mujoco": "3.15.0", "esbuild": "0.25.10", + "playwright": "1.62.1", "three": "0.180.0" } }, @@ -455,6 +457,13 @@ "node": ">=18" } }, + "node_modules/@mujoco/mujoco": { + "version": "3.15.0", + "resolved": "https://registry.npmjs.org/@mujoco/mujoco/-/mujoco-3.15.0.tgz", + "integrity": "sha512-79j0h4Tok+igTkVBxMPkRvTmztJoyEaNyDrSbHC0s0yOsSmLcyMp+sIS1zGvYKeXYmSt9xV4vXVwLu/CvfHvMg==", + "dev": true, + "license": "Apache-2.0" + }, "node_modules/esbuild": { "version": "0.25.10", "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.10.tgz", @@ -497,6 +506,53 @@ "@esbuild/win32-x64": "0.25.10" } }, + "node_modules/fsevents": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", + "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/playwright": { + "version": "1.62.1", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.62.1.tgz", + "integrity": "sha512-0M+L3LAD8/nm554LOla9Ayx0j0tmFZ0FBcoQ7F1VuVHpM/XpiC8RcDzBQB8W5+hA8L22THxELzeF+2WcUzvcLg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.62.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + }, + "optionalDependencies": { + "fsevents": "2.3.2" + } + }, + "node_modules/playwright-core": { + "version": "1.62.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.62.1.tgz", + "integrity": "sha512-wPYSwEBJY9GHraISXqyqtx0na0LpO3XEX7jNDhntbex7tzUS7kLnZsOlFruFJB4Hi/rhDMjXGqHewDZ68nYZVw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/three": { "version": "0.180.0", "resolved": "https://registry.npmjs.org/three/-/three-0.180.0.tgz", diff --git a/viewer/package.json b/viewer/package.json index 3d14d81..8845ac0 100644 --- a/viewer/package.json +++ b/viewer/package.json @@ -5,6 +5,15 @@ "description": "Pinned build dependencies for the self-hosted DVIDIA reference replay", "license": "MIT", "type": "module", - "scripts": {"build": "node ../scripts/build-reference-viewer.mjs", "build:assets": "node build-assets.mjs"}, - "devDependencies": {"esbuild": "0.25.10", "three": "0.180.0"} + "scripts": { + "build": "node ../scripts/build-reference-viewer.mjs", + "build:assets": "node build-assets.mjs", + "build:workstation": "node build-workstation.mjs" + }, + "devDependencies": { + "@mujoco/mujoco": "3.15.0", + "esbuild": "0.25.10", + "playwright": "1.62.1", + "three": "0.180.0" + } }