The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Rebuild Voxel Worlds as an editable 3D environment and asset studio (#146)
Dee882503054b9d
diff --git a/.github/workflows/experience-checks.yml b/.github/workflows/experience-checks.ymlindex de80ca03c..6dcdcc04e 100644--- a/.github/workflows/experience-checks.yml+++ b/.github/workflows/experience-checks.yml@@ -20,7 +20,9 @@ jobs:with:node-version: '22.23.2'- name: Verify generated artifacts match reviewed sources- run: node store/tools/build-experiences.mjs --check+ run: |+ sh store/agents/voxel-worlds/toolchain/setup.sh+ node store/tools/build-experiences.mjs --check- name: Verify packaged branding matches desktop assetsrun: node store/tools/build-experience-branding.mjs --check- name: Check models, packages and viewer behavior@@ -68,6 +70,13 @@ jobs:env:EXPERIENCE_IDS: generative-art,music-studio,creative-directionrun: node store/tools/experience-tests/browser.mjs+ - name: Edit, walk and export a Voxel Worlds project in the browser+ env:+ VOXEL_QA_ROOT: work/experience-evidence/tidelands-browser+ run: |+ npm ci --prefix store/agents/voxel-worlds/toolchain --ignore-scripts --no-audit --no-fund+ node store/agents/voxel-worlds/test/browser.mjs+ node store/agents/voxel-worlds/test/acceptance.mjs- name: Verify MIDI and aligned audio with independent readersrun: |python3 -m venv /tmp/music-delivery-readerdiff --git a/HANDOFF.md b/HANDOFF.mdindex 861ec5025..2a8dbecb3 100644--- a/HANDOFF.md+++ b/HANDOFF.md@@ -6,10 +6,18 @@ The main checkout is shared with other sessions; leave it alone.**Current sequential rebuild:** the user asked to improve the remaining five one by one.See [FIVE-REBUILDS.md](work/FIVE-REBUILDS.md). Creative Direction now has an editable brandstudio, source save bridge and complete launch exports; [FORME-REBUILD.md](work/FORME-REBUILD.md)-records the actual tests and limits. It is relisted for Store testing. Voxel Worlds is next;-Drone Pilot, Game Master and Lab Bench remain unlisted. The older “focus only on Art/Music”+records the actual tests and limits. It is published for Store testing (#141). Voxel Worlds now has a source-backed 3D studio,+standard exports and six independently reopened deliveries; publication is in progress. Read+[its acceptance evidence](store/agents/voxel-worlds/test/ACCEPTANCE.md). Drone Pilot is next;+Game Master and Lab Bench also remain unlisted. The older “focus only on Art/Music”instruction below is historical and has been superseded by this user request.+**Score installation regression fixed and published (#145):** setup now installs official+checksum-pinned LilyPond 2.26.0 when needed. Real Intel Mac and Linux CI installation/engraving+passed. The published package was installed normally at `~/.harness/dsh/autonomous/score` on+this Mac, and `dsh doctor autonomous/score` passed; the user was told to click Retry.+The public catalog and actual resolver bytes were verified at `b74d3f2b`.+**Current authoring rebuild:** read [AUTHORING-REBUILD.md](work/AUTHORING-REBUILD.md). Art and Musicnow use source under their own `template/studio/` directories, with real editable projects andproduction exports. `build-experiences.mjs` delegates to their builders. Their original presetdiff --git a/desktop/lib/widgets/engine_identity.dart b/desktop/lib/widgets/engine_identity.dartindex ec21d8ef4..8edb386a9 100644--- a/desktop/lib/widgets/engine_identity.dart+++ b/desktop/lib/widgets/engine_identity.dart@@ -296,7 +296,7 @@ const _harnesses = <String, EngineIdentity>{id: 'autonomous/voxel-worlds',label: 'Voxel Worlds',category: 'Games',- tagline: 'Build and walk a seeded voxel island',+ tagline: 'Build original worlds. Keep every piece.',creator: 'Autonomous',color: Color(0xffaac785),asset: 'assets/engine-icons/voxel-worlds.png',diff --git a/store/agents/voxel-worlds/.gitattributes b/store/agents/voxel-worlds/.gitattributesnew file mode 100644index 000000000..e67fd8e26--- /dev/null+++ b/store/agents/voxel-worlds/.gitattributes@@ -0,0 +1,2 @@+template/world/index.html linguist-generated=true whitespace=-blank-at-eol,-space-before-tab+toolchain/package-lock.json linguist-generated=truediff --git a/store/agents/voxel-worlds/.gitignore b/store/agents/voxel-worlds/.gitignorenew file mode 100644index 000000000..00758e57d--- /dev/null+++ b/store/agents/voxel-worlds/.gitignore@@ -0,0 +1,4 @@+toolchain/node_modules/+toolchain/browsers/+template/.harness/+template/delivery/diff --git a/store/agents/voxel-worlds/AGENTS.md b/store/agents/voxel-worlds/AGENTS.mdindex 551f10f68..6d51e7009 100644--- a/store/agents/voxel-worlds/AGENTS.md+++ b/store/agents/voxel-worlds/AGENTS.md@@ -1,65 +1,24 @@-# Voxel Worlds harness--You turn a plain-English description into a **playable 3D voxel world in a single self-contained-`world/index.html`**. The warehouse Page loads that file in the pane, so a visitor can walk it.--## What a good world is--- **One file.** Everything (three.js, textures, controls, audio) bundled or generated inline — no- CDN at runtime so the pane can load it offline. A long global world script plus a small `onload`- is fine.-- **Walkable, first-person, mouse+keyboard** (and touch), with block **place** and **break**.- These four things are the floor; without them the world is a diorama, not a game.-- **A day/night cycle** and a small **HUD** (a crosshair, a hotbar, a health/heart row) separate a- "gold" world from a "silver" one on the Voxelcraft-style checklists. Textured blocks read far- better than flat colors — procedurally texture grass/dirt/stone/wood (noise, not a flat fill).-- **Lean on specific palette terms.** "a small farming village with wheat fields and a dirt road- through the center, river along the eastern edge" beats "a cool world". Vague nouns make generic- mush; concrete nouns make adjacent and aligned things.--## How to work so the pane moves--1. **Save within a minute.** Materialize `world/index.html` with a tiny camera on a flat ground tile- first, so the header shows a state and the pane can load it. Then build up.-2. **Build one feature at a time**, and after every pass verify in the browser: load the file, take- a screenshot from the *player camera* (not a debug angle), look at it. The camera is the referee.- Fix what you can see, re-take, repeat.-3. **Update `.harness/verdict.json` at every check and phase change** — `ready`, a one-line- `summary` for the header, `phases` (world → interaction → polish), and `findings` for anything- unfinished. Write it as a feed, not once at the end.--## Rules--- If the user reports a bug in plain words ("I can't climb out of the ocean"), diagnose the actual- cause (here: the classic 1-block shore wall) and fix it rather than papering over it.-- Mark every crafted decision USER vs AI with one line in `world/DESIGN.md`- (`YYYY-MM-DD | USER|AI | topic | decision | still in build?`) so discarded ideas don't- resurrect.-- Say plainly in `summary` what is real and playable now, and what is not. Don't claim "done" on a- build you haven't walked.--## Shipped experience and operating standard--The workspace starts with **Tidelands**, a working experience, not an empty placeholder.-Walk, collision, jump, place/break, five materials, day/night, island overview, world JSON export.--- Read the existing artifact before replacing it. The useful model boundaries are world geometry, collision, camera, raycast editing, day cycle.-- Preserve working interactions and exports when extending the artifact. Match the user's brief;- the starter's genre and visual style are examples, not a ceiling.-- Expose meaningful domain controls and outputs. Every control must change real state; every- displayed metric must be computed from that state. Never invent model activity or test results.-- Use named random streams and a fixed simulation/score clock. Sample seeds, repeat the same- seed, inspect exported data, and verify keyboard/touch controls in the actual viewer.-- This HTML runs with same-origin APIs in the shared viewer. Sibling fetches, localStorage,- downloads and pointer lock are available. Keep files portable and support direct opening.-- Do not equate an existing HTML file, a successful reload, or a source-string test with a usable- result. `seed-verdict.sh` deliberately keeps `ready:false`; write `ready:true` only after your- checks establish it. Record exact commands, sampled seeds, observations and limitations.-- Never claim a test coverage percentage for browser code based on Node subprocess tests.--## Check your actual edited model--Run `node tools/check.mjs --seeds 100` in the workspace. It reads the pure model from-`<script id="harness-model">` in the artifact, checks domain invariants, repeats each seed, and-writes `.harness/model-check.json`. Preserve that script boundary when editing. Model checks are-followed by browser interaction, exported-output inspection, and visual or listening review.+# Voxel Worlds — Tidelands++Turn the user's brief into an original, editable 3D environment or reusable asset kit. Read the+`world-builder` skill. The harbor is an authored example, not a style or genre restriction.+Work in `world/project.json` and the source under `studio/`. Build with `node tools/build.mjs`.++Name meaningful objects: buildings, terrain sections, furniture, props and modules. Keep approved+objects intact during targeted revisions. Use the actual physical scale, useful entrances and+clear walking routes. Do not add fake health, activity, progress or game mechanics.++The studio supports direct object movement, quarter turns, duplication, locks, visibility,+voxel build/erase/paint, editable materials, undo/redo and explicit workspace saves. Browser drafts+and agent source edits may conflict: preserve both versions and resolve deliberately. Offline+projects remain editable and can be reopened from `.tidelands.json`.++Deliver usable GLB meshes, VOX geometry, source JSON and an offline studio/walkthrough. Run+`node tools/check.mjs` and `node tools/export.mjs`, then exercise the actual viewer and inspect+exported files independently. A successful build never marks a world ready. Write an honest+`.harness/verdict.json` after walking, editing and export checks. Record the brief, decisions,+revision scope and limitations in `world/DESIGN.md`.++A walkable environment is not a complete game. Do not claim rules, animation, multiplayer,+structural safety or accessibility certification that were not implemented and tested. Geometry+checks use a 1.7 m tall, 0.52 m wide visitor; they do not replace actual browser walking.diff --git a/store/agents/voxel-worlds/PROVENANCE.md b/store/agents/voxel-worlds/PROVENANCE.mdnew file mode 100644index 000000000..9fc270226--- /dev/null+++ b/store/agents/voxel-worlds/PROVENANCE.md@@ -0,0 +1,20 @@+# Provenance++The studio, editable model, authored scenes, exporters and visual identity are original OpenHarness+contributor work under the package's MIT license. The original island implementation is retained+in `store/tools/experiences/` and is no longer this package's builder.++- Three.js 0.186.0 (MIT), pinned in the local toolchain; its license notice is retained in bundled+ HTML. Source: https://github.com/mrdoob/three+- esbuild 0.27.2 (MIT), build time only. https://github.com/evanw/esbuild+- Playwright Core 1.63.0 (Apache-2.0), browser verification. https://github.com/microsoft/playwright+- Khronos glTF Validator 2.0.0-dev.3.10 (Apache-2.0), independent export checks.+ https://github.com/KhronosGroup/glTF-Validator+- GLB encoding follows glTF 2.0: https://github.com/KhronosGroup/glTF/tree/main/specification/2.0+- VOX encoding and static transforms follow Ephtracy's published format specifications:+ https://github.com/ephtracy/voxel-model++No sampled textures, downloaded 3D models or generated bitmap assets are included. The harbor,+courtyard and dungeon are authored acceptance fixtures, not customer projects or evidence of an+installed coding agent completing those prompts. Setup reuses an installed Chrome/Chromium or+installs Playwright's browser into the package-local cache. The offline HTML embeds its runtime.diff --git a/store/agents/voxel-worlds/README.md b/store/agents/voxel-worlds/README.mdindex 6e9b43a42..1a25b2a66 100644--- a/store/agents/voxel-worlds/README.md+++ b/store/agents/voxel-worlds/README.md@@ -1,60 +1,51 @@# Voxel Worlds — Tidelands-> Withdrawn from Store discovery on 2026-09-20: the current starter does not meet our-> standard for an open-ended tool that completes real user work. Existing projects and-> source remain available. See [the product review](../../../work/SUPERPOWERS.md).--Build and walk a seeded voxel island. Sculpt terrain, place and break blocks, explore a cabin and lighthouse, change the light, and save your world.--## Try it--> Turn this island into a harbor village with a walkable pier, a hilltop observatory, and lanterns along the road.--The starter already works before the first prompt. Change it with the agent, interact with the-result in the pane, and keep the output. Everything needed at runtime is in `world/index.html`.-It works offline and can be opened outside Harness.--## What you can do--Walk, collision, jump, place/break, five materials, day/night, island overview, world JSON save and restore.--## Build on the starter--The model functions `voxelWorld`, `movePlayer`, `raycastWorld`, `putBlock` and `importWorld` are the starting points for substantive changes. Preserve seed-reproducibility and user controls while changing the domain behavior. A different brief can replace-this starter's entire visual language. Keep the artifact self-contained and test the actual result.--The source checkout builds these starters with `node store/tools/build-experiences.mjs`. Installed-workspaces are editable HTML; no build tool, network dependency or paid service is required.--## Verification--Model census: `node --test store/tools/experience-tests/models.test.mjs` from the source checkout.-Browser interactions, exports, same-origin APIs and manifest routing: see-[`store/tools/experience-tests`](../../tools/experience-tests/README.md).--`seed-verdict.sh` establishes only artifact presence and keeps `ready:false`. The agent must run-and record real domain and browser checks before writing a ready verdict. No cross-device pixel or-audio equality is promised. The research is inspiration; this is original code, not a wrapper of-any cited third-party engine.--## Check your actual edited model--Run `node tools/check.mjs --seeds 100` in the workspace. It reads the pure model from-`<script id="harness-model">` in the artifact, checks domain invariants, repeats each seed, and-writes `.harness/model-check.json`. Preserve that script boundary when editing. Model checks are-followed by browser interaction, exported-output inspection, and visual or listening review.--## Logo and icon--The original identity ships in `brand/`: [vector icon](brand/icon.svg),-[256px PNG](brand/icon.png), [light logo](brand/logo.svg) and-[dark logo](brand/logo-dark.svg). The same mark appears in the starter header,-its offline favicon and the desktop Store/picker/tabs. MIT, by OpenHarness contributors.--## Credit and stewardship--Original implementation and visual identity by OpenHarness contributors, maintained by-Autonomous under the [MIT license](LICENSE). Report issues in the OpenHarness repository.+Turn an idea into an editable 3D environment and a reusable asset kit. Describe a harbor, a civic+courtyard, a dungeon module or a place of your own. The agent authors the geometry; you can move+objects, sculpt voxels, change materials, walk the result and take it into other tools.++The studio supports named objects, snapping movement, quarter turns, duplication, locking,+visibility, build/erase/paint brushes, custom materials, physical scale, undo/redo and lighting.+Save source to the workspace, reopen complete projects, and retain both versions when an agent+revision conflicts with a browser draft. A single static MagicaVoxel asset can be imported with+its palette and orientation, including a single-instance transform graph.++Export a named GLB in meters, a flattened VOX, individual reusable assets, the source project and+an offline editable studio/walkthrough. A ZIP collects the complete handoff. The harbor is an+authored example; there is no fixed style selector. The earlier island implementation is preserved+under `store/tools/experiences/voxel-worlds.*` for reference.++## Use and build++Harness setup installs pinned package-local Three.js, esbuild and browser tools. Node comes from+the shared runtime helper when needed. No CDN, paid API or network is required by the built HTML.++```sh+sh toolchain/setup.sh+# Inside a materialized workspace (VOXEL_DSH_DIR is set by Harness):+node tools/build.mjs+node tools/check.mjs+node tools/export.mjs+```++Edit `world/project.json`; source modules live under `studio/`. The [project contract](skills/world-builder/references/project.md)+defines limits and coordinates. The local viewer only accepts same-origin saves, verifies source+revisions and keeps history. It runs trusted workspace code; it is not a sandbox for hostile scripts.++## What the files preserve++GLB retains visible geometry as named meshes with materials, in meters, Y-up. VOX flattens geometry+and colors, Z-up. The source JSON keeps object structure and editing settings. Isolated object+exports retain faces hidden by other objects in the scene. MagicaVoxel import supports one static+model/instance; it rejects multi-model scenes, animation and missing palettes. Imported placement+is rebased to the object bounds; specialized shaders are not reproduced.++This is an environment and asset authoring tool. Walking uses a simulated 1.7 m visitor; it does+not supply game rules, multiplayer, rigging, construction validation or accessibility certification.+Geometry checks do not establish visual quality. See [acceptance evidence](test/ACCEPTANCE.md)+for the tests actually performed and remaining validation.++The original [logo and icon](brand/) are retained in the Store, studio and favicon. Three.js and+runtime provenance are recorded in [PROVENANCE.md](PROVENANCE.md).diff --git a/store/agents/voxel-worlds/harness.json b/store/agents/voxel-worlds/harness.jsonindex a7a8dee86..b2fb3a015 100644--- a/store/agents/voxel-worlds/harness.json+++ b/store/agents/voxel-worlds/harness.json@@ -4,7 +4,7 @@"name": "Voxel Worlds","category": "Games","author": "Autonomous",- "description": "Build and walk a seeded voxel island. Sculpt terrain, place and break blocks, explore a cabin and lighthouse, change the light, and save your world.",+ "description": "Turn an idea into an editable 3D environment and a reusable asset kit. Shape named objects, sculpt terrain, walk the result, import voxel assets and export GLB, VOX and an offline walkthrough.","engine": "claude","workspace": {"template": "template",@@ -25,11 +25,11 @@"doctor": "toolchain/doctor.sh"},"viewer": {- "use": "autonomous/web-viewer",+ "command": "toolchain/viewer.sh","artifactExtensions": [".html"],- "url": "http://127.0.0.1:${port}/?file=${artifact}"+ "url": "http://127.0.0.1:${port}/"},"verdict": ".harness/verdict.json"}diff --git a/store/agents/voxel-worlds/skills/world-builder/SKILL.md b/store/agents/voxel-worlds/skills/world-builder/SKILL.mdindex 870d66ec6..fa5b9490f 100644--- a/store/agents/voxel-worlds/skills/world-builder/SKILL.md+++ b/store/agents/voxel-worlds/skills/world-builder/SKILL.md@@ -1,73 +1,65 @@---name: world-builder-description: Build a playable 3D voxel world in one HTML file from a plain-English description. Use whenever the user asks for a world, a voxel scene, a Minecraft-style sandbox, a place to walk around, or a prompt-to-world build.+description: Turn a user's brief into an editable voxel environment or asset kit in Voxel Worlds. Use for original scene design, modular assets, terrain sculpting, walkable spaces, importing VOX assets and delivering GLB/VOX files with an offline studio.----# world-builder--Take the user's description and produce a **single self-contained `world/index.html`** that is-walkable first-person, lets the player place and break blocks, has a day/night cycle, and runs-entirely offline (all three.js/audio inline — no CDN at runtime). Everything ships in that one-file so the web-viewer pane can load it directly.--## The floor (do these first, in order)--1. **Camera + controls.** First-person pointer-lock mouse-look, WASD movement, canvas click to- grab. Touch: a virtual stick / drag-to-look so it works on a phone too.-2. **Terrain.** Generate from a seeded noise function so the same description + seed gives the same- world every time. Keep it small enough to walk easily (a few dozen blocks per axis).-3. **Place & break.** A crosshair; left click breaks the targeted block, right click places a block- from a small hotbar. Visible block selection outline.-4. **Day/night** — a slowly-moving sun/moon and sky color ramp (or at minimum a timed light shift).- A clock or sky clearly shows it.--## The gold checklist (what separates a good world from a demo)--- **Textured, not flat**: procedurally texture grass/dirt/stone/wood (noise + a few tones), so the- world reads as voxels from a real game, not colored boxes.-- **HUD**: crosshair, a health/heart row, and a 5-slot hotbar (even if hotbar is read-only at- first).-- **Specific palette terms win.** Concrete nouns ("dirt road through the center, river along the- eastern edge, wheat fields") produce adjacency-aware aligned things (roads join into junctions,- shorelines blend into sand). Vague nouns make generic mush. Ask one round of clarifying- questions only — then default aggressively.-- **Audio**: at least a place/break click; a simple background tone is a bonus.--## Verify like a visitor, not a compiler--Load `world/index.html`, screenshot from the **player camera**, and look. Walk the world: can you-actually get in and out of the water, up a slope, through a doorway? The camera is the referee —-a world you cannot move through is not done no matter how the code reads. Render, look, fix,-re-render.--## Verdict feed--Write `.harness/verdict.json` (in the workspace) at every change:--```json-{ "spec": 1, "ready": false, "summary": "walkable village: road, river, houses · day/night · no audio yet",- "findings": [{ "severity": "warning", "kind": "audio", "message": "no place/break sound yet" }],- "artifact": "world/index.html",- "phases": [{ "id": "world", "name": "World", "state": "done" },- { "id": "interaction", "name": "Interaction", "state": "active" },- { "id": "polish", "name": "Polish", "state": "pending" }],- "updatedAt": "2026-09-18T00:00:00Z" }-```--## Starting from Tidelands--The template is functional: Walk, collision, jump, place/break, five materials, day/night, island overview, world JSON export.--Keep its useful controls and exports when making a user's creation. Test the behavioral core-(world geometry, collision, camera, raycast editing, day cycle) as well as the visible result. A self-contained HTML file can still have well-separated-model, rendering, input and export functions. Do not turn a finished starter into a waiting screen.--Presence-only helpers do not prove correctness or reproducibility. Record actual evidence before-marking the result ready. Export and reopen the result as part of the handoff to the user.--## Check your actual edited model--Run `node tools/check.mjs --seeds 100` in the workspace. It reads the pure model from-`<script id="harness-model">` in the artifact, checks domain invariants, repeats each seed, and-writes `.harness/model-check.json`. Preserve that script boundary when editing. Model checks are-followed by browser interaction, exported-output inspection, and visual or listening review.+# From an idea to a world the user can keep building++Understand the place, purpose and deliverable. A game environment, architectural massing study,+tabletop kit and miniature scene need different geometry. State sensible assumptions and produce+an original first version. Do not funnel the person into the harbor, a style enum or a seed picker.++Read [the project contract](references/project.md). The editable source is `world/project.json`.+Create meaningful named objects with local geometry; use custom palettes and physical scale.+The coding agent authors new geometry and layouts from the brief. The studio's controls edit+that geometry directly; there is no pretend generation button or remote model dependency.++## Build and revise++1. Read the existing project and `world/DESIGN.md`. Preserve supplied assets, approved objects,+ names, physical scale and decisions unless the user asks to change them.+2. Author boxes and cell edits, with generous readable forms at the chosen voxel scale. Shape+ roofs, openings, terrain and paths deliberately. Ensure that different briefs produce+ different useful structures, not recolored copies of the same scene.+3. Build: `node tools/build.mjs`. For a workspace outside the package, `VOXEL_DSH_DIR` is provided+ by the harness and resolves the installed tools. Setup installs Node and pinned local tools.+4. Open the actual viewer. Test object selection, transforms, sculpting, materials and save.+ Walk critical entrances, slopes and destinations with keyboard or touch controls. Check the+ result from the visitor's viewpoint as well as the overview. Correct geometry, not requirements.+5. A targeted revision should touch only the requested objects or decisions. Compare preserved+ objects in source and, for an approved asset, its isolated GLB/VOX export before and after.+ The studio keeps undo history; workspace saves retain prior sources in `.harness/history/`.++## Supply and save++The studio can import one static `.vox` model, including a single-instance transform graph.+Geometry, palette and orientation are preserved; the imported object is rebased for placement in+this world, at this project's physical voxel scale. Multi-model scenes, animation, absent palettes+and hidden assets fail explicitly. Specialized MagicaVoxel shaders are not reproduced.++Save to workspace writes the actual source with a revision check and rebuilds the offline artifact.+An agent revision arriving during a browser edit offers both versions instead of silently replacing+one. Keep the draft download before restoring the source. Open accepts a project file; the local+viewer also offers recent home-folder projects and an explicit path field. Portable HTML uses the+browser file picker. Save a complete `.tidelands.json` to retain editable object structure.++## Export and verify++Run `node tools/check.mjs` for geometry, a VOX round trip and finite walking-route checks. It writes+`.harness/world-check.json`, not a ready verdict. Run `node tools/export.mjs` for the delivery folder:++- GLB: Y-up, meters, named visible meshes, palette materials and emissive/transparent surfaces.+- VOX: Z-up, flattened visible cells and RGBA palette. Source object boundaries are not in VOX.+- Project JSON: named source objects, rotations, edits, locks, palette, scale, start and destinations.+- `studio.html` and `walkthrough.html`: standalone files with their runtime embedded, usable offline.+- ZIP and README: the files above, plus a finite route-check report.++Browser exports use the current draft, including unsaved changes. Isolated object exports include+all of that object's faces, even where it touches other objects. Whole-scene GLB removes buried+faces; it is not a collision mesh or physics setup for another engine. Reopen GLB/VOX with an+independent reader, inspect scale/orientation/materials, and test the offline files. Report which+checks were actually performed; geometry checks do not establish visual quality or a user's “wow.”++Do not publish a world as ready based on file presence or a screenshot alone. Keep the old working+handoff while resolving a failing requirement. Return concrete files and concrete revision options+in the user's language, without requiring them to learn a 3D editor first.diff --git a/store/agents/voxel-worlds/skills/world-builder/references/project.md b/store/agents/voxel-worlds/skills/world-builder/references/project.mdnew file mode 100644index 000000000..c707063ff--- /dev/null+++ b/store/agents/voxel-worlds/skills/world-builder/references/project.md@@ -0,0 +1,34 @@+# Tidelands project contract++`world/project.json` uses `spec: "tidelands/2"`, a stable lowercase ID, title, original brief,+`size: [width,height,depth]` in voxels and `unit` in meters per voxel. Y is up; coordinates start+at zero. The dimensions are integers 4–128 with at most 1,048,576 total cells. Unit is 0.01–10 m.+Small-scale miniatures may not fit the 1.7 m visitor; use the orbit view and label that limitation.++Materials have unique IDs 1–255, name, hex `color`, boolean `solid`, `opacity` 0.05–1 and `emission`+0–1. ID 0 means air. Materials affect every object using that ID; duplicate a material when a+revision must remain local. `solid` affects the studio visitor, not exported engine physics.++Each object has a unique stable `id`, descriptive `name`, local `size`, world `origin`, `rotation`+0–3 (quarter turns around Y), `hidden`, `locked`, `boxes` and `edits`. Rotated bounds must fit the+world. Boxes are `[x,y,z,width,height,depth,materialId]`; cell edits are `[x,y,z,materialId]`.+Apply boxes in order, then cell edits in order. Air carves that object's geometry. Later objects+win at occupied cells; their air never deletes earlier objects. Use an object of its own for each+building, prop, terrain section or reusable module. Do not make the entire world one object.++Source limits: 128 objects, 8,388,608 total local cells, 16,777,216 box fill operations, 100,000+geometry commands and 12 MB JSON. Mesh/export limit: 350,000 exposed faces. Split complex work+into related projects or assets instead of bypassing budgets. Sculpting bakes an object's quarter+turn into its cells and may enlarge its local bounds while preserving existing world positions.+Painting changes existing cells only. Erasing a foreground object may reveal an object behind it.++`spawn` is `{position:[x,y,z],yaw}` where position is the visitor's feet; yaw 0 faces +Z, PI faces+−Z. Height is 1.7 m, width 0.52 m, step 0.45 m. Optional `stops` contain unique ID, name,+description and foot position. Studio stop buttons reposition the visitor; they do not prove a+walkable route. `light` is 0–1 around a day and `notes` describe useful handoff details.++The stored JSON is the source of truth. The built HTML embeds a validated snapshot and revision.+A browser save uses that revision and retains a prior source. An exported JSON preserves current+object data, including imported-asset provenance, but not temporary browser undo stacks. Generated+GLB positions are meters and use standard glTF colors; VOX exchanges Y/Z and reflects depth to+preserve handedness. VOX has no physical-scale field, so keep the README and source project.diff --git a/store/agents/voxel-worlds/store.json b/store/agents/voxel-worlds/store.jsonindex cde6cce3f..28e7772c2 100644--- a/store/agents/voxel-worlds/store.json+++ b/store/agents/voxel-worlds/store.json@@ -1,16 +1,28 @@{- "listed": false,+ "listed": true,"homepage": "https://github.com/autonomous-ai/openharness/tree/main/store/agents/voxel-worlds","license": "MIT",- "tagline": "Build and walk a seeded voxel island",+ "tagline": "Build original worlds. Keep every piece.","screenshots": [- "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/voxel-worlds/starter.jpg"+ "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/voxel-worlds/starter.jpg",+ "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/voxel-worlds/civic-court.jpg",+ "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/voxel-worlds/amber-vault.jpg"],"examples": [{- "prompt": "Turn this island into a harbor village with a walkable pier, a hilltop observatory, and lanterns along the road.",- "caption": "Tidelands · interactive offline starter",+ "prompt": "Build a cozy harbor village with a broad walking quay, a lighthouse and colorful workshops. Keep the buildings and boats separate so I can reuse them in my game; give me a GLB asset kit and an offline walkthrough.",+ "caption": "Author an editable environment, walk it and keep named 3D assets","image": "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/voxel-worlds/starter.jpg"+ },+ {+ "prompt": "Block out a civic arts courtyard with a sheltered gallery, water garden, reading canopy and sculpture. Let me move each structure and export the masses in meters for a 3D design tool.",+ "caption": "Revise real geometry and physical scale; export independent building masses",+ "image": "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/voxel-worlds/civic-court.jpg"+ },+ {+ "prompt": "Create a modular dungeon kit with a branching hall, an amber altar and an east treasury. Widen the west entrance while keeping my approved east wing unchanged, and export the modules.",+ "caption": "Preserve approved work while revising a reusable voxel kit",+ "image": "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/voxel-worlds/amber-vault.jpg"}]}diff --git a/store/agents/voxel-worlds/template/studio/app.js b/store/agents/voxel-worlds/template/studio/app.jsnew file mode 100644index 000000000..b90765246--- /dev/null+++ b/store/agents/voxel-worlds/template/studio/app.js@@ -0,0 +1,144 @@+import * as THREE from 'three';+import {OrbitControls} from 'three/addons/controls/OrbitControls.js';+import {TransformControls} from 'three/addons/controls/TransformControls.js';+import {validateProject,clone,escapeHTML as esc,compileWorld,meshWorld,rotatedSize,paintCells,cellAt,moveVisitor,fitsVisitor,navigationReport} from './project.mjs';+import {exportGLB,exportVOX,importVOX,addImportedAsset} from './formats.mjs';+import {zipFiles} from './archive.mjs';++const originalHTML='<!doctype html>'+document.documentElement.outerHTML;+const $=id=>document.getElementById(id),data=JSON.parse($('world-data').textContent),readonly=data.mode==='walk';+let project=validateProject(data.project),revision=project.revision,selected=project.objects.find(o=>!o.locked&&!o.hidden)?.id??project.objects[0].id,material=project.materials[0].id;+let world,meshes=[],tool='select',walking=false,visitor,pitch=0,dirty=false,connected=false,saving=false,sourcePending=null,pollEpoch=0,cycle=0;+const past=[],future=[],keys=new Set(),draftKey='tidelands:'+project.id,viewport=$('viewport');+const report=message=>{$('status').textContent=message;};+function failure(error){renderUI();report(error.message);const dialog=document.querySelector('dialog[open]');if(dialog){let notice=dialog.querySelector('[data-error]');if(!notice){notice=document.createElement('p');notice.dataset.error='';notice.setAttribute('role','alert');notice.style.color='#a24b2f';dialog.append(notice);}notice.textContent=error.message;}}+const guard=fn=>(...args)=>{try{const result=fn(...args);if(result?.catch)result.catch(failure);}catch(error){failure(error);}};+const download=(name,body,type='application/octet-stream')=>{const url=URL.createObjectURL(body instanceof Blob?body:new Blob([body],{type})),a=document.createElement('a');a.href=url;a.download=name;a.click();setTimeout(()=>URL.revokeObjectURL(url),10000);};+const stamp=()=>new Date().toISOString().slice(0,19).replace(/[:T]/g,'-');+const state=()=>{$('save-state').textContent=dirty?'Unsaved changes':connected?'Saved in workspace':'Editable offline project';$('save-source').hidden=!connected||readonly;$('save-source').disabled=!dirty||saving||Boolean(sourcePending);$('undo').disabled=!past.length;$('redo').disabled=!future.length;};+function saveDraft(){try{localStorage.setItem(draftKey,JSON.stringify({revision,project,at:Date.now()}));}catch{report('Browser draft storage is full. Save your project to keep these changes.');}}+function mutate(fn,message='World updated'){+ if(readonly)return;const next=clone(project);fn(next);const valid=validateProject(next);+ // Mesh before committing, so an over-budget scene cannot replace a working draft.+ const compiled=compileWorld(valid),geometry=meshWorld(valid,compiled);+ past.push(JSON.stringify(project));while(past.length>40||past.reduce((n,s)=>n+s.length,0)>16000000)past.shift();future.length=0;+ project=valid;world=compiled;dirty=true;renderWorld(geometry);renderUI();saveDraft();report(message);+}+function history(from,to){if(!from.length)return;to.push(JSON.stringify(project));project=validateProject(JSON.parse(from.pop()));dirty=true;rebuild();saveDraft();report('Edit history restored');}+const scene=new THREE.Scene(),camera=new THREE.PerspectiveCamera(43,1,.1,2000),renderer=new THREE.WebGLRenderer({antialias:true,preserveDrawingBuffer:true});+renderer.setPixelRatio(Math.min(devicePixelRatio,2));renderer.shadowMap.enabled=true;renderer.shadowMap.type=THREE.PCFSoftShadowMap;renderer.outputColorSpace=THREE.SRGBColorSpace;renderer.toneMapping=THREE.ACESFilmicToneMapping;renderer.toneMappingExposure=1.18;viewport.append(renderer.domElement);+const ambient=new THREE.HemisphereLight('#f1f1d9','#66716e',2.2),sun=new THREE.DirectionalLight('#ffedd1',3.1);sun.castShadow=true;sun.shadow.mapSize.set(2048,2048);sun.shadow.normalBias=.05;sun.shadow.bias=-.0001;scene.add(ambient,sun,sun.target);+const orbit=new OrbitControls(camera,renderer.domElement);orbit.enableDamping=true;orbit.dampingFactor=.09;orbit.maxPolarAngle=Math.PI*.49;orbit.minDistance=3;orbit.maxDistance=300;+const anchor=new THREE.Object3D();scene.add(anchor);const transform=new TransformControls(camera,renderer.domElement);transform.setTranslationSnap(1);transform.setSize(.65);scene.add(transform.getHelper());+const selectionBox=new THREE.Box3Helper(new THREE.Box3(),new THREE.Color('#da9a52'));selectionBox.material.depthTest=false;selectionBox.renderOrder=5;scene.add(selectionBox);+const hitBox=new THREE.Mesh(new THREE.BoxGeometry(1.015,1.015,1.015),new THREE.MeshBasicMaterial({color:'#fff2c7',wireframe:true,depthTest:false}));hitBox.visible=false;hitBox.renderOrder=6;scene.add(hitBox);+let grid,ground,dragOrigin=null,transformDragging=false;const glowLights=[];+function selectedObject(){return project.objects.find(o=>o.id===selected);}+function syncSelection(){const o=selectedObject();selectionBox.visible=Boolean(o&&!o.hidden&&!walking);transform.detach();if(!o||o.hidden)return;const size=rotatedSize(o);selectionBox.box.set(new THREE.Vector3(...o.origin),new THREE.Vector3(...o.origin.map((n,i)=>n+size[i])));anchor.position.set(...o.origin);if(tool==='select'&&!o.locked&&!walking&&!readonly)transform.attach(anchor);}+transform.addEventListener('dragging-changed',event=>{+ transformDragging=event.value;orbit.enabled=!event.value&&!walking;+ if(event.value)dragOrigin=[...selectedObject().origin];+ else if(dragOrigin){const next=anchor.position.toArray().map(Math.round);dragOrigin=null;try{mutate(p=>{p.objects.find(o=>o.id===selected).origin=next;},'Object moved');}catch(error){rebuild();report(error.message);}syncSelection();}+});+transform.addEventListener('objectChange',()=>{+ if(!dragOrigin)return;const o=selectedObject(),size=rotatedSize(o);anchor.position.fromArray(anchor.position.toArray().map((n,i)=>Math.max(0,Math.min(project.size[i]-size[i],Math.round(n)))));+ const delta=anchor.position.toArray().map((n,i)=>n-dragOrigin[i]);for(const mesh of meshes)if(mesh.userData.id===selected)mesh.position.set(...delta);+ selectionBox.box.set(anchor.position.clone(),anchor.position.clone().add(new THREE.Vector3(...size)));+});+function dispose(mesh){mesh.geometry?.dispose();if(Array.isArray(mesh.material))mesh.material.forEach(m=>m.dispose());else mesh.material?.dispose();scene.remove(mesh);}+function lighting(value=project.light){+ const t=value*2*Math.PI,day=Math.max(.05,Math.sin(t)),span=Math.max(...project.size);scene.background=new THREE.Color().lerpColors(new THREE.Color('#182732'),new THREE.Color('#dbe1d2'),day);scene.fog=new THREE.Fog(scene.background,span*2,span*6);+ sun.position.set(project.size[0]/2+Math.cos(t)*span,Math.max(10,Math.sin(t)*span),project.size[2]*1.5);sun.target.position.set(project.size[0]/2,0,project.size[2]/2);sun.intensity=.25+day*2.7;ambient.intensity=.55+day*1.5;+ sun.shadow.camera.left=-span;sun.shadow.camera.right=span;sun.shadow.camera.top=span;sun.shadow.camera.bottom=-span;sun.shadow.camera.far=span*5;sun.shadow.camera.updateProjectionMatrix();+}+function renderWorld(geometry){+ for(const m of meshes)dispose(m);meshes=[];+ for(const light of glowLights)scene.remove(light);glowLights.length=0;+ for(const g of geometry){const geo=new THREE.BufferGeometry();geo.setAttribute('position',new THREE.Float32BufferAttribute(g.positions,3));geo.setAttribute('normal',new THREE.Float32BufferAttribute(g.normals,3));geo.setIndex(g.indices);geo.computeBoundingSphere();const m=project.materials.find(m=>m.id===g.material),mat=new THREE.MeshStandardMaterial({color:m.color,roughness:.86,metalness:0,transparent:m.opacity<1,opacity:m.opacity,depthWrite:m.opacity===1,emissive:m.color,emissiveIntensity:m.emission*.55});const mesh=new THREE.Mesh(geo,mat);mesh.castShadow=m.opacity===1;mesh.receiveShadow=true;mesh.userData={id:project.objects[g.object].id,material:g.material};meshes.push(mesh);scene.add(mesh);}+ for(const mesh of meshes){const material=project.materials.find(m=>m.id===mesh.userData.material);if(material.emission>0&&glowLights.length<12){mesh.geometry.computeBoundingBox();const light=new THREE.PointLight(material.color,material.emission*45,18,2);mesh.geometry.boundingBox.getCenter(light.position);glowLights.push(light);scene.add(light);}}+ if(grid)dispose(grid);const span=Math.max(project.size[0],project.size[2]);grid=new THREE.GridHelper(span,Math.ceil(span/4),'#879685','#b3bcab');grid.position.set(project.size[0]/2,-.03,project.size[2]/2);grid.material.transparent=true;grid.material.opacity=.4;scene.add(grid);+ if(ground)dispose(ground);ground=new THREE.Mesh(new THREE.PlaneGeometry(span*12,span*12),new THREE.MeshStandardMaterial({color:'#c4ccbb',roughness:1}));ground.rotation.x=-Math.PI/2;ground.position.set(project.size[0]/2,-.07,project.size[2]/2);ground.receiveShadow=true;scene.add(ground);+ lighting();syncSelection();$('scene-measures').textContent=`${world.count.toLocaleString()} voxels · ${project.size.map(n=>(n*project.unit).toFixed(1)).join(' × ')} m`;+}+function rebuild(){world=compileWorld(project);renderWorld(meshWorld(project,world));renderUI();if(walking&&visitor&&!fitsVisitor(world,visitor.position)){setWalking(false);report('The world changed around the visitor. Review it before walking again.');}}+function frame(bounds){const box=bounds??new THREE.Box3(new THREE.Vector3(0,0,0),new THREE.Vector3(project.size[0],Math.max(...project.objects.filter(o=>!o.hidden).map(o=>o.origin[1]+rotatedSize(o)[1]),2),project.size[2]));const center=box.getCenter(new THREE.Vector3()),size=box.getSize(new THREE.Vector3()),distance=Math.max(...size.toArray())*1.35;if(!bounds)center.y*=.55;orbit.target.copy(center);camera.position.copy(center).add(new THREE.Vector3(distance*.8,distance*.65,distance*.95));camera.lookAt(center);orbit.update();}+function setSelected(id){selected=id;syncSelection();renderUI();}+function setTool(value){tool=value;document.querySelectorAll('[data-tool]').forEach(b=>b.classList.toggle('active',b.dataset.tool===tool));orbit.mouseButtons.LEFT=tool==='select'?THREE.MOUSE.ROTATE:-1;orbit.mouseButtons.RIGHT=THREE.MOUSE.ROTATE;syncSelection();hitBox.visible=false;$('interaction-hint').textContent=tool==='select'?'Drag to orbit · click to select · arrows move objects':'Click to sculpt selected object · right-drag to orbit';}+function renderUI(){+ $('world-title').textContent=project.title;document.title=project.title+' — Tidelands';$('brief-text').textContent=project.brief;$('object-count').textContent=project.objects.length+' objects';$('light').value=project.light;+ const query=$('object-search').value.toLowerCase();$('object-list').innerHTML=project.objects.filter(o=>o.name.toLowerCase().includes(query)).map(o=>`<div class="object-row ${o.id===selected?'selected':''} ${o.hidden?'hidden-object':''}"><button data-object="${o.id}" title="${esc(o.name)}"><span class="dot"></span>${esc(o.name)}</button><button class="toggle" data-visible="${o.id}" title="${o.hidden?'Show':'Hide'} ${esc(o.name)}">${o.hidden?'○':'●'}</button><button class="toggle" data-lock="${o.id}" title="${o.locked?'Unlock':'Lock'} ${esc(o.name)}">${o.locked?'▣':'□'}</button></div>`).join('');+ const o=selectedObject();$('object-editor').innerHTML=o?`<label>Name<input id="object-name" value="${esc(o.name)}" ${o.locked?'disabled':''}></label><label>Position · voxels<div class="xyz">${['X','Y','Z'].map((axis,i)=>`<label>${axis}<input data-position="${i}" type="number" step="1" min="0" value="${o.origin[i]}" ${o.locked?'disabled':''}></label>`).join('')}</div></label><div class="fine">${rotatedSize(o).map(n=>(n*project.unit).toFixed(1)).join(' × ')} m · ${o.locked?'locked':'editable'}</div><div class="actions"><button id="rotate-object" ${o.locked?'disabled':''}>Rotate 90°</button><button id="duplicate-object">Duplicate</button><button id="delete-object" ${o.locked||project.objects.length===1?'disabled':''}>Delete</button></div><div class="actions"><button id="asset-glb">Asset .glb ↗</button><button id="asset-vox">Asset .vox ↗</button></div>`:'Choose an object to edit its geometry.';+ $('palette').innerHTML=project.materials.map(m=>`<button data-material="${m.id}" title="${esc(m.name)}" aria-label="${esc(m.name)}" style="background:${m.color}" class="${m.id===material?'active':''}"></button>`).join('');+ const m=project.materials.find(m=>m.id===material)??project.materials[0];material=m.id;$('material-editor').innerHTML=`<div class="color-row"><input id="material-color" aria-label="Material color" type="color" value="${m.color}"><input id="material-name" aria-label="Material name" value="${esc(m.name)}"></div><label class="check"><input id="material-solid" type="checkbox" ${m.solid?'checked':''}> Blocks walking</label><label>Opacity<input id="material-opacity" type="range" min=".05" max="1" step=".01" value="${m.opacity}"></label><label>Glow<input id="material-glow" type="range" min="0" max="1" step=".05" value="${m.emission}"></label>`;+ $('tour-stops').innerHTML=project.stops.map(s=>`<button data-stop="${s.id}" title="${esc(s.description)}">${esc(s.name)} ↗</button>`).join('');state();+}+$('object-list').onclick=guard(event=>{const b=event.target.closest('button');if(!b)return;if(b.dataset.object)setSelected(b.dataset.object);if(b.dataset.visible)mutate(p=>{const o=p.objects.find(o=>o.id===b.dataset.visible);o.hidden=!o.hidden;},'Object visibility changed');if(b.dataset.lock)mutate(p=>{const o=p.objects.find(o=>o.id===b.dataset.lock);o.locked=!o.locked;},'Object lock changed');});+$('object-search').oninput=renderUI;+$('object-editor').onchange=guard(event=>{const id=event.target.id;if(id==='object-name')mutate(p=>{p.objects.find(o=>o.id===selected).name=event.target.value;});if(event.target.dataset.position)mutate(p=>{p.objects.find(o=>o.id===selected).origin[Number(event.target.dataset.position)]=Number(event.target.value);},'Object moved');});+$('object-editor').onclick=guard(event=>{const id=event.target.closest('button')?.id,o=selectedObject();if(!o)return;+ if(id==='rotate-object')mutate(p=>{p.objects.find(o=>o.id===selected).rotation=(o.rotation+1)%4;},'Object rotated');+ if(id==='duplicate-object'){const newid=unique(o.id);mutate(p=>{const copy=clone(o);copy.id=newid;copy.name+=' copy';copy.locked=false;copy.origin=copy.origin.map((n,i)=>i===0?Math.min(project.size[0]-rotatedSize(copy)[0],n+2):n);p.objects.push(copy);},'Object duplicated');setSelected(newid);}+ if(id==='delete-object'){mutate(p=>{p.objects=p.objects.filter(o=>o.id!==selected);},'Object removed');setSelected(project.objects[0].id);}+ if(id==='asset-glb')download(o.id+'.glb',exportGLB(project,{objectId:o.id}),'model/gltf-binary');if(id==='asset-vox')download(o.id+'.vox',exportVOX(project,{objectId:o.id}));+});+function unique(prefix){let id=prefix,n=2;while(project.objects.some(o=>o.id===id))id=prefix.slice(0,56)+'-'+n++;return id;}+$('new-object').onclick=guard(()=>{const id=unique('object');mutate(p=>p.objects.push({id,name:'New voxel object',origin:[Math.floor(p.size[0]/2),Math.min(p.size[1]-1,Math.floor(project.spawn.position[1])),Math.floor(p.size[2]/2)],size:[1,1,1],boxes:[[0,0,0,1,1,1,material]],edits:[],rotation:0,hidden:false,locked:false}),'New object added');setSelected(id);setTool('add');});+$('palette').onclick=event=>{const b=event.target.closest('[data-material]');if(b){material=Number(b.dataset.material);renderUI();}};+$('material-editor').onchange=guard(event=>{const map={'material-name':['name',event.target.value],'material-color':['color',event.target.value],'material-solid':['solid',event.target.checked],'material-opacity':['opacity',Number(event.target.value)],'material-glow':['emission',Number(event.target.value)]};const entry=map[event.target.id];if(entry)mutate(p=>{p.materials.find(m=>m.id===material)[entry[0]]=entry[1];},'Material updated across the world');});+$('new-material').onclick=guard(()=>{const id=Array.from({length:255},(_,i)=>i+1).find(id=>!project.materials.some(m=>m.id===id));if(!id)throw new Error('The palette already has 255 materials.');mutate(p=>p.materials.push({id,name:'New material',color:'#c58b65',solid:true,opacity:1,emission:0}));material=id;renderUI();});+document.querySelectorAll('[data-tool]').forEach(b=>b.onclick=()=>setTool(b.dataset.tool));$('undo').onclick=()=>history(past,future);$('redo').onclick=()=>history(future,past);+$('light').oninput=event=>lighting(Number(event.target.value));$('light').onchange=guard(event=>mutate(p=>{p.light=Number(event.target.value);},'Light saved'));$('cycle-light').onchange=()=>{cycle=project.light;};+$('frame-world').onclick=()=>{if(walking)setWalking(false);frame();};$('focus-object').onclick=()=>{if(selectedObject())frame(selectionBox.box);};+const raycaster=new THREE.Raycaster(),pointer=new THREE.Vector2();let down=null,lookDrag=null;+function hit(event){const rect=renderer.domElement.getBoundingClientRect();pointer.set((event.clientX-rect.left)/rect.width*2-1,-((event.clientY-rect.top)/rect.height)*2+1);raycaster.setFromCamera(pointer,camera);return raycaster.intersectObjects(meshes,false)[0];}+function voxelPosition(h,add){const point=h.point.clone().addScaledVector(h.face.normal,add?.001:-.001);return point.toArray().map(Math.floor);}+renderer.domElement.addEventListener('pointerdown',event=>{viewport.focus();down={x:event.clientX,y:event.clientY,button:event.button};if(walking&&!document.pointerLockElement){lookDrag={x:event.clientX,y:event.clientY};renderer.domElement.setPointerCapture(event.pointerId);}});+renderer.domElement.addEventListener('pointermove',event=>{+ if(walking){if(document.pointerLockElement||lookDrag){const dx=document.pointerLockElement?event.movementX:event.clientX-lookDrag.x,dy=document.pointerLockElement?event.movementY:event.clientY-lookDrag.y;visitor.yaw-=dx*.003;pitch=Math.max(-1.45,Math.min(1.45,pitch-dy*.003));if(lookDrag)lookDrag={x:event.clientX,y:event.clientY};}return;}+ if(tool==='select'||transformDragging){hitBox.visible=false;return;}const h=hit(event);hitBox.visible=Boolean(h);if(h)hitBox.position.set(...voxelPosition(h,tool==='add').map(n=>n+.5));+});+renderer.domElement.addEventListener('pointerup',guard(event=>{lookDrag=null;if(walking||transformDragging||!down||down.button!==0||Math.hypot(event.clientX-down.x,event.clientY-down.y)>4)return;const h=hit(event);if(!h)return;if(tool==='select'){setSelected(h.object.userData.id);return;}const at=voxelPosition(h,tool==='add');if(at.some((n,i)=>n<0||n>=project.size[i]))throw new Error('The brush is outside the world. Enlarge the project to build here.');+ if(tool!=='add'&&h.object.userData.id!==selected)throw new Error('Select that object before changing its voxels.');+ mutate(p=>paintCells(p,selected,at,tool==='erase'?0:material,Number($('brush-radius').value),{existingOnly:tool==='paint'}),tool==='erase'?'Voxels removed':tool==='paint'?'Voxels painted':'Voxels added');+}));+renderer.domElement.addEventListener('contextmenu',e=>e.preventDefault());+function resetVisitor(position=project.spawn.position){if(!fitsVisitor(world,position))throw new Error('This destination has insufficient room for a 1.7 m visitor. Check the walking routes.');visitor={position:[...position],yaw:project.spawn.yaw,velocity:0,grounded:true};pitch=0;}+function setWalking(value){if(value){resetVisitor();}else{document.exitPointerLock?.();}walking=value;document.body.classList.toggle('walking',walking);$('interaction-hint').textContent=value?'WASD · drag to look · Space to jump':'Drag to orbit · click to select';$('walk-overlay').hidden=!value;$('crosshair').hidden=!value;$('touch-walk').hidden=!value||!matchMedia('(pointer:coarse)').matches;$('edit-tools').hidden=value||readonly;$('walk-mode').classList.toggle('active',value);$('edit-mode').classList.toggle('active',!value);orbit.enabled=!value;keys.clear();syncSelection();if(!value)frame();resize();}+$('walk-mode').onclick=guard(()=>setWalking(true));$('edit-mode').onclick=()=>setWalking(false);$('enter-walk').onclick=guard(async()=>{try{await renderer.domElement.requestPointerLock();}catch{report('Drag the view to look around; keyboard and touch walking remain available.');}viewport.focus();});+$('tour-stops').onclick=guard(event=>{const stop=project.stops.find(s=>s.id===event.target.dataset.stop);if(stop){resetVisitor(stop.position);report(stop.name+' · '+stop.description);}});+document.addEventListener('pointerlockchange',()=>{$('enter-walk').hidden=Boolean(document.pointerLockElement);});+window.addEventListener('keydown',guard(event=>{if(event.target.matches('input,textarea,select'))return;if((event.metaKey||event.ctrlKey)&&event.key.toLowerCase()==='z'){event.preventDefault();history(event.shiftKey?future:past,event.shiftKey?past:future);return;}if(walking&&['KeyW','KeyA','KeyS','KeyD','Space','ShiftLeft','ArrowUp','ArrowDown','ArrowLeft','ArrowRight'].includes(event.code)){event.preventDefault();keys.add(event.code);}else if(!walking&&!readonly&&event.code.startsWith('Arrow')&&selectedObject()&&!selectedObject().locked){event.preventDefault();const axis=event.code==='ArrowLeft'||event.code==='ArrowRight'?0:2,delta=event.code==='ArrowLeft'||event.code==='ArrowUp'?-1:1;mutate(p=>{p.objects.find(o=>o.id===selected).origin[axis]+=delta;},'Object nudged');}}));+window.addEventListener('keyup',event=>keys.delete(event.code));window.addEventListener('blur',()=>keys.clear());+const touchKeys={forward:'KeyW',back:'KeyS',left:'KeyA',right:'KeyD',jump:'Space'};document.querySelectorAll('[data-move]').forEach(b=>{b.onpointerdown=e=>{e.preventDefault();b.setPointerCapture(e.pointerId);keys.add(touchKeys[b.dataset.move]);};b.onpointerup=b.onpointercancel=()=>keys.delete(touchKeys[b.dataset.move]);});+let last=performance.now(),accumulator=0;+function animate(now){requestAnimationFrame(animate);const dt=Math.min(.06,(now-last)/1000);last=now;if(walking&&visitor){accumulator+=dt;while(accumulator>=1/120){visitor=moveVisitor(world,visitor,{forward:(keys.has('KeyW')||keys.has('ArrowUp')?1:0)-(keys.has('KeyS')||keys.has('ArrowDown')?1:0),right:(keys.has('KeyD')||keys.has('ArrowRight')?1:0)-(keys.has('KeyA')||keys.has('ArrowLeft')?1:0),sprint:keys.has('ShiftLeft'),jump:keys.has('Space')},1/120);keys.delete('Space');accumulator-=1/120;}camera.position.set(visitor.position[0],visitor.position[1]+1.58/project.unit,visitor.position[2]);camera.lookAt(camera.position.clone().add(new THREE.Vector3(Math.sin(visitor.yaw)*Math.cos(pitch),Math.sin(pitch),Math.cos(visitor.yaw)*Math.cos(pitch))));}else orbit.update();if($('cycle-light').checked){cycle=(cycle+dt/120)%1;lighting(cycle);}renderer.render(scene,camera);}+function resize(){const {width,height}=viewport.getBoundingClientRect();if(!width||!height)return;camera.aspect=width/height;camera.updateProjectionMatrix();renderer.setSize(width,height,false);}new ResizeObserver(resize).observe(viewport);+$('edit-project').onclick=()=>{$('project-title').value=project.title;$('project-brief').value=project.brief;$('project-notes').value=project.notes;$('project-unit').value=project.unit;['x','y','z'].forEach((c,i)=>$('size-'+c).value=project.size[i]);$('project-dialog').showModal();};+$('apply-project').onclick=guard(()=>{mutate(p=>{p.title=$('project-title').value;p.brief=$('project-brief').value;p.notes=$('project-notes').value;p.unit=Number($('project-unit').value);p.size=['x','y','z'].map(c=>Number($('size-'+c).value));},'Project settings saved');$('project-dialog').close();});+function portable(mode='edit'){const payload=JSON.stringify({project,mode}).replace(/</g,'\\u003c');return originalHTML.replace(/(<script id="world-data" type="application\/json">)[\s\S]*?(<\/script>)/,(_,a,b)=>a+payload+b);}+const readme=()=>`# ${project.title}\n\n${project.brief}\n\nOpen studio.html to edit or walkthrough.html to explore, including offline. Import the .glb into a glTF-capable 3D tool. GLB is Y-up in meters; named objects become meshes. The .vox file is one flattened MagicaVoxel model with a palette, with its Z axis vertical. Keep ${project.id}.tidelands.json: it preserves source objects, rotations, locks, materials, scale, spawn and destinations. Browser undo history is temporary.\n\nOne voxel = ${project.unit} meters. The visitor is 1.7 m tall and 0.52 m wide. Route checks are finite geometry checks, not a substitute for walking the result. No game rules, networking or physical construction certification are included.\n\n${project.notes}\n`;+$('save-project').onclick=()=>download(project.id+'.tidelands.json',JSON.stringify(project,null,2),'application/json');+$('deliver').onclick=()=>{$('export-summary').textContent=project.title+' · '+world.count.toLocaleString()+' voxels · '+project.objects.filter(o=>!o.hidden).length+' visible objects';$('export-dialog').showModal();};$('close-export').onclick=()=>$('export-dialog').close();+$('export-glb').onclick=guard(()=>download(project.id+'.glb',exportGLB(project),'model/gltf-binary'));$('export-vox').onclick=guard(()=>download(project.id+'.vox',exportVOX(project)));$('export-walk').onclick=()=>download(project.id+'-walkthrough.html',portable('walk'),'text/html');+$('export-kit').onclick=guard(async()=>{report('Preparing your editable world kit…');await new Promise(r=>setTimeout(r,30));const files=[[project.id+'.tidelands.json',JSON.stringify(project,null,2)],[project.id+'.glb',exportGLB(project)],[project.id+'.vox',exportVOX(project)],['studio.html',portable()],['walkthrough.html',portable('walk')],['README.md',readme()],['walking-check.json',JSON.stringify(navigationReport(project),null,2)]];download(project.id+'-world-kit.zip',zipFiles(files));report('World kit exported: source, GLB, VOX, editable studio and walkthrough');});+$('snapshot').onclick=()=>{renderer.render(scene,camera);renderer.domElement.toBlob(blob=>{if(blob)download(project.id+'-'+stamp()+'.png',blob);});};+$('check-routes').onclick=guard(()=>{const result=navigationReport(project);report(result.issues.length?result.issues.join(' '):`${result.reachableStandingCells.toLocaleString()} connected standing positions; all ${result.stops.length} destinations reached by the geometry check. Walk the result to verify it.`);download(project.id+'-walking-check.json',JSON.stringify(result,null,2),'application/json');});+function openProject(next,message){const valid=validateProject(next);meshWorld(valid);project=valid;selected=project.objects.find(o=>!o.locked)?.id??project.objects[0].id;past.length=0;future.length=0;dirty=true;rebuild();if(walking)setWalking(false);frame();saveDraft();report(message);}+$('open-project').onclick=guard(async()=>{$('native-open').hidden=!connected;$('open-dialog').showModal();if(connected){const response=await fetch('/api/files'),data=await response.json();$('recent-projects').replaceChildren();for(const file of data.files??[]){const button=document.createElement('button');button.className='wide';button.textContent=file.name;button.title=file.folder;button.onclick=guard(()=>openPath(file.path));$('recent-projects').append(button);}if(!data.files?.length)$('recent-projects').textContent='No saved worlds in Downloads, Desktop or Documents yet.';}});+$('choose-project').onclick=()=>$('project-file').click();$('close-open').onclick=()=>$('open-dialog').close();+async function openPath(path){const response=await fetch('/api/open',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({path})}),data=await response.json();if(!response.ok)throw new Error(data.error||'Could not open the project.');openProject(data.project,'Project opened as a draft. Save to keep it in this workspace.');$('open-dialog').close();}+$('open-path').onclick=guard(()=>openPath($('project-path').value));+$('project-file').onchange=guard(async event=>{const f=event.target.files[0];event.target.value='';if(!f)return;if(f.size>12000000)throw new Error('Choose a project smaller than 12 MB.');openProject(JSON.parse(await f.text()),'Project opened as a draft. Save to keep it in this workspace.');$('open-dialog').close();});+$('import-vox').onclick=()=>$('vox-file').click();$('vox-file').onchange=guard(async event=>{const f=event.target.files[0];event.target.value='';if(!f)return;if(f.size>24000000)throw new Error('Choose a VOX file smaller than 24 MB.');const asset=importVOX(await f.arrayBuffer()),origin=[0,Math.floor(project.spawn.position[1]),0],result=addImportedAsset(project,asset,{name:f.name.replace(/\.vox$/i,''),origin});mutate(p=>Object.assign(p,result.project),'Supplied voxel asset imported');setSelected(result.id);});+function sourceNotice(next,message){sourcePending=next;$('source-notice').hidden=false;$('source-notice').querySelector('span').textContent=message;state();}+$('draft-keep').onclick=()=>download(project.id+'-draft-'+stamp()+'.tidelands.json',JSON.stringify(project,null,2),'application/json');+$('source-load').onclick=guard(()=>{if(!sourcePending)return;download(project.id+'-before-restore-'+stamp()+'.tidelands.json',JSON.stringify(project,null,2),'application/json');const next=sourcePending;sourcePending=null;openProject(next,'Prior draft downloaded; source version restored');revision=next.revision;dirty=false;$('source-notice').hidden=true;state();});+$('save-source').onclick=guard(async()=>{if(!connected||sourcePending)return;saving=true;pollEpoch++;state();try{const response=await fetch('/api/project',{method:'PUT',headers:{'content-type':'application/json','if-match':revision},body:JSON.stringify(project)}),result=await response.json();if(response.status===409){sourceNotice(result.project,'The source changed while you were editing. Download your draft before choosing the source.');return;}if(!response.ok)throw new Error(result.error||'Save failed');project=validateProject(result.project);revision=project.revision;dirty=false;try{localStorage.removeItem(draftKey);}catch{}report('Saved to workspace; the previous source is retained in history.');}finally{saving=false;state();}});+async function poll(){if(location.protocol==='file:'||readonly||saving)return;const epoch=++pollEpoch;try{const response=await fetch('/api/project');if(!response.ok)return;const result=await response.json();if(epoch!==pollEpoch||saving||!result.project)return;connected=true;const next=validateProject(result.project);if(next.revision!==revision){if(dirty)sourceNotice(next,'Your agent changed the source. Keep your draft before switching versions.');else{project=next;revision=next.revision;rebuild();report('Agent changes loaded from the source project');}}state();}catch{}}+document.body.classList.toggle('readonly',readonly);rebuild();frame();resize();setTool('select');requestAnimationFrame(animate);+if(readonly){guard(()=>setWalking(true))();$('save-state').textContent='Offline walkthrough';}else{+ try{const draft=JSON.parse(localStorage.getItem(draftKey)||'null');if(draft?.project&&JSON.stringify(draft.project)!==JSON.stringify(project)){const source=project;openProject(draft.project,'Recovered your browser draft');sourceNotice(source,'A previous browser draft was recovered. You can keep it or return to the saved source.');}}catch{}+ poll();setInterval(poll,3000);+}+// The same live state used by the controls is exposed for finite browser acceptance checks.+window.tidelands={get project(){return clone(project);},get world(){return world;},get visitor(){return clone(visitor);},get selected(){return selected;},screenPoint(point){const q=new THREE.Vector3(...point).project(camera),r=renderer.domElement.getBoundingClientRect();return {x:r.x+(q.x+1)/2*r.width,y:r.y+(1-q.y)/2*r.height};},get connected(){return connected;},get dirty(){return dirty;},setSelected,exportGLB:()=>exportGLB(project),exportVOX:()=>exportVOX(project),portable,navigationReport:()=>navigationReport(project)};diff --git a/store/agents/voxel-worlds/template/studio/archive.mjs b/store/agents/voxel-worlds/template/studio/archive.mjsnew file mode 100644index 000000000..ff64bbf68--- /dev/null+++ b/store/agents/voxel-worlds/template/studio/archive.mjs@@ -0,0 +1,20 @@+// ZIP STORE: portable editable delivery without a runtime dependency or a cloud service.+export function zipFiles(files) {+ const enc = new TextEncoder(), chunks = [], central = []; let offset = 0;+ for (const [name, body] of files) {+ const path = enc.encode(name), bytes = typeof body === 'string' ? enc.encode(body) : new Uint8Array(body);+ let crc = 0xffffffff;+ for (const b of bytes) { crc ^= b; for (let i = 0; i < 8; i++) crc = (crc >>> 1) ^ (0xedb88320 & -(crc & 1)); }+ crc = (crc ^ 0xffffffff) >>> 0;+ const header = new Uint8Array(30 + path.length), v = new DataView(header.buffer);+ v.setUint32(0, 0x04034b50, true); v.setUint16(4, 20, true); v.setUint16(6, 0x800, true); v.setUint16(12, 33, true);+ v.setUint32(14, crc, true); v.setUint32(18, bytes.length, true); v.setUint32(22, bytes.length, true); v.setUint16(26, path.length, true); header.set(path, 30);+ const row = new Uint8Array(46 + path.length), c = new DataView(row.buffer);+ c.setUint32(0, 0x02014b50, true); c.setUint16(4, 20, true); c.setUint16(6, 20, true); c.setUint16(8, 0x800, true); c.setUint16(14, 33, true);+ c.setUint32(16, crc, true); c.setUint32(20, bytes.length, true); c.setUint32(24, bytes.length, true); c.setUint16(28, path.length, true); c.setUint32(42, offset, true); row.set(path, 46);+ chunks.push(header, bytes); central.push(row); offset += header.length + bytes.length;+ }+ const length = central.reduce((n, row) => n + row.length, 0), end = new Uint8Array(22), e = new DataView(end.buffer);+ e.setUint32(0, 0x06054b50, true); e.setUint16(8, files.length, true); e.setUint16(10, files.length, true); e.setUint32(12, length, true); e.setUint32(16, offset, true);+ return new Blob([...chunks, ...central, end], { type: 'application/zip' });+}diff --git a/store/agents/voxel-worlds/template/studio/formats.mjs b/store/agents/voxel-worlds/template/studio/formats.mjsnew file mode 100644index 000000000..214234992--- /dev/null+++ b/store/agents/voxel-worlds/template/studio/formats.mjs@@ -0,0 +1,95 @@+import {validateProject,compileWorld,meshWorld,boxesFromCells,clone} from './project.mjs';+const text=new TextEncoder(),decode=new TextDecoder();+const concat=arrays=>{const out=new Uint8Array(arrays.reduce((n,a)=>n+a.length,0));let offset=0;for(const a of arrays){out.set(a,offset);offset+=a.length;}return out;};+const pad=(array,value=0)=>{const out=new Uint8Array(Math.ceil(array.length/4)*4);out.fill(value);out.set(array);return out;};+const linear=n=>n<=.04045?n/12.92:((n+.055)/1.055)**2.4;+export function selectAsset(project,id){+ const p=clone(project),o=p.objects.find(o=>o.id===id);if(!o)throw new Error('Choose an object to export.');+ const origin=[...o.origin];o.origin=[0,0,0];o.hidden=false;p.objects=[o];p.size=o.rotation%2?[o.size[2],o.size[1],o.size[0]]:[...o.size];+ p.title=o.name;p.id=o.id;p.stops=[];p.spawn={position:[0,0,0],yaw:0};return {project:p,origin};+}+// glTF 2.0 binary: editable named meshes, Y up, meters, explicit sRGB-to-linear materials.+export function exportGLB(project,{objectId}={}){+ let p=validateProject(project);if(objectId)p=selectAsset(p,objectId).project;+ const parts=[],views=[],accessors=[],nodes=[],meshes=[],materials=p.materials.map(m=>{+ const rgb=[1,3,5].map(i=>linear(parseInt(m.color.slice(i,i+2),16)/255));+ return {name:m.name,pbrMetallicRoughness:{baseColorFactor:[...rgb,m.opacity],metallicFactor:0,roughnessFactor:.9},...(m.opacity<1?{alphaMode:'BLEND',doubleSided:true}:{}),...(m.emission?{emissiveFactor:rgb.map(n=>n*m.emission)}:{}),extras:{voxelMaterialId:m.id,solid:m.solid}};+ });let byteOffset=0;+ function accessor(array,type,componentType,target,min,max){const bytes=pad(new Uint8Array(array.buffer));views.push({buffer:0,byteOffset,byteLength:array.byteLength,target});parts.push(bytes);byteOffset+=bytes.length;accessors.push({bufferView:views.length-1,componentType,count:array.length/(type==='VEC3'?3:1),type,...(min?{min,max}:{})});return accessors.length-1;}+ const byObject=new Map();+ for(const group of meshWorld(p)){+ const o=p.objects[group.object],positions=new Float32Array(group.positions.map((v,i)=>(v-o.origin[i%3])*p.unit)),min=[Infinity,Infinity,Infinity],max=[-Infinity,-Infinity,-Infinity];+ for(let i=0;i<positions.length;i++){min[i%3]=Math.min(min[i%3],positions[i]);max[i%3]=Math.max(max[i%3],positions[i]);}+ const primitive={attributes:{POSITION:accessor(positions,'VEC3',5126,34962,min,max),NORMAL:accessor(new Float32Array(group.normals),'VEC3',5126,34962)},indices:accessor(new Uint32Array(group.indices),'SCALAR',5125,34963),material:p.materials.findIndex(m=>m.id===group.material)};+ if(!byObject.has(group.object))byObject.set(group.object,[]);byObject.get(group.object).push(primitive);+ }+ if(!byObject.size)throw new Error('There is no visible geometry to export.');+ for(const [index,primitives]of byObject){const o=p.objects[index];meshes.push({name:o.name,primitives});nodes.push({name:o.name,mesh:meshes.length-1,translation:o.origin.map(n=>n*p.unit),extras:{objectId:o.id,locked:o.locked}});}+ const bin=concat(parts),json=pad(text.encode(JSON.stringify({asset:{version:'2.0',generator:'Tidelands / Voxel Worlds'},scene:0,scenes:[{name:p.title,nodes:nodes.map((_,i)=>i)}],nodes,meshes,materials,buffers:[{byteLength:bin.length}],bufferViews:views,accessors,extras:{brief:p.brief,voxelSizeMeters:p.unit}})),32),header=new Uint8Array(20),v=new DataView(header.buffer),binHeader=new Uint8Array(8),b=new DataView(binHeader.buffer);+ v.setUint32(0,0x46546c67,true);v.setUint32(4,2,true);v.setUint32(8,28+json.length+bin.length,true);v.setUint32(12,json.length,true);v.setUint32(16,0x4e4f534a,true);b.setUint32(0,bin.length,true);b.setUint32(4,0x004e4942,true);+ return concat([header,json,binHeader,bin]);+}+function chunk(name,body,children=new Uint8Array()) {const h=new Uint8Array(12),v=new DataView(h.buffer);h.set(text.encode(name));v.setUint32(4,body.length,true);v.setUint32(8,children.length,true);return concat([h,body,children]);}+// MagicaVoxel's vertical axis is Z. Reflect depth while exchanging Y/Z to preserve handedness.+export function exportVOX(project,{objectId}={}){+ let p=validateProject(project);if(objectId)p=selectAsset(p,objectId).project;+ const world=compileWorld(p),[w,h,d]=world.size,size=new Uint8Array(12),s=new DataView(size.buffer),xyzi=new Uint8Array(4+world.count*4),v=new DataView(xyzi.buffer),palette=new Uint8Array(1024);+ s.setUint32(0,w,true);s.setUint32(4,d,true);s.setUint32(8,h,true);v.setUint32(0,world.count,true);let offset=4;+ for(let y=0;y<h;y++)for(let z=0;z<d;z++)for(let x=0;x<w;x++){const id=world.cells[(y*d+z)*w+x];if(id){xyzi.set([x,d-1-z,y,id],offset);offset+=4;}}+ for(const m of p.materials){palette.set([...([1,3,5].map(i=>parseInt(m.color.slice(i,i+2),16))),Math.round(m.opacity*255)],(m.id-1)*4);}+ const header=new Uint8Array(8);header.set(text.encode('VOX '));new DataView(header.buffer).setUint32(4,150,true);+ return concat([header,chunk('MAIN',new Uint8Array(),concat([chunk('SIZE',size),chunk('XYZI',xyzi),chunk('RGBA',palette)]))]);+}+export function importVOX(input){+ const bytes=new Uint8Array(input);if(bytes.length<20||bytes.length>24000000)throw new Error('Choose a .vox file smaller than 24 MB.');+ const v=new DataView(bytes.buffer,bytes.byteOffset,bytes.byteLength),name=(i,n=4)=>decode.decode(bytes.slice(i,i+n));+ if(name(0)!=='VOX '||![150,200].includes(v.getUint32(4,true))||name(8)!=='MAIN')throw new Error('Not a supported MagicaVoxel file.');+ let size,voxels,palette,modelCount=0,offset=20+v.getUint32(12,true),end=offset+v.getUint32(16,true);const nodes=new Map(),hiddenLayers=new Set();+ if(end!==bytes.length)throw new Error('Truncated or trailing VOX data.');+ while(offset<end){if(offset+12>end)throw new Error('Truncated VOX chunk.');const id=name(offset),length=v.getUint32(offset+4,true),children=v.getUint32(offset+8,true),start=offset+12,next=start+length+children;if(next>end)throw new Error('Truncated VOX chunk.');+ if(id==='SIZE'){if(length!==12)throw new Error('Invalid VOX size.');size=[0,4,8].map(n=>v.getUint32(start+n,true));modelCount++;}+ if(id==='XYZI'){if(length<4||v.getUint32(start,true)*4+4!==length||voxels)throw new Error('Use one flattened voxel model.');voxels=bytes.slice(start+4,start+length);}+ if(id==='RGBA'){if(length!==1024)throw new Error('Invalid VOX palette.');palette=bytes.slice(start,start+length);}+ if(['nTRN','nGRP','nSHP','LAYR'].includes(id)){+ let cursor=start;const integer=()=>{if(cursor+4>start+length)throw new Error('Truncated scene transforms.');const n=v.getInt32(cursor,true);cursor+=4;return n;};+ const string=()=>{const n=integer();if(n<0||n>10000||cursor+n>start+length)throw new Error('Invalid VOX scene string.');const s=name(cursor,n);cursor+=n;return s;};+ const dict=()=>{const n=integer();if(n<0||n>64)throw new Error('Invalid VOX scene attributes.');const result=Object.create(null);for(let i=0;i<n;i++)result[string()]=string();return result;};+ const nodeId=integer(),attrs=dict();if(nodeId<0||nodes.size>128)throw new Error('Invalid VOX scene node.');+ if(id==='LAYR'){if(attrs._hidden==='1')hiddenLayers.add(nodeId);integer();}+ else{+ if(nodes.has(nodeId))throw new Error('Duplicate VOX scene node.');const node={id,attrs};+ if(id==='nTRN'){node.child=integer();if(integer()!==-1)throw new Error('Invalid VOX transform.');node.layer=integer();if(integer()!==1)throw new Error('Import a static VOX asset; animated transforms are not supported.');node.frame=dict();}+ if(id==='nGRP'){if(integer()!==1)throw new Error('Import one model instance at a time.');node.child=integer();}+ if(id==='nSHP'){if(integer()!==1||integer()!==0)throw new Error('Import one static voxel model.');dict();}+ nodes.set(nodeId,node);+ }+ if(cursor!==start+length)throw new Error('Unexpected VOX scene data.');+ }+ offset=next;+ }+ if(modelCount!==1||!size||!voxels)throw new Error('Import a single flattened voxel model. Multiple models are not supported.');+ if(!palette)throw new Error('Export the model with its RGBA palette before importing. Default-palette files are not supported.');+ if(size.some(n=>n<1||n>128)||size.reduce((a,b)=>a*b,1)>1048576)throw new Error('Use a model up to 128 cells per axis and one million cells.');+ const transforms=[];+ if(nodes.size){+ const children=new Set([...nodes.values()].map(n=>n.child).filter(n=>n!==undefined)),roots=[...nodes.keys()].filter(n=>!children.has(n));if(roots.length!==1)throw new Error('Invalid or cyclic VOX scene.');let current=roots[0];const visited=new Set();+ while(current!==undefined){if(visited.has(current)||!nodes.has(current))throw new Error('Invalid or cyclic VOX scene.');visited.add(current);const node=nodes.get(current);if(node.attrs._hidden==='1'||hiddenLayers.has(node.layer))throw new Error('The imported asset is hidden in its scene.');+ if(node.id==='nTRN'){const r=Number(node.frame._r??4),a=r&3,b=(r>>2)&3,c=3-a-b;if(!Number.isInteger(r)||r<0||r>127||a>2||b>2||a===b||c<0||c>2)throw new Error('Invalid VOX rotation.');const translation=String(node.frame._t??'0 0 0').trim().split(/\s+/).map(Number);if(translation.length!==3||translation.some(n=>!Number.isInteger(n)||Math.abs(n)>1000000))throw new Error('Invalid VOX translation.');transforms.push({axes:[a,b,c],signs:[4,5,6].map(bit=>r&(1<<bit)?-1:1),translation});}+ current=node.child;+ }+ if(visited.size!==nodes.size||![...nodes.values()].some(n=>n.id==='nSHP'))throw new Error('Import one connected VOX model.');+ }+ const transform=point=>{let q=[...point];for(const t of [...transforms].reverse())q=t.axes.map((axis,i)=>q[axis]*t.signs[i]+t.translation[i]);return q;};+ const corners=[];for(const x of [0,size[0]-1])for(const y of [0,size[1]-1])for(const z of [0,size[2]-1])corners.push(transform([x,y,z]));+ const min=[0,1,2].map(i=>Math.min(...corners.map(p=>p[i]))),dimensions=[0,1,2].map(i=>Math.max(...corners.map(p=>p[i]))-min[i]+1);+ const shape=[dimensions[0],dimensions[2],dimensions[1]],cells=new Uint8Array(shape.reduce((a,b)=>a*b,1)),used=new Set();+ for(let i=0;i<voxels.length;i+=4){const point=[...voxels.slice(i,i+3)],id=voxels[i+3];if(point.some((n,i)=>n>=size[i])||!id)throw new Error('VOX cell outside its declared model.');const [x,z,y]=transform(point).map((n,i)=>n-min[i]),index=(y*shape[2]+shape[2]-1-z)*shape[0]+x;if(cells[index])throw new Error('Duplicate VOX cell.');cells[index]=id;used.add(id);}+ const materials=[...used].sort((a,b)=>a-b).map(id=>{const rgba=palette.slice((id-1)*4,id*4);if(rgba[3]<13)throw new Error('A used VOX material is fully transparent.');return {id,name:'Imported '+id,color:'#'+[...rgba.slice(0,3)].map(n=>n.toString(16).padStart(2,'0')).join(''),opacity:rgba[3]/255,solid:true,emission:0};});+ if(!materials.length)throw new Error('That model contains no voxels.');return {size:shape,cells,materials,boxes:boxesFromCells(cells,shape),source:{format:'vox',transforms,placement:'Oriented model rebased to its own bounds for placement in this world; VOX has no physical scale.'}};+}+export function addImportedAsset(project,asset,{name='Imported asset',origin=[0,0,0]}={}){+ const p=clone(project),mapping=new Map();+ for(const m of asset.materials){let existing=p.materials.find(x=>x.color.toLowerCase()===m.color.toLowerCase()&&Math.abs(x.opacity-m.opacity)<.001&&x.solid===m.solid);if(!existing){const used=new Set(p.materials.map(m=>m.id)),id=Array.from({length:255},(_,i)=>i+1).find(id=>!used.has(id));if(!id)throw new Error('The combined palette exceeds 255 colors.');existing={...m,id};p.materials.push(existing);}mapping.set(m.id,existing.id);}+ let id='imported',n=2;while(p.objects.some(o=>o.id===id))id='imported-'+n++;+ p.objects.push({id,name,size:asset.size,origin,rotation:0,hidden:false,locked:false,boxes:asset.boxes.map(b=>[...b.slice(0,6),mapping.get(b[6])]),edits:[],source:asset.source});return {project:validateProject(p),id};+}diff --git a/store/agents/voxel-worlds/template/studio/icon.svg b/store/agents/voxel-worlds/template/studio/icon.svgnew file mode 100644index 000000000..64b653d86--- /dev/null+++ b/store/agents/voxel-worlds/template/studio/icon.svg@@ -0,0 +1,14 @@+<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 96 96">+ <title>Voxel Worlds — stepped island</title>+ <rect x="4" y="4" width="88" height="88" rx="23" fill="#183e36"/>+ <path d="M20 58 48 74 76 58v10L48 84 20 68Z" fill="#619e9d"/>+ <path d="m20 42 14-8 14 8-14 8Z" fill="#d8e9a6"/>+ <path d="m20 42 14 8v20l-14-8Z" fill="#71936a"/>+ <path d="m34 50 14-8v20l-14 8Z" fill="#aac785"/>+ <path d="m48 42 14-8 14 8-14 8Z" fill="#d8e9a6"/>+ <path d="m48 42 14 8v20l-14-8Z" fill="#71936a"/>+ <path d="m62 50 14-8v20l-14 8Z" fill="#aac785"/>+ <path d="m34 24 14-8 14 8-14 8Z" fill="#f4efce"/>+ <path d="m34 24 14 8v30l-14-8Z" fill="#99b878"/>+ <path d="m48 32 14-8v30l-14 8Z" fill="#d8e9a6"/>+</svg>diff --git a/store/agents/voxel-worlds/template/studio/project.mjs b/store/agents/voxel-worlds/template/studio/project.mjsnew file mode 100644index 000000000..74cb49b41--- /dev/null+++ b/store/agents/voxel-worlds/template/studio/project.mjs@@ -0,0 +1,166 @@+// Editable, named voxel objects. Empty cells are zero; material IDs are 1–255.+export const SPEC = 'tidelands/2';+export const clone = value => structuredClone(value);+export const escapeHTML = value => String(value ?? '').replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));+const idPattern = /^[a-z][a-z0-9_-]{0,63}$/;+const finite = (v,lo,hi) => Number.isFinite(v) && v >= lo && v <= hi;+const ints = (a,n,lo,hi) => Array.isArray(a) && a.length === n && a.every(v => Number.isInteger(v) && finite(v,lo,hi));+const words = (v,n) => typeof v === 'string' && v.length <= n;+export function rotatedSize(object) { return object.rotation % 2 ? [object.size[2],object.size[1],object.size[0]] : [...object.size]; }+export function localToWorld(object,x,y,z) {+ const [w,,d] = object.size;+ const [a,c] = [[x,z],[d-1-z,x],[w-1-x,d-1-z],[z,w-1-x]][object.rotation];+ return [a+object.origin[0],y+object.origin[1],c+object.origin[2]];+}+export function worldToLocal(object,x,y,z) {+ x-=object.origin[0];y-=object.origin[1];z-=object.origin[2];const [w,,d]=object.size;+ const [a,c]=[[x,z],[z,d-1-x],[w-1-x,d-1-z],[w-1-z,x]][object.rotation];return [a,y,c];+}+export function validateProject(input) {+ const p=clone(input);+ if(!p || p.spec!==SPEC || !idPattern.test(p.id))throw new Error('Open a Tidelands world project.');+ if(!words(p.title,120)||!p.title.trim()||!words(p.brief,12000))throw new Error('Give the world a title and brief.');+ if(!ints(p.size,3,4,128)||p.size.reduce((a,b)=>a*b,1)>1048576)throw new Error('Use a world up to 128 cells per side and one million cells.');+ if(!finite(p.unit,0.01,10))throw new Error('Set the real size of one voxel in meters.');+ if(!Array.isArray(p.materials)||!p.materials.length||p.materials.length>255)throw new Error('Use 1–255 materials.');+ const materials=new Set([0]);+ for(const m of p.materials){+ if(!Number.isInteger(m.id)||!finite(m.id,1,255)||materials.has(m.id)||!words(m.name,80)||!/^#[0-9a-f]{6}$/i.test(m.color))throw new Error('Materials need unique numeric IDs, names and hex colors.');+ materials.add(m.id);m.solid??=true;m.opacity??=1;m.emission??=0;+ if(typeof m.solid!=='boolean'||!finite(m.opacity,.05,1)||!finite(m.emission,0,1))throw new Error('Invalid material solidity, opacity or emission.');+ }+ if(!Array.isArray(p.objects)||!p.objects.length||p.objects.length>128)throw new Error('Use 1–128 named objects.');+ let volume=0,paint=0,commands=0;const ids=new Set();+ for(const o of p.objects){+ if(!idPattern.test(o.id)||ids.has(o.id)||!words(o.name,120))throw new Error('Give every object a unique ID and a name.');ids.add(o.id);+ if(!ints(o.size,3,1,128)||!ints(o.origin,3,0,127))throw new Error('Object dimensions and origins must be whole voxel coordinates.');+ o.rotation??=0;o.hidden??=false;o.locked??=false;o.edits??=[];+ if(!Number.isInteger(o.rotation)||!finite(o.rotation,0,3)||typeof o.hidden!=='boolean'||typeof o.locked!=='boolean')throw new Error('Invalid object orientation or visibility.');+ if(rotatedSize(o).some((n,i)=>o.origin[i]+n>p.size[i]))throw new Error(`${o.name} extends outside the world. Move it inward or enlarge the world.`);+ volume+=o.size.reduce((a,b)=>a*b,1);+ if(!Array.isArray(o.boxes)||!Array.isArray(o.edits))throw new Error('Object geometry needs boxes and cell edits.');+ for(const b of o.boxes){+ if(!ints(b,7,0,255)||b.slice(3,6).some(n=>!n)||b.slice(0,3).some((n,i)=>n+b[i+3]>o.size[i])||!materials.has(b[6]))throw new Error(`Invalid voxel box in ${o.name}.`);+ paint+=b[3]*b[4]*b[5];commands++;+ }+ for(const e of o.edits){if(!ints(e,4,0,255)||e.slice(0,3).some((n,i)=>n>=o.size[i])||!materials.has(e[3]))throw new Error(`Invalid cell edit in ${o.name}.`);commands++;}+ }+ if(volume>8388608||paint>16777216||commands>100000)throw new Error('This project exceeds the editing budget. Split it into related worlds or assets.');+ const position = v => Array.isArray(v)&&v.length===3&&v.every((n,i)=>finite(n,0,p.size[i]));+ if(!p.spawn||!position(p.spawn.position)||!finite(p.spawn.yaw,-Math.PI*2,Math.PI*2))throw new Error('Place the visitor start inside the world.');+ p.stops??=[];if(!Array.isArray(p.stops)||p.stops.length>30)throw new Error('Use at most 30 tour stops.');+ const stopIds=new Set();for(const s of p.stops){if(!idPattern.test(s.id)||stopIds.has(s.id)||!words(s.name,120)||!words(s.description,2000)||!position(s.position))throw new Error('Invalid tour stop.');stopIds.add(s.id);}+ p.notes??='';if(!words(p.notes,12000))throw new Error('Keep project notes under 12,000 characters.');+ p.light??=.32;if(!finite(p.light,0,1))throw new Error('Choose a light setting from 0 to 1.');+ if(JSON.stringify(p).length>12000000)throw new Error('Keep the editable project under 12 MB.');+ return p;+}+export function objectCells(object) {+ const [w,h,d]=object.size,cells=new Uint8Array(w*h*d),at=(x,y,z)=>(y*d+z)*w+x;+ for(const [x,y,z,sx,sy,sz,id]of object.boxes)for(let j=y;j<y+sy;j++)for(let k=z;k<z+sz;k++)cells.fill(id,at(x,j,k),at(x+sx,j,k));+ for(const [x,y,z,id]of object.edits)cells[at(x,y,z)]=id;+ return cells;+}+export function compileWorld(p) {+ const [w,h,d]=p.size,cells=new Uint8Array(w*h*d),owners=new Uint16Array(cells.length),materials=new Map(p.materials.map(m=>[m.id,m]));+ let count=0;const counts=new Map();+ for(let i=0;i<p.objects.length;i++){+ const o=p.objects[i];if(o.hidden)continue;const local=objectCells(o),[ow,oh,od]=o.size;+ for(let y=0;y<oh;y++)for(let z=0;z<od;z++)for(let x=0;x<ow;x++){+ const id=local[(y*od+z)*ow+x];if(!id)continue;const [wx,wy,wz]=localToWorld(o,x,y,z),n=(wy*d+wz)*w+wx;+ cells[n]=id;owners[n]=i+1;+ }+ }+ for(const id of cells)if(id){count++;counts.set(id,(counts.get(id)||0)+1);}+ return {size:p.size,unit:p.unit,cells,owners,materials,count,counts};+}+export function cellAt(world,x,y,z) { const [w,h,d]=world.size;return x<0||y<0||z<0||x>=w||y>=h||z>=d?0:world.cells[(y*d+z)*w+x]; }+export function isSolid(world,x,y,z){return world.materials.get(cellAt(world,x,y,z))?.solid??false;}+export const faces = [+ {n:[1,0,0],v:[[1,0,0],[1,1,0],[1,1,1],[1,0,1]]},+ {n:[-1,0,0],v:[[0,0,1],[0,1,1],[0,1,0],[0,0,0]]},+ {n:[0,1,0],v:[[0,1,1],[1,1,1],[1,1,0],[0,1,0]]},+ {n:[0,-1,0],v:[[0,0,0],[1,0,0],[1,0,1],[0,0,1]]},+ {n:[0,0,1],v:[[1,0,1],[1,1,1],[0,1,1],[0,0,1]]},+ {n:[0,0,-1],v:[[0,0,0],[0,1,0],[1,1,0],[1,0,0]]},+];+export function meshWorld(p,world=compileWorld(p)) {+ const groups=new Map(),[w,h,d]=world.size;let faceCount=0;+ for(let y=0;y<h;y++)for(let z=0;z<d;z++)for(let x=0;x<w;x++){+ const index=(y*d+z)*w+x,id=world.cells[index];if(!id)continue;const owner=world.owners[index]-1,key=owner+':'+id;+ for(const f of faces){+ const next=cellAt(world,x+f.n[0],y+f.n[1],z+f.n[2]);if(next&&(next===id||world.materials.get(next).opacity===1))continue;+ if(++faceCount>350000)throw new Error('This scene has too many exposed voxel faces. Simplify scattered geometry or split it into assets.');+ if(!groups.has(key))groups.set(key,{object:owner,material:id,positions:[],normals:[],indices:[]});const g=groups.get(key),base=g.positions.length/3;+ for(const v of f.v){g.positions.push(x+v[0],y+v[1],z+v[2]);g.normals.push(...f.n);}g.indices.push(base,base+1,base+2,base,base+2,base+3);+ }+ }+ return [...groups.values()];+}+export function paintCells(p,objectId,worldPosition,material,radius=0,{existingOnly=false}={}) {+ const o=p.objects.find(o=>o.id===objectId);if(!o||o.locked)throw new Error('Choose an unlocked object to sculpt.');+ if(o.rotation){+ const old=objectCells(o),[w,h,d]=o.size,nextSize=rotatedSize(o),next=new Uint8Array(nextSize.reduce((a,b)=>a*b,1));+ for(let y=0;y<h;y++)for(let z=0;z<d;z++)for(let x=0;x<w;x++){const [a,b,c]=localToWorld(o,x,y,z).map((n,i)=>n-o.origin[i]);next[(b*nextSize[2]+c)*nextSize[0]+a]=old[(y*d+z)*w+x];}+ o.size=nextSize;o.rotation=0;o.boxes=boxesFromCells(next,nextSize);o.edits=[];+ }+ if(material!==0&&!existingOnly){+ const lower=worldPosition.map((n,i)=>Math.max(-o.origin[i],Math.min(0,n-o.origin[i]-radius)));+ const upper=worldPosition.map((n,i)=>Math.min(p.size[i]-o.origin[i],Math.max(o.size[i],n-o.origin[i]+radius+1)));+ for(const b of o.boxes)for(let i=0;i<3;i++)b[i]-=lower[i];for(const e of o.edits)for(let i=0;i<3;i++)e[i]-=lower[i];+ o.size=upper.map((n,i)=>n-lower[i]);o.origin=o.origin.map((n,i)=>n+lower[i]);+ }+ const center=worldToLocal(o,...worldPosition),edits=new Map(o.edits.map(e=>[e.slice(0,3).join(','),e])),before=existingOnly?objectCells(o):null;let changed=0;+ for(let y=-radius;y<=radius;y++)for(let z=-radius;z<=radius;z++)for(let x=-radius;x<=radius;x++){+ const at=[center[0]+x,center[1]+y,center[2]+z];if(at.some((n,i)=>n<0||n>=o.size[i]))continue;+ if(before&&!before[(at[1]*o.size[2]+at[2])*o.size[0]+at[0]])continue;+ edits.set(at.join(','),[...at,material]);changed++;+ }+ o.edits=[...edits.values()];return changed;+}+export function boxesFromCells(cells,size){+ const [w,h,d]=size,boxes=[];+ for(let y=0;y<h;y++)for(let z=0;z<d;z++)for(let x=0;x<w;){const id=cells[(y*d+z)*w+x],start=x++;while(x<w&&cells[(y*d+z)*w+x]===id)x++;if(id)boxes.push([start,y,z,x-start,1,1,id]);}+ return boxes;+}+export function fitsVisitor(world,position) {+ const [x,y,z]=position,r=.26/world.unit,height=1.7/world.unit;+ if(x-r<0||z-r<0||x+r>world.size[0]||z+r>world.size[2]||y<0||y+height>world.size[1])return false;+ for(let a=Math.floor(x-r);a<=Math.floor(x+r-.0001);a++)for(let b=Math.floor(y+.0001);b<=Math.floor(y+height-.0001);b++)for(let c=Math.floor(z-r);c<=Math.floor(z+r-.0001);c++)if(isSolid(world,a,b,c))return false;+ return true;+}+export function moveVisitor(world,visitor,input,dt=1/60) {+ const p=clone(visitor);let dx=Math.sin(p.yaw)*(input.forward||0)-Math.cos(p.yaw)*(input.right||0),dz=Math.cos(p.yaw)*(input.forward||0)+Math.sin(p.yaw)*(input.right||0);+ const speed=(input.sprint?5:3)/world.unit,normal=Math.max(1,Math.hypot(dx,dz));dx=dx/normal*speed*dt;dz=dz/normal*speed*dt;+ for(const [axis,delta]of [[0,dx],[2,dz]]){+ const next=[...p.position];next[axis]+=delta;+ if(fitsVisitor(world,next))p.position=next;+ else if(p.grounded){for(let step=1;step<=Math.ceil(.45/world.unit);step++){next[1]=Math.floor(p.position[1])+step;if(next[1]-p.position[1]>.45/world.unit+.001)break;if(fitsVisitor(world,next)){p.position=next;break;}}}+ }+ if(input.jump&&p.grounded)p.velocity=4/world.unit;+ p.velocity=(p.velocity||0)-9.8/world.unit*dt;const vertical=[...p.position];vertical[1]+=p.velocity*dt;+ if(fitsVisitor(world,vertical)){p.position=vertical;p.grounded=false;}+ else{+ let low=0,high=1;const delta=vertical[1]-p.position[1];+ for(let i=0;i<12;i++){const middle=(low+high)/2,candidate=[...p.position];candidate[1]+=delta*middle;if(fitsVisitor(world,candidate))low=middle;else high=middle;}+ p.position[1]+=delta*low;if(p.velocity<0)p.grounded=true;p.velocity=0;+ }+ return p;+}+export function navigationReport(p,world=compileWorld(p)) {+ const issues=[],height=1.7/p.unit,step=.45/p.unit,drop=1/p.unit,[w,h,d]=p.size,surfaces=new Map();+ for(let z=0;z<d;z++)for(let x=0;x<w;x++){+ const ys=[];for(let y=1;y+height<=h;y++)if(isSolid(world,x,y-1,z)&&!isSolid(world,x,y,z)&&fitsVisitor(world,[x+.5,y,z+.5]))ys.push(y);+ if(ys.length)surfaces.set(x+','+z,ys);+ }+ const start=p.spawn.position.map(Math.floor),startHeights=surfaces.get(start[0]+','+start[2])??[],sy=startHeights.find(y=>Math.abs(y-p.spawn.position[1])<.2);+ if(sy===undefined||!fitsVisitor(world,p.spawn.position))issues.push('The visitor start has no clear standing space.');+ const visited=new Set(),queue=[];if(sy!==undefined){start[1]=sy;queue.push(start);visited.add(start.join(','));}+ for(let i=0;i<queue.length;i++){+ const [x,y,z]=queue[i];for(const [dx,dz]of [[1,0],[-1,0],[0,1],[0,-1]])for(const ny of surfaces.get((x+dx)+','+(z+dz))??[]){+ if(ny-y>step+.001||y-ny>drop+.001)continue;const next=[x+dx,ny,z+dz],key=next.join(',');if(!visited.has(key)){visited.add(key);queue.push(next);}+ }+ }+ const stops=p.stops.map(s=>{const [x,y,z]=s.position,reachable=[...surfaces.get(Math.floor(x)+','+Math.floor(z))??[]].some(ny=>Math.abs(y-ny)<.2&&visited.has([Math.floor(x),ny,Math.floor(z)].join(',')));if(!reachable)issues.push(`${s.name} is not connected to the visitor start by the checked walking routes.`);return {id:s.id,reachable};});+ return {spawnClear:sy!==undefined&&fitsVisitor(world,p.spawn.position),reachableStandingCells:visited.size,stops,issues,method:'Cardinal standing-cell search with visitor clearance, 0.45 m steps and 1 m descents; actual browser walking still required.'};+}diff --git a/store/agents/voxel-worlds/template/studio/shell.html b/store/agents/voxel-worlds/template/studio/shell.htmlnew file mode 100644index 000000000..f87dae9ba--- /dev/null+++ b/store/agents/voxel-worlds/template/studio/shell.html@@ -0,0 +1,12 @@+<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Tidelands — World Studio</title><!-- FAVICON --><style>/* STUDIO_CSS */</style></head><body>+<header><div class="identity"><span class="mark"><!-- WORLD_ICON --></span><span>TIDELANDS<small>WORLD STUDIO</small></span></div><div class="project-heading"><strong id="world-title"></strong><span id="save-state">Opening world</span></div><nav><button id="open-project">Open</button><button id="save-project">Save project</button><button id="save-source" class="primary" hidden>Save to workspace</button><button id="deliver" class="primary">Export kit ↗</button></nav></header>+<div id="source-notice" class="notice" hidden><span></span><button id="source-load">Use source version</button><button id="draft-keep">Download my draft</button></div>+<main><aside class="objects-panel"><div class="panel-title">SCENE <span id="object-count"></span></div><div class="search"><input id="object-search" placeholder="Find an object" aria-label="Find an object"></div><div id="object-list"></div><button id="new-object" class="wide">+ New voxel object</button><button id="import-vox" class="wide">↗ Import .vox asset</button><div class="brief"><div class="eyebrow">THE BRIEF</div><p id="brief-text"></p><button id="edit-project">Project & scale</button></div></aside>+<section class="stage"><div id="viewport" tabindex="0" aria-label="Interactive 3D world"></div><div class="modebar"><div class="segmented"><button id="edit-mode" class="active">Build</button><button id="walk-mode">Walk the world</button></div><button id="frame-world" title="Frame the whole world">↗ Frame all</button><button id="snapshot">Save view</button></div><div class="tools" id="edit-tools"><button data-tool="select" class="active" title="Select and move an object">↖ Select</button><button data-tool="add">+ Build</button><button data-tool="erase">− Erase</button><button data-tool="paint">◈ Paint</button><span></span><button id="undo" title="Undo (Command/Ctrl Z)">↶</button><button id="redo" title="Redo (Command/Ctrl Shift Z)">↷</button></div><div id="crosshair" hidden>+</div><div id="walk-overlay" hidden><button id="enter-walk" class="primary">Enter world</button><p>WASD to walk · drag to look · Space to jump · Esc to release</p><div id="tour-stops"></div></div><div id="touch-walk" hidden><button data-move="forward" aria-label="Walk forward">↑</button><div><button data-move="left" aria-label="Walk left">←</button><button data-move="back" aria-label="Walk backward">↓</button><button data-move="right" aria-label="Walk right">→</button><button data-move="jump" aria-label="Jump">↟</button></div></div><div class="scene-caption"><span id="scene-measures"></span><span id="interaction-hint">Drag to orbit · scroll to zoom · click an object</span></div></section>+<aside class="inspector"><div class="panel-title">OBJECT <button id="focus-object">Focus ↗</button></div><div id="object-editor"></div><section class="materials"><div class="panel-title">MATERIALS <button id="new-material">+</button></div><div id="palette"></div><div id="material-editor"></div><label>Brush radius <select id="brush-radius"><option value="0">One voxel</option><option value="1">3 × 3 × 3</option><option value="2">5 × 5 × 5</option></select></label></section><section class="lighting"><div class="panel-title">LIGHT</div><label>Time of day<input id="light" type="range" min="0" max="1" step=".01"></label><label class="check"><input id="cycle-light" type="checkbox"> Let daylight move</label></section></aside></main>+<footer><span id="status" role="status">Ready to shape your world</span><button id="check-routes">Check walking routes</button></footer>+<dialog id="project-dialog"><form method="dialog"><h2>Project & scale</h2><label>Title<input id="project-title" required maxlength="120"></label><label>Your brief<textarea id="project-brief" rows="5" maxlength="12000"></textarea></label><label>Size in voxels<div class="xyz"><input id="size-x" type="number" min="4" max="128" aria-label="World width"><input id="size-y" type="number" min="4" max="128" aria-label="World height"><input id="size-z" type="number" min="4" max="128" aria-label="World depth"></div></label><label>Meters per voxel<input id="project-unit" type="number" min=".01" max="10" step=".01"></label><label>Notes<textarea id="project-notes" rows="3"></textarea></label><p>Changing scale changes the real size of the scene and visitor clearance.</p><div class="dialog-actions"><button value="cancel">Cancel</button><button id="apply-project" type="button" class="primary">Apply</button></div></form></dialog>+<dialog id="export-dialog"><h2>Take your world with you</h2><p id="export-summary"></p><div class="export-options"><button id="export-glb"><strong>3D world · GLB</strong><span>Named meshes and materials, in meters</span></button><button id="export-vox"><strong>Voxel world · VOX</strong><span>Flattened geometry and color palette</span></button><button id="export-walk"><strong>Walkthrough · HTML</strong><span>One offline file to share and explore</span></button><button id="export-kit" class="primary"><strong>Complete editable kit · ZIP</strong><span>3D files, project, studio and walkthrough</span></button></div><p class="fine">GLB keeps visible geometry and materials. VOX merges the scene into one voxel model. Keep the project JSON to retain object structure and project settings.</p><button id="close-export">Close</button></dialog>+<dialog id="open-dialog"><h2>Open a world</h2><p>Open a saved Tidelands project as a draft. Save it to this workspace when you are ready.</p><button id="choose-project">Choose project file…</button><section id="native-open"><label>Or paste the path to a project in your home folder<input id="project-path" placeholder="~/Downloads/my-world.tidelands.json"></label><button id="open-path">Open this project</button><div class="panel-title" style="margin-top:24px">RECENT PROJECTS</div><div id="recent-projects"></div></section><div class="dialog-actions"><button id="close-open">Close</button></div></dialog>+<input id="project-file" type="file" accept=".json,.tidelands.json" hidden><input id="vox-file" type="file" accept=".vox" hidden>+<script id="world-data" type="application/json">WORLD_DATA</script><script>/* WORLD_APP */</script></body></html>diff --git a/store/agents/voxel-worlds/template/studio/style.css b/store/agents/voxel-worlds/template/studio/style.cssnew file mode 100644index 000000000..6ffff55c3--- /dev/null+++ b/store/agents/voxel-worlds/template/studio/style.css@@ -0,0 +1,4 @@+*{box-sizing:border-box} :root{font:13px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;color:#273637;background:#eeeae2;--border:#d8d9ce;--muted:#737d75;--green:#285c50;--accent:#db9e69}body{margin:0;height:100dvh;display:flex;flex-direction:column;overflow:hidden}button,input,textarea,select{font:inherit}button{cursor:pointer;background:#fafbf5;border:1px solid var(--border);color:inherit;padding:8px 12px;border-radius:6px;white-space:nowrap}button:hover{background:#e4e9dd;border-color:#adb9a6}button:disabled{opacity:.4;cursor:default}button.primary{background:var(--green);border-color:var(--green);color:#fff}button.active{background:#d8e8d7;border-color:#a0b89b;color:#204d40}button:focus-visible,input:focus-visible,select:focus-visible,textarea:focus-visible{outline:2px solid #ad7642;outline-offset:2px}[hidden]{display:none!important}header{height:78px;flex-shrink:0;display:flex;gap:24px;align-items:center;padding:0 24px;background:#f9faf3;border-bottom:1px solid var(--border)}.identity{display:flex;gap:10px;align-items:center;font-size:16px;font-weight:750;letter-spacing:2px;min-width:208px}.identity small{display:block;font-size:9px;letter-spacing:2px;font-weight:500;color:var(--muted)}.mark{width:36px;height:36px;display:block}.mark svg{width:100%;height:100%}.project-heading{flex:1;min-width:0}.project-heading strong{font-size:17px;display:block;overflow:hidden;white-space:nowrap;text-overflow:ellipsis}.project-heading span{font-size:11px;color:var(--muted)}nav{display:flex;gap:7px}main{flex:1;min-height:0;display:grid;grid-template-columns:235px minmax(240px,1fr) 250px}aside{background:#f9faf3;overflow:auto;padding:20px 16px}.objects-panel{border-right:1px solid var(--border)}.inspector{border-left:1px solid var(--border)}.panel-title{font-size:10px;letter-spacing:1.7px;font-weight:700;display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;color:#667263}.panel-title button{padding:3px 6px;font-size:10px;letter-spacing:0}.panel-title span{font-size:10px;letter-spacing:0}.search{margin-bottom:14px}input,textarea,select{background:#fffef8;border:1px solid var(--border);border-radius:5px;color:inherit;max-width:100%;padding:7px 9px}input:not([type=color]):not([type=checkbox]):not([type=range]),textarea{width:100%}.object-row{display:flex;gap:6px;align-items:center;margin:3px -7px;border:1px solid transparent;border-radius:6px}.object-row.selected{border-color:#b6c8ad;background:#e8efdf}.object-row>button:first-child{border:0;background:transparent;text-align:left;flex:1;overflow:hidden;text-overflow:ellipsis;padding:9px 5px;font-size:12px;min-width:0}.object-row .dot{display:inline-block;width:8px;height:8px;background:#a3b69a;margin:0 8px 0 5px;border-radius:2px}.object-row button.toggle{border:0;background:none;padding:4px;font-size:11px;opacity:.6}.object-row.hidden-object{opacity:.5}.wide{width:100%;margin-top:9px;font-size:12px}.brief{border-top:1px solid var(--border);margin-top:25px;padding-top:20px}.eyebrow{font-size:9px;letter-spacing:1.8px;color:var(--muted)}.brief p{font-size:11px;line-height:1.75;color:#778170}.brief button{font-size:11px}#object-list{max-height:45vh;overflow:auto}label{display:block;font-size:11px;color:#73806e;margin:13px 0}label input,label select,label textarea{display:block;margin-top:5px;font-size:12px;color:#34483c}.xyz{display:flex;gap:5px}.xyz input{min-width:0;padding:7px 5px}.xyz label{margin:0;flex:1}.inspector .actions{display:flex;gap:5px;margin:12px 0;flex-wrap:wrap}.actions button{font-size:11px;padding:6px 9px}.check{display:flex;align-items:center;gap:7px}.check input{margin:0}.materials,.lighting{border-top:1px solid var(--border);margin-top:22px;padding-top:20px}#palette{display:flex;flex-wrap:wrap;gap:7px}#palette button{width:25px;height:25px;padding:0;border:2px solid #fff;box-shadow:0 0 0 1px #ccd1c7;border-radius:5px}#palette button.active{box-shadow:0 0 0 2px #284c40}#material-editor .color-row{display:flex;gap:8px;align-items:center;margin-top:12px}input[type=color]{height:31px;width:40px;padding:2px;flex-shrink:0}input[type=range]{width:100%;accent-color:var(--green)}.stage{position:relative;min-width:0;overflow:hidden;background:#d2d8cf}#viewport{position:absolute;inset:0;outline:0;touch-action:none}#viewport canvas{width:100%;height:100%;display:block}.modebar{position:absolute;top:18px;left:20px;right:20px;display:flex;gap:7px;pointer-events:none}.modebar button,.modebar .segmented{pointer-events:auto;box-shadow:0 3px 12px #1429220c}.segmented{display:flex;gap:3px;background:#f6f8eeee;border:1px solid #d6ddce;border-radius:8px;padding:3px;margin-right:auto}.segmented button{border:0;padding:6px 13px;box-shadow:none}.modebar>button{background:#f6f8eeed}.tools{position:absolute;bottom:55px;left:50%;transform:translateX(-50%);display:flex;gap:4px;padding:5px;background:#f5f7eef2;box-shadow:0 6px 28px #1b2c2720;border:1px solid #d3ddcd;border-radius:9px}.tools button{border:0;background:transparent;padding:8px 12px;font-size:12px}.tools button.active{background:#d9e5d0}.tools span{border-left:1px solid #d3ddcd;margin:4px}.scene-caption{position:absolute;bottom:0;left:0;right:0;display:flex;justify-content:space-between;gap:15px;padding:12px 18px;background:linear-gradient(transparent,#e2e5dceb);font-size:10px;color:#526559;pointer-events:none}footer{height:35px;padding:0 20px;display:flex;justify-content:space-between;align-items:center;border-top:1px solid var(--border);background:#f9faf3;font-size:11px;flex-shrink:0}footer button{font-size:10px;padding:3px 7px;border:0;background:none}#status{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}dialog{border:1px solid var(--border);border-radius:14px;background:#f9faf3;color:inherit;max-width:540px;width:calc(100% - 36px);padding:28px;box-shadow:0 20px 80px #12251d30}dialog::backdrop{background:#1d30264d;backdrop-filter:blur(4px)}dialog h2{margin:0 0 14px;font-size:23px;letter-spacing:-.7px}dialog p{color:var(--muted);font-size:12px}.dialog-actions{display:flex;justify-content:flex-end;gap:8px}.export-options{display:grid;gap:9px;margin:22px 0}.export-options button{text-align:left;padding:15px 18px}.export-options strong,.export-options span{display:block}.export-options span{font-size:11px;opacity:.75;margin-top:3px}.fine{font-size:11px!important}.notice{background:#f2dfb7;color:#654e28;padding:8px 20px;display:flex;align-items:center;gap:12px;font-size:12px}.notice span{flex:1}.notice button{font-size:11px;padding:4px 8px}#crosshair{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);font-size:24px;color:white;text-shadow:0 1px 4px #000}#walk-overlay{position:absolute;top:80px;left:20px;right:20px;text-align:center;pointer-events:none}#walk-overlay button{pointer-events:auto}#walk-overlay p{color:#fff;text-shadow:0 1px 3px #000;font-size:11px}#tour-stops{display:flex;justify-content:center;gap:7px}#tour-stops button{font-size:11px;background:#f9fbf0d9}#touch-walk{position:absolute;bottom:60px;left:24px;text-align:center;touch-action:none}#touch-walk button{width:44px;height:44px;background:#f4f8eee0;padding:0;font-size:22px;margin:2px}body.walking .objects-panel,body.walking .inspector{display:none}body.walking main{grid-template-columns:1fr}body.readonly nav,body.readonly #edit-mode,body.readonly #snapshot,body.readonly footer button{display:none}body.readonly .identity small{font-size:8px}body.readonly .project-heading span{display:none}@media(max-width:1100px){main{grid-template-columns:190px minmax(240px,1fr) 218px}header{padding:0 16px;gap:16px}.identity{min-width:170px;font-size:14px}.tools button{padding:8px}.scene-caption #interaction-hint{display:none}aside{padding:16px 12px}}@media(max-width:820px){main{grid-template-columns:170px minmax(240px,1fr)}.inspector{display:none}header{height:68px}.identity{min-width:0}.identity>span:last-child{display:none}nav button{font-size:11px;padding:7px 9px}#save-project{display:none}.project-heading strong{font-size:14px}.modebar{left:12px;right:12px;top:12px}.modebar>button{display:none}}@media(max-width:560px){main{grid-template-columns:1fr}.objects-panel{display:none}.tools{bottom:50px;max-width:calc(100% - 16px);width:max-content}.tools button{font-size:11px;padding:7px 9px}header{padding:0 12px;gap:10px}.project-heading span{font-size:10px}footer{padding:0 12px;font-size:10px}.notice{flex-wrap:wrap;font-size:11px}.notice span{min-width:100%}}++body.readonly .objects-panel,body.readonly .inspector{display:none}body.readonly main{grid-template-columns:1fr}+@media(max-width:560px){#save-source:disabled{display:none}}diff --git a/store/agents/voxel-worlds/template/tools/build.mjs b/store/agents/voxel-worlds/template/tools/build.mjsnew file mode 100644index 000000000..8ef5befac--- /dev/null+++ b/store/agents/voxel-worlds/template/tools/build.mjs@@ -0,0 +1,27 @@+#!/usr/bin/env node+import {readFile,writeFile,mkdir,realpath,access} from 'node:fs/promises';+import {resolve,join,sep,dirname} from 'node:path';+import {fileURLToPath,pathToFileURL} from 'node:url';+import {createHash} from 'node:crypto';+import {validateProject,compileWorld,meshWorld} from '../studio/project.mjs';+export async function readProject(workspace){+ const root=await realpath(workspace),source=await realpath(join(root,'world/project.json'));+ if(!source.startsWith(root+sep)||!source.startsWith(join(root,'world')+sep))throw new Error('Keep the project source inside world/.');+ const project=validateProject(JSON.parse(await readFile(source,'utf8')));delete project.revision;return project;+}+export async function toolsDirectory(){+ const candidates=[process.env.VOXEL_DSH_DIR&&join(process.env.VOXEL_DSH_DIR,'toolchain'),fileURLToPath(new URL('../../toolchain/',import.meta.url))].filter(Boolean);+ for(const path of candidates){try{await access(join(path,'node_modules/esbuild/lib/main.js'));return path;}catch{}}+ throw new Error('Voxel Worlds build tools are missing. Run its setup script, then use VOXEL_DSH_DIR for an installed workspace.');+}+export async function buildWorld(workspace,{check=false}={}){+ const root=resolve(workspace);if(!check){await mkdir(join(root,'.harness'),{recursive:true});await writeFile(join(root,'.harness/verdict.json'),JSON.stringify({spec:1,ready:false,artifact:'world/index.html',summary:'Building the editable world; browser review pending'}));}+ const project=await readProject(root),world=compileWorld(project);meshWorld(project,world);project.revision=createHash('sha256').update(JSON.stringify(project)).digest('hex');+ const tools=await toolsDirectory(),{build}=await import(pathToFileURL(join(tools,'node_modules/esbuild/lib/main.js')).href);+ const bundle=await build({entryPoints:[join(root,'studio/app.js')],bundle:true,write:false,format:'iife',minify:true,target:'es2022',legalComments:'eof',nodePaths:[join(tools,'node_modules')]});+ const [shell,css,icon]=await Promise.all(['shell.html','style.css','icon.svg'].map(n=>readFile(join(root,'studio',n),'utf8')));+ const html=shell.replace('/* STUDIO_CSS */',()=>css).replace('<!-- WORLD_ICON -->',()=>icon).replace('<!-- FAVICON -->',()=>`<link rel="icon" href="data:image/svg+xml,${encodeURIComponent(icon)}">`).replace('WORLD_DATA',()=>JSON.stringify({project,mode:'edit'}).replace(/</g,'\\u003c')).replace('/* WORLD_APP */',()=>bundle.outputFiles[0].text.replace(/<\/script/gi,'<\\/script'));+ const target=join(root,'world/index.html');if(check){if(await readFile(target,'utf8')!==html)throw new Error('World preview is stale. Run node tools/build.mjs.');}else{await writeFile(target,html);await writeFile(join(root,'.harness/verdict.json'),JSON.stringify({spec:1,ready:false,artifact:'world/index.html',summary:project.title+' · editable world built; walking and export review pending',findings:[{severity:'info',kind:'review_pending',message:'A build does not establish usability or visual quality. Walk the actual world and reopen the exported geometry.'}]},null,2)+'\n');}+ return {title:project.title,revision:project.revision,objects:project.objects.length,voxels:world.count};+}+if(process.argv[1]&&resolve(process.argv[1])===fileURLToPath(import.meta.url))console.log(JSON.stringify(await buildWorld(resolve(dirname(fileURLToPath(import.meta.url)),'..'),{check:process.argv.includes('--check')})));diff --git a/store/agents/voxel-worlds/template/tools/check.mjs b/store/agents/voxel-worlds/template/tools/check.mjsindex f8d823ba2..e0fb39d71 100644--- a/store/agents/voxel-worlds/template/tools/check.mjs+++ b/store/agents/voxel-worlds/template/tools/check.mjs@@ -1,75 +1,11 @@-const CONFIG = {"id":"voxel-worlds","artifact":"world/index.html"};-// Compiled into each workspace's tools/check.mjs. Tests the model in the ACTUAL edited HTML.-import { readFile, mkdir, writeFile } from "node:fs/promises";-import { createHash } from "node:crypto";-import vm from "node:vm";-import { resolve, dirname } from "node:path";--const args = process.argv.slice(2),- i = args.indexOf("--seeds");-const count = i === -1 ? 32 : Number(args[i + 1]);-if (!Number.isInteger(count) || count < 1 || count > 1000)- throw new Error("--seeds must be an integer from 1 to 1000");-const artifact = resolve(CONFIG.artifact);-const html = await readFile(artifact, "utf8");-const script = html.match(- /<script id="harness-model">([\s\S]*?)<\/script>/,-)?.[1];-if (!script)- throw new Error(- 'Keep the pure model in <script id="harness-model"> so this checker can exercise the actual artifact.',- );-const expressions = {- "generative-art": `const m=artModel(SEED);const p=artPaths(m);({state:m,valid:p.length>0&&p.flat().every(([x,y])=>Number.isFinite(x)&&Number.isFinite(y)),metrics:{paths:p.length,palette:m.palette}})`,- "creative-direction": `const m=directionModel(SEED);const ratio=contrast(m.colors[0],m.colors[1]);({state:m,valid:ratio>=4.5,metrics:{direction:m.name,contrast:ratio}})`,- "lab-bench": `const p=experiment(SEED),e=treatmentEffect(p);({state:p,valid:p.length>1&&p.every(p=>Number.isFinite(p.x)&&Number.isFinite(p.y))&&Number.isFinite(e.low)&&e.low<=e.high,metrics:{samples:p.length,effect:e.difference,interval:[e.low,e.high]}})`,- "music-studio": `const s=musicScore(SEED),r=renderMusic(s);({state:Array.from(r.samples),valid:r.peak>.001&&r.peak<=.95&&r.samples.every(Number.isFinite),metrics:{seconds:r.duration,peak:r.peak,rms:r.rms}})`,- "game-master": `const m=arenaMatch(SEED),s=m.history.at(-1);({state:m,valid:m.history.length>1&&m.history.length<=10000&&s.units.every(u=>u.hp>=0&&u.x>=0&&u.x<m.map.w&&u.y>=0&&u.y<m.map.h),metrics:{turns:s.turn,score:s.score,winner:m.winner}})`,- "drone-pilot": `const s=flyAutopilot(SEED);({state:s,valid:s.finished&&!s.crashed&&s.passed===flightCourse(SEED).length,metrics:{seconds:s.time,passed:s.passed,missed:s.missed}})`,- "voxel-worlds": `const w=voxelWorld(SEED);let p={...w.spawn,vy:0,grounded:true};const clear=playerFits(w,p.x,p.y,p.z);for(let t=0;t<120;t++)p=movePlayer(w,p,{forward:1});({state:Array.from(w.blocks),valid:clear&&playerFits(w,p.x,p.y,p.z),metrics:{blocks:w.blocks.filter(Boolean).length,walkDistance:Math.hypot(p.x-w.spawn.x,p.z-w.spawn.z)}})`,-};-const expression = expressions[CONFIG.id];-const digest = (value) =>- createHash("sha256").update(JSON.stringify(value)).digest("hex");-const results = [];-for (let seed = 0; seed < count; seed++) {- const run = () =>- vm.runInNewContext(- `${script}\n${expression}`,- { SEED: String(seed) },- { timeout: 10000 },- );- try {- const first = run(),- second = run(),- signature = digest(first.state),- repeat = digest(second.state);- results.push({- seed,- ok: first.valid && signature === repeat,- signature,- metrics: first.metrics,- });- } catch (error) {- results.push({ seed, ok: false, error: error.message });- }-}-const passed = results.filter((r) => r.ok).length;-const report = {- spec: 1,- harness: CONFIG.id,- artifact: CONFIG.artifact,- checkedAt: new Date().toISOString(),- modelChecks: { passed, total: count },- scope:- "Pure model invariants and same-process repeatability. Browser interaction, layout, listening and export review still required.",- results,-};-const out = resolve(".harness/model-check.json");-await mkdir(dirname(out), { recursive: true });-await writeFile(out, JSON.stringify(report, null, 2) + "\n");-console.log(- `${CONFIG.id}: ${passed}/${count} model checks passed. Report: ${out}`,-);-console.log(report.scope);-if (passed !== count) process.exitCode = 1;+#!/usr/bin/env node+import {readProject} from './build.mjs';+import {compileWorld,navigationReport} from '../studio/project.mjs';+import {exportGLB,exportVOX,importVOX} from '../studio/formats.mjs';+import {mkdir,writeFile} from 'node:fs/promises';+import {resolve,dirname,join} from 'node:path';+import {fileURLToPath} from 'node:url';+const root=resolve(dirname(fileURLToPath(import.meta.url)),'..'),p=await readProject(root),world=compileWorld(p),glb=exportGLB(p),vox=importVOX(exportVOX(p));+if(vox.cells.some((n,i)=>n!==world.cells[i]))throw new Error('VOX round trip changed geometry.');+const report={title:p.title,objects:p.objects.length,voxels:world.count,glbBytes:glb.length,voxRoundTrip:true,navigation:navigationReport(p),limits:'Finite model checks. Inspect the actual studio and reopen exported geometry before marking ready.'};+await mkdir(join(root,'.harness'),{recursive:true});await writeFile(join(root,'.harness/world-check.json'),JSON.stringify(report,null,2)+'\n');console.log(JSON.stringify(report));if(report.navigation.issues.length)process.exitCode=1;diff --git a/store/agents/voxel-worlds/template/tools/export.mjs b/store/agents/voxel-worlds/template/tools/export.mjsnew file mode 100644index 000000000..d46be8f49--- /dev/null+++ b/store/agents/voxel-worlds/template/tools/export.mjs@@ -0,0 +1,13 @@+#!/usr/bin/env node+import {mkdir,writeFile,readFile} from 'node:fs/promises';+import {join,resolve,dirname} from 'node:path';+import {fileURLToPath} from 'node:url';+import {readProject,buildWorld} from './build.mjs';+import {exportGLB,exportVOX} from '../studio/formats.mjs';+import {navigationReport} from '../studio/project.mjs';+import {zipFiles} from '../studio/archive.mjs';+export async function exportWorld(workspace,output=join(workspace,'delivery')){+ await buildWorld(workspace);const p=await readProject(workspace),html=await readFile(join(workspace,'world/index.html'),'utf8'),files=[[p.id+'.tidelands.json',JSON.stringify(p,null,2)],[p.id+'.glb',exportGLB(p)],[p.id+'.vox',exportVOX(p)],['studio.html',html],['walkthrough.html',html.replace(/(<script id="world-data" type="application\/json">)[\s\S]*?(<\/script>)/,(_,a,b)=>a+JSON.stringify({project:p,mode:'walk'}).replace(/</g,'\\u003c')+b)],['walking-check.json',JSON.stringify(navigationReport(p),null,2)],['README.md',`# ${p.title}\n\n${p.brief}\n\nOpen studio.html to edit or walkthrough.html to explore offline. GLB preserves named visible meshes, Y up, meters. VOX flattens the world into a single voxel model and palette, Z up. Keep the .tidelands.json source for all objects, settings, materials and destinations.\n\nOne voxel = ${p.unit} meters. A 1.7 m visitor is simulated. Route checks are finite geometry checks; walk the actual result. No game rules or physical construction validation is implied.\n\n${p.notes}\n`]];+ await mkdir(output,{recursive:true});for(const [name,body]of files)await writeFile(join(output,name),body);await writeFile(join(output,p.id+'-world-kit.zip'),new Uint8Array(await zipFiles(files).arrayBuffer()));return {title:p.title,output,files:files.map(([name])=>name)};+}+if(process.argv[1]&&resolve(process.argv[1])===fileURLToPath(import.meta.url)){const root=resolve(dirname(fileURLToPath(import.meta.url)),'..');console.log(JSON.stringify(await exportWorld(root,process.argv[2]?resolve(process.argv[2]):undefined)));}diff --git a/store/agents/voxel-worlds/template/world/index.html b/store/agents/voxel-worlds/template/world/index.htmlindex 298c7cb37..0519791d1 100644--- a/store/agents/voxel-worlds/template/world/index.html+++ b/store/agents/voxel-worlds/template/world/index.html@@ -1,1648 +1,4269 @@-<!doctype html>-<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">-<meta name="color-scheme" content="dark light"><title>TIDELANDS — Voxel Worlds</title>-<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22256%22%20height%3D%22256%22%20viewBox%3D%220%200%2096%2096%22%3E%0A%20%20%3Ctitle%3EVoxel%20Worlds%20%E2%80%94%20stepped%20island%3C%2Ftitle%3E%0A%20%20%3Crect%20x%3D%224%22%20y%3D%224%22%20width%3D%2288%22%20height%3D%2288%22%20rx%3D%2223%22%20fill%3D%22%23183e36%22%2F%3E%0A%20%20%3Cpath%20d%3D%22M20%2058%2048%2074%2076%2058v10L48%2084%2020%2068Z%22%20fill%3D%22%23619e9d%22%2F%3E%0A%20%20%3Cpath%20d%3D%22m20%2042%2014-8%2014%208-14%208Z%22%20fill%3D%22%23d8e9a6%22%2F%3E%0A%20%20%3Cpath%20d%3D%22m20%2042%2014%208v20l-14-8Z%22%20fill%3D%22%2371936a%22%2F%3E%0A%20%20%3Cpath%20d%3D%22m34%2050%2014-8v20l-14%208Z%22%20fill%3D%22%23aac785%22%2F%3E%0A%20%20%3Cpath%20d%3D%22m48%2042%2014-8%2014%208-14%208Z%22%20fill%3D%22%23d8e9a6%22%2F%3E%0A%20%20%3Cpath%20d%3D%22m48%2042%2014%208v20l-14-8Z%22%20fill%3D%22%2371936a%22%2F%3E%0A%20%20%3Cpath%20d%3D%22m62%2050%2014-8v20l-14%208Z%22%20fill%3D%22%23aac785%22%2F%3E%0A%20%20%3Cpath%20d%3D%22m34%2024%2014-8%2014%208-14%208Z%22%20fill%3D%22%23f4efce%22%2F%3E%0A%20%20%3Cpath%20d%3D%22m34%2024%2014%208v30l-14-8Z%22%20fill%3D%22%2399b878%22%2F%3E%0A%20%20%3Cpath%20d%3D%22m48%2032%2014-8v30l-14%208Z%22%20fill%3D%22%23d8e9a6%22%2F%3E%0A%3C%2Fsvg%3E">-<!-- Built by store/tools/build-experiences.mjs. Edit this file freely in your workspace. -->-<style>:root {- color-scheme: dark;- --bg: #111414;- --panel: #191e1c;- --line: #ffffff1c;- --ink: #f4f2e9;- --muted: #a1aaa4;- --accent: #d0f28a;- font:- 14px/1.5 -apple-system,- BlinkMacSystemFont,- "Segoe UI",- sans-serif;-}-* {- box-sizing: border-box;-}-body {- margin: 0;- background: var(--bg);- color: var(--ink);-}-button,-input,-select {- font: inherit;-}-button,-a,-input,-select {- -webkit-tap-highlight-color: transparent;-}-button,-a {- touch-action: manipulation;-}-button {- cursor: pointer;-}-button:disabled {- opacity: 0.45;- cursor: wait;-}-button:focus-visible,-input:focus-visible,-select:focus-visible,-a:focus-visible {- outline: 2px solid var(--accent);- outline-offset: 4px;-}-button,-input,-select {- color: inherit;- background: transparent;- border: 1px solid var(--line);- border-radius: 5px;- padding: 9px 13px;-}-button:hover {- background: #ffffff0c;- border-color: var(--muted);-}-button.primary {- background: var(--accent);- color: #142015;- border-color: transparent;- font-weight: 650;-}-button[aria-pressed="true"] {- border-color: var(--accent);- color: var(--accent);-}-input[type="range"] {- accent-color: var(--accent);- padding: 0;- min-width: 0;-}-input[type="number"] {- width: 80px;-}-select {- background: var(--panel);-}-label {- cursor: pointer;-}-a {- color: inherit;-}-h1,-h2,-h3,-p {- margin: 0;-}-h1 {- font-size: clamp(32px, 5vw, 64px);- line-height: 1.02;- letter-spacing: -0.055em;- font-weight: 550;-}-h2 {- font-weight: 550;- letter-spacing: -0.03em;-}-h3 {- font-size: 14px;- font-weight: 550;-}-.mono,-.eyebrow {- font-family: ui-monospace, "SFMono-Regular", Consolas, monospace;-}-.eyebrow {- font-size: 10px;- letter-spacing: 0.16em;- text-transform: uppercase;- color: var(--muted);-}-.muted {- color: var(--muted);-}-.small {- font-size: 12px;-}-.masthead {- display: flex;- align-items: center;- justify-content: space-between;- gap: 20px;- padding: 19px 28px;- border-bottom: 1px solid var(--line);-}-.identity {- display: flex;- gap: 12px;- align-items: center;- white-space: nowrap;- font-size: 12px;- font-weight: 600;- letter-spacing: 0.04em;-}-.mark {- width: 28px;- height: 28px;- flex: 0 0 28px;- display: grid;- place-items: center;+<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Tidelands — World Studio</title><link rel="icon" href="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22256%22%20height%3D%22256%22%20viewBox%3D%220%200%2096%2096%22%3E%0A%20%20%3Ctitle%3EVoxel%20Worlds%20%E2%80%94%20stepped%20island%3C%2Ftitle%3E%0A%20%20%3Crect%20x%3D%224%22%20y%3D%224%22%20width%3D%2288%22%20height%3D%2288%22%20rx%3D%2223%22%20fill%3D%22%23183e36%22%2F%3E%0A%20%20%3Cpath%20d%3D%22M20%2058%2048%2074%2076%2058v10L48%2084%2020%2068Z%22%20fill%3D%22%23619e9d%22%2F%3E%0A%20%20%3Cpath%20d%3D%22m20%2042%2014-8%2014%208-14%208Z%22%20fill%3D%22%23d8e9a6%22%2F%3E%0A%20%20%3Cpath%20d%3D%22m20%2042%2014%208v20l-14-8Z%22%20fill%3D%22%2371936a%22%2F%3E%0A%20%20%3Cpath%20d%3D%22m34%2050%2014-8v20l-14%208Z%22%20fill%3D%22%23aac785%22%2F%3E%0A%20%20%3Cpath%20d%3D%22m48%2042%2014-8%2014%208-14%208Z%22%20fill%3D%22%23d8e9a6%22%2F%3E%0A%20%20%3Cpath%20d%3D%22m48%2042%2014%208v20l-14-8Z%22%20fill%3D%22%2371936a%22%2F%3E%0A%20%20%3Cpath%20d%3D%22m62%2050%2014-8v20l-14%208Z%22%20fill%3D%22%23aac785%22%2F%3E%0A%20%20%3Cpath%20d%3D%22m34%2024%2014-8%2014%208-14%208Z%22%20fill%3D%22%23f4efce%22%2F%3E%0A%20%20%3Cpath%20d%3D%22m34%2024%2014%208v30l-14-8Z%22%20fill%3D%22%2399b878%22%2F%3E%0A%20%20%3Cpath%20d%3D%22m48%2032%2014-8v30l-14%208Z%22%20fill%3D%22%23d8e9a6%22%2F%3E%0A%3C%2Fsvg%3E%0A"><style>*{box-sizing:border-box} :root{font:13px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;color:#273637;background:#eeeae2;--border:#d8d9ce;--muted:#737d75;--green:#285c50;--accent:#db9e69}body{margin:0;height:100dvh;display:flex;flex-direction:column;overflow:hidden}button,input,textarea,select{font:inherit}button{cursor:pointer;background:#fafbf5;border:1px solid var(--border);color:inherit;padding:8px 12px;border-radius:6px;white-space:nowrap}button:hover{background:#e4e9dd;border-color:#adb9a6}button:disabled{opacity:.4;cursor:default}button.primary{background:var(--green);border-color:var(--green);color:#fff}button.active{background:#d8e8d7;border-color:#a0b89b;color:#204d40}button:focus-visible,input:focus-visible,select:focus-visible,textarea:focus-visible{outline:2px solid #ad7642;outline-offset:2px}[hidden]{display:none!important}header{height:78px;flex-shrink:0;display:flex;gap:24px;align-items:center;padding:0 24px;background:#f9faf3;border-bottom:1px solid var(--border)}.identity{display:flex;gap:10px;align-items:center;font-size:16px;font-weight:750;letter-spacing:2px;min-width:208px}.identity small{display:block;font-size:9px;letter-spacing:2px;font-weight:500;color:var(--muted)}.mark{width:36px;height:36px;display:block}.mark svg{width:100%;height:100%}.project-heading{flex:1;min-width:0}.project-heading strong{font-size:17px;display:block;overflow:hidden;white-space:nowrap;text-overflow:ellipsis}.project-heading span{font-size:11px;color:var(--muted)}nav{display:flex;gap:7px}main{flex:1;min-height:0;display:grid;grid-template-columns:235px minmax(240px,1fr) 250px}aside{background:#f9faf3;overflow:auto;padding:20px 16px}.objects-panel{border-right:1px solid var(--border)}.inspector{border-left:1px solid var(--border)}.panel-title{font-size:10px;letter-spacing:1.7px;font-weight:700;display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;color:#667263}.panel-title button{padding:3px 6px;font-size:10px;letter-spacing:0}.panel-title span{font-size:10px;letter-spacing:0}.search{margin-bottom:14px}input,textarea,select{background:#fffef8;border:1px solid var(--border);border-radius:5px;color:inherit;max-width:100%;padding:7px 9px}input:not([type=color]):not([type=checkbox]):not([type=range]),textarea{width:100%}.object-row{display:flex;gap:6px;align-items:center;margin:3px -7px;border:1px solid transparent;border-radius:6px}.object-row.selected{border-color:#b6c8ad;background:#e8efdf}.object-row>button:first-child{border:0;background:transparent;text-align:left;flex:1;overflow:hidden;text-overflow:ellipsis;padding:9px 5px;font-size:12px;min-width:0}.object-row .dot{display:inline-block;width:8px;height:8px;background:#a3b69a;margin:0 8px 0 5px;border-radius:2px}.object-row button.toggle{border:0;background:none;padding:4px;font-size:11px;opacity:.6}.object-row.hidden-object{opacity:.5}.wide{width:100%;margin-top:9px;font-size:12px}.brief{border-top:1px solid var(--border);margin-top:25px;padding-top:20px}.eyebrow{font-size:9px;letter-spacing:1.8px;color:var(--muted)}.brief p{font-size:11px;line-height:1.75;color:#778170}.brief button{font-size:11px}#object-list{max-height:45vh;overflow:auto}label{display:block;font-size:11px;color:#73806e;margin:13px 0}label input,label select,label textarea{display:block;margin-top:5px;font-size:12px;color:#34483c}.xyz{display:flex;gap:5px}.xyz input{min-width:0;padding:7px 5px}.xyz label{margin:0;flex:1}.inspector .actions{display:flex;gap:5px;margin:12px 0;flex-wrap:wrap}.actions button{font-size:11px;padding:6px 9px}.check{display:flex;align-items:center;gap:7px}.check input{margin:0}.materials,.lighting{border-top:1px solid var(--border);margin-top:22px;padding-top:20px}#palette{display:flex;flex-wrap:wrap;gap:7px}#palette button{width:25px;height:25px;padding:0;border:2px solid #fff;box-shadow:0 0 0 1px #ccd1c7;border-radius:5px}#palette button.active{box-shadow:0 0 0 2px #284c40}#material-editor .color-row{display:flex;gap:8px;align-items:center;margin-top:12px}input[type=color]{height:31px;width:40px;padding:2px;flex-shrink:0}input[type=range]{width:100%;accent-color:var(--green)}.stage{position:relative;min-width:0;overflow:hidden;background:#d2d8cf}#viewport{position:absolute;inset:0;outline:0;touch-action:none}#viewport canvas{width:100%;height:100%;display:block}.modebar{position:absolute;top:18px;left:20px;right:20px;display:flex;gap:7px;pointer-events:none}.modebar button,.modebar .segmented{pointer-events:auto;box-shadow:0 3px 12px #1429220c}.segmented{display:flex;gap:3px;background:#f6f8eeee;border:1px solid #d6ddce;border-radius:8px;padding:3px;margin-right:auto}.segmented button{border:0;padding:6px 13px;box-shadow:none}.modebar>button{background:#f6f8eeed}.tools{position:absolute;bottom:55px;left:50%;transform:translateX(-50%);display:flex;gap:4px;padding:5px;background:#f5f7eef2;box-shadow:0 6px 28px #1b2c2720;border:1px solid #d3ddcd;border-radius:9px}.tools button{border:0;background:transparent;padding:8px 12px;font-size:12px}.tools button.active{background:#d9e5d0}.tools span{border-left:1px solid #d3ddcd;margin:4px}.scene-caption{position:absolute;bottom:0;left:0;right:0;display:flex;justify-content:space-between;gap:15px;padding:12px 18px;background:linear-gradient(transparent,#e2e5dceb);font-size:10px;color:#526559;pointer-events:none}footer{height:35px;padding:0 20px;display:flex;justify-content:space-between;align-items:center;border-top:1px solid var(--border);background:#f9faf3;font-size:11px;flex-shrink:0}footer button{font-size:10px;padding:3px 7px;border:0;background:none}#status{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}dialog{border:1px solid var(--border);border-radius:14px;background:#f9faf3;color:inherit;max-width:540px;width:calc(100% - 36px);padding:28px;box-shadow:0 20px 80px #12251d30}dialog::backdrop{background:#1d30264d;backdrop-filter:blur(4px)}dialog h2{margin:0 0 14px;font-size:23px;letter-spacing:-.7px}dialog p{color:var(--muted);font-size:12px}.dialog-actions{display:flex;justify-content:flex-end;gap:8px}.export-options{display:grid;gap:9px;margin:22px 0}.export-options button{text-align:left;padding:15px 18px}.export-options strong,.export-options span{display:block}.export-options span{font-size:11px;opacity:.75;margin-top:3px}.fine{font-size:11px!important}.notice{background:#f2dfb7;color:#654e28;padding:8px 20px;display:flex;align-items:center;gap:12px;font-size:12px}.notice span{flex:1}.notice button{font-size:11px;padding:4px 8px}#crosshair{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);font-size:24px;color:white;text-shadow:0 1px 4px #000}#walk-overlay{position:absolute;top:80px;left:20px;right:20px;text-align:center;pointer-events:none}#walk-overlay button{pointer-events:auto}#walk-overlay p{color:#fff;text-shadow:0 1px 3px #000;font-size:11px}#tour-stops{display:flex;justify-content:center;gap:7px}#tour-stops button{font-size:11px;background:#f9fbf0d9}#touch-walk{position:absolute;bottom:60px;left:24px;text-align:center;touch-action:none}#touch-walk button{width:44px;height:44px;background:#f4f8eee0;padding:0;font-size:22px;margin:2px}body.walking .objects-panel,body.walking .inspector{display:none}body.walking main{grid-template-columns:1fr}body.readonly nav,body.readonly #edit-mode,body.readonly #snapshot,body.readonly footer button{display:none}body.readonly .identity small{font-size:8px}body.readonly .project-heading span{display:none}@media(max-width:1100px){main{grid-template-columns:190px minmax(240px,1fr) 218px}header{padding:0 16px;gap:16px}.identity{min-width:170px;font-size:14px}.tools button{padding:8px}.scene-caption #interaction-hint{display:none}aside{padding:16px 12px}}@media(max-width:820px){main{grid-template-columns:170px minmax(240px,1fr)}.inspector{display:none}header{height:68px}.identity{min-width:0}.identity>span:last-child{display:none}nav button{font-size:11px;padding:7px 9px}#save-project{display:none}.project-heading strong{font-size:14px}.modebar{left:12px;right:12px;top:12px}.modebar>button{display:none}}@media(max-width:560px){main{grid-template-columns:1fr}.objects-panel{display:none}.tools{bottom:50px;max-width:calc(100% - 16px);width:max-content}.tools button{font-size:11px;padding:7px 9px}header{padding:0 12px;gap:10px}.project-heading span{font-size:10px}footer{padding:0 12px;font-size:10px}.notice{flex-wrap:wrap;font-size:11px}.notice span{min-width:100%}}++body.readonly .objects-panel,body.readonly .inspector{display:none}body.readonly main{grid-template-columns:1fr}+@media(max-width:560px){#save-source:disabled{display:none}}+</style></head><body>+<header><div class="identity"><span class="mark"><svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 96 96">+ <title>Voxel Worlds — stepped island</title>+ <rect x="4" y="4" width="88" height="88" rx="23" fill="#183e36"/>+ <path d="M20 58 48 74 76 58v10L48 84 20 68Z" fill="#619e9d"/>+ <path d="m20 42 14-8 14 8-14 8Z" fill="#d8e9a6"/>+ <path d="m20 42 14 8v20l-14-8Z" fill="#71936a"/>+ <path d="m34 50 14-8v20l-14 8Z" fill="#aac785"/>+ <path d="m48 42 14-8 14 8-14 8Z" fill="#d8e9a6"/>+ <path d="m48 42 14 8v20l-14-8Z" fill="#71936a"/>+ <path d="m62 50 14-8v20l-14 8Z" fill="#aac785"/>+ <path d="m34 24 14-8 14 8-14 8Z" fill="#f4efce"/>+ <path d="m34 24 14 8v30l-14-8Z" fill="#99b878"/>+ <path d="m48 32 14-8v30l-14 8Z" fill="#d8e9a6"/>+</svg>+</span><span>TIDELANDS<small>WORLD STUDIO</small></span></div><div class="project-heading"><strong id="world-title"></strong><span id="save-state">Opening world</span></div><nav><button id="open-project">Open</button><button id="save-project">Save project</button><button id="save-source" class="primary" hidden>Save to workspace</button><button id="deliver" class="primary">Export kit ↗</button></nav></header>+<div id="source-notice" class="notice" hidden><span></span><button id="source-load">Use source version</button><button id="draft-keep">Download my draft</button></div>+<main><aside class="objects-panel"><div class="panel-title">SCENE <span id="object-count"></span></div><div class="search"><input id="object-search" placeholder="Find an object" aria-label="Find an object"></div><div id="object-list"></div><button id="new-object" class="wide">+ New voxel object</button><button id="import-vox" class="wide">↗ Import .vox asset</button><div class="brief"><div class="eyebrow">THE BRIEF</div><p id="brief-text"></p><button id="edit-project">Project & scale</button></div></aside>+<section class="stage"><div id="viewport" tabindex="0" aria-label="Interactive 3D world"></div><div class="modebar"><div class="segmented"><button id="edit-mode" class="active">Build</button><button id="walk-mode">Walk the world</button></div><button id="frame-world" title="Frame the whole world">↗ Frame all</button><button id="snapshot">Save view</button></div><div class="tools" id="edit-tools"><button data-tool="select" class="active" title="Select and move an object">↖ Select</button><button data-tool="add">+ Build</button><button data-tool="erase">− Erase</button><button data-tool="paint">◈ Paint</button><span></span><button id="undo" title="Undo (Command/Ctrl Z)">↶</button><button id="redo" title="Redo (Command/Ctrl Shift Z)">↷</button></div><div id="crosshair" hidden>+</div><div id="walk-overlay" hidden><button id="enter-walk" class="primary">Enter world</button><p>WASD to walk · drag to look · Space to jump · Esc to release</p><div id="tour-stops"></div></div><div id="touch-walk" hidden><button data-move="forward" aria-label="Walk forward">↑</button><div><button data-move="left" aria-label="Walk left">←</button><button data-move="back" aria-label="Walk backward">↓</button><button data-move="right" aria-label="Walk right">→</button><button data-move="jump" aria-label="Jump">↟</button></div></div><div class="scene-caption"><span id="scene-measures"></span><span id="interaction-hint">Drag to orbit · scroll to zoom · click an object</span></div></section>+<aside class="inspector"><div class="panel-title">OBJECT <button id="focus-object">Focus ↗</button></div><div id="object-editor"></div><section class="materials"><div class="panel-title">MATERIALS <button id="new-material">+</button></div><div id="palette"></div><div id="material-editor"></div><label>Brush radius <select id="brush-radius"><option value="0">One voxel</option><option value="1">3 × 3 × 3</option><option value="2">5 × 5 × 5</option></select></label></section><section class="lighting"><div class="panel-title">LIGHT</div><label>Time of day<input id="light" type="range" min="0" max="1" step=".01"></label><label class="check"><input id="cycle-light" type="checkbox"> Let daylight move</label></section></aside></main>+<footer><span id="status" role="status">Ready to shape your world</span><button id="check-routes">Check walking routes</button></footer>+<dialog id="project-dialog"><form method="dialog"><h2>Project & scale</h2><label>Title<input id="project-title" required maxlength="120"></label><label>Your brief<textarea id="project-brief" rows="5" maxlength="12000"></textarea></label><label>Size in voxels<div class="xyz"><input id="size-x" type="number" min="4" max="128" aria-label="World width"><input id="size-y" type="number" min="4" max="128" aria-label="World height"><input id="size-z" type="number" min="4" max="128" aria-label="World depth"></div></label><label>Meters per voxel<input id="project-unit" type="number" min=".01" max="10" step=".01"></label><label>Notes<textarea id="project-notes" rows="3"></textarea></label><p>Changing scale changes the real size of the scene and visitor clearance.</p><div class="dialog-actions"><button value="cancel">Cancel</button><button id="apply-project" type="button" class="primary">Apply</button></div></form></dialog>+<dialog id="export-dialog"><h2>Take your world with you</h2><p id="export-summary"></p><div class="export-options"><button id="export-glb"><strong>3D world · GLB</strong><span>Named meshes and materials, in meters</span></button><button id="export-vox"><strong>Voxel world · VOX</strong><span>Flattened geometry and color palette</span></button><button id="export-walk"><strong>Walkthrough · HTML</strong><span>One offline file to share and explore</span></button><button id="export-kit" class="primary"><strong>Complete editable kit · ZIP</strong><span>3D files, project, studio and walkthrough</span></button></div><p class="fine">GLB keeps visible geometry and materials. VOX merges the scene into one voxel model. Keep the project JSON to retain object structure and project settings.</p><button id="close-export">Close</button></dialog>+<dialog id="open-dialog"><h2>Open a world</h2><p>Open a saved Tidelands project as a draft. Save it to this workspace when you are ready.</p><button id="choose-project">Choose project file…</button><section id="native-open"><label>Or paste the path to a project in your home folder<input id="project-path" placeholder="~/Downloads/my-world.tidelands.json"></label><button id="open-path">Open this project</button><div class="panel-title" style="margin-top:24px">RECENT PROJECTS</div><div id="recent-projects"></div></section><div class="dialog-actions"><button id="close-open">Close</button></div></dialog>+<input id="project-file" type="file" accept=".json,.tidelands.json" hidden><input id="vox-file" type="file" accept=".vox" hidden>+<script id="world-data" type="application/json">{"project":{"spec":"tidelands/2","id":"lantern-quay","title":"Lantern Quay","brief":"An intimate harbor village for a cozy exploration game. A broad public quay leads to a lighthouse, working piers and colorful workshops. Keep buildings separate so they can become a reusable environment kit.","size":[80,48,64],"unit":0.3,"light":0.3,"materials":[{"id":1,"name":"Chalk limestone","color":"#d7ccb4","solid":true,"opacity":1,"emission":0},{"id":2,"name":"Meadow","color":"#75917a","solid":true,"opacity":1,"emission":0},{"id":3,"name":"Harbor water","color":"#537f91","solid":false,"opacity":0.72,"emission":0},{"id":4,"name":"Weathered timber","color":"#8f6750","solid":true,"opacity":1,"emission":0},{"id":5,"name":"Terracotta","color":"#ad6453","solid":true,"opacity":1,"emission":0},{"id":6,"name":"Warm plaster","color":"#eee0bd","solid":true,"opacity":1,"emission":0},{"id":7,"name":"Deep teal trim","color":"#315b5c","solid":true,"opacity":1,"emission":0},{"id":8,"name":"Window glow","color":"#ffd894","solid":true,"opacity":1,"emission":0.7},{"id":9,"name":"Paving","color":"#b4ada2","solid":true,"opacity":1,"emission":0},{"id":10,"name":"Leaves","color":"#436f62","solid":true,"opacity":1,"emission":0},{"id":11,"name":"Lighthouse white","color":"#f6edd8","solid":true,"opacity":1,"emission":0},{"id":12,"name":"Ink metal","color":"#374756","solid":true,"opacity":1,"emission":0}],"objects":[{"id":"headland","name":"Limestone headland","origin":[0,0,0],"size":[56,4,64],"boxes":[[0,0,0,56,3,64,1],[0,3,0,56,1,64,2]],"rotation":0,"hidden":false,"locked":true,"edits":[]},{"id":"water","name":"Tidal water","origin":[56,1,0],"size":[24,2,64],"boxes":[[0,0,0,24,2,64,3]],"rotation":0,"hidden":false,"locked":true,"edits":[]},{"id":"quay","name":"Public promenade","origin":[26,3,0],"size":[30,1,64],"boxes":[[0,0,0,10,1,64,9],[10,0,25,20,1,12,9],[26,0,0,4,1,64,9]],"rotation":0,"hidden":false,"locked":true,"edits":[]},{"id":"bakery","name":"Copper Roof Bakery","origin":[5,4,7],"size":[17,20,15],"boxes":[[0,0,0,17,1,15,4],[0,1,0,17,11,1,6],[0,1,14,17,11,1,6],[0,1,1,1,11,13,6],[16,1,1,1,11,13,6],[7,1,0,3,8,1,0],[2,4,0,3,4,1,8],[12,4,0,3,4,1,8],[0,4,5,1,4,3,8],[16,4,5,1,4,3,8],[7,9,0,3,1,1,7],[0,12,0,17,1,15,5],[0,13,1,17,1,13,5],[0,14,2,17,1,11,5],[0,15,3,17,1,9,5],[0,16,4,17,1,7,5],[0,17,5,17,1,5,5],[2,13,6,2,7,2,1]],"rotation":2,"hidden":false,"locked":false,"edits":[]},{"id":"workshop","name":"Teal Boat Workshop","origin":[5,4,39],"size":[17,20,15],"boxes":[[0,0,0,17,1,15,4],[0,1,0,17,11,1,11],[0,1,14,17,11,1,11],[0,1,1,1,11,13,11],[16,1,1,1,11,13,11],[7,1,0,3,8,1,0],[2,4,0,3,4,1,8],[12,4,0,3,4,1,8],[0,4,5,1,4,3,8],[16,4,5,1,4,3,8],[7,9,0,3,1,1,7],[0,12,0,17,1,15,7],[0,13,1,17,1,13,7],[0,14,2,17,1,11,7],[0,15,3,17,1,9,7],[0,16,4,17,1,7,7],[0,17,5,17,1,5,7],[2,13,6,2,7,2,1]],"rotation":0,"hidden":false,"locked":false,"edits":[]},{"id":"pier","name":"East timber pier","origin":[55,0,28],"size":[23,4,7],"boxes":[[0,3,0,23,1,7,4],[2,0,0,1,3,1,12],[2,0,6,1,3,1,12],[11,0,0,1,3,1,12],[11,0,6,1,3,1,12],[20,0,0,1,3,1,12],[20,0,6,1,3,1,12]],"rotation":0,"hidden":false,"locked":false,"edits":[]},{"id":"lighthouse","name":"Quay lighthouse","origin":[40,4,2],"size":[11,38,11],"boxes":[[0,0,0,11,1,11,1],[2,1,2,7,26,7,11],[3,1,3,5,24,5,0],[4,1,2,3,8,1,0],[2,12,2,7,2,7,5],[3,12,3,5,2,5,0],[1,27,1,9,1,9,7],[3,28,3,5,5,5,8],[1,33,1,9,2,9,7],[3,35,3,5,1,5,7],[5,36,5,1,2,1,12]],"rotation":0,"hidden":false,"locked":false,"edits":[]},{"id":"lantern-1","name":"Quay lantern 1","origin":[37,4,22],"size":[3,11,3],"boxes":[[1,0,1,1,8,1,12],[0,8,0,3,2,3,8],[0,10,0,3,1,3,12]],"rotation":0,"hidden":false,"locked":false,"edits":[]},{"id":"lantern-2","name":"Quay lantern 2","origin":[49,4,22],"size":[3,11,3],"boxes":[[1,0,1,1,8,1,12],[0,8,0,3,2,3,8],[0,10,0,3,1,3,12]],"rotation":0,"hidden":false,"locked":false,"edits":[]},{"id":"lantern-3","name":"Quay lantern 3","origin":[37,4,40],"size":[3,11,3],"boxes":[[1,0,1,1,8,1,12],[0,8,0,3,2,3,8],[0,10,0,3,1,3,12]],"rotation":0,"hidden":false,"locked":false,"edits":[]},{"id":"lantern-4","name":"Quay lantern 4","origin":[49,4,40],"size":[3,11,3],"boxes":[[1,0,1,1,8,1,12],[0,8,0,3,2,3,8],[0,10,0,3,1,3,12]],"rotation":0,"hidden":false,"locked":false,"edits":[]},{"id":"tree-1","name":"Wind shaped tree 1","origin":[1,4,27],"size":[7,15,7],"boxes":[[3,0,3,1,9,1,4],[1,7,1,5,5,5,10],[0,9,2,7,4,3,10],[2,12,2,3,3,3,2]],"rotation":0,"hidden":false,"locked":false,"edits":[]},{"id":"tree-2","name":"Wind shaped tree 2","origin":[18,4,27],"size":[7,15,7],"boxes":[[3,0,3,1,9,1,4],[1,7,1,5,5,5,10],[0,9,2,7,4,3,10],[2,12,2,3,3,3,2]],"rotation":0,"hidden":false,"locked":false,"edits":[]},{"id":"tree-3","name":"Wind shaped tree 3","origin":[43,4,52],"size":[7,15,7],"boxes":[[3,0,3,1,9,1,4],[1,7,1,5,5,5,10],[0,9,2,7,4,3,10],[2,12,2,3,3,3,2]],"rotation":0,"hidden":false,"locked":false,"edits":[]},{"id":"tree-4","name":"Wind shaped tree 4","origin":[36,4,52],"size":[7,15,7],"boxes":[[3,0,3,1,9,1,4],[1,7,1,5,5,5,10],[0,9,2,7,4,3,10],[2,12,2,3,3,3,2]],"rotation":0,"hidden":false,"locked":false,"edits":[]},{"id":"crates","name":"Cargo stack","origin":[42,4,28],"size":[6,6,4],"boxes":[[0,0,0,3,3,3,4],[3,0,1,3,3,3,5],[1,3,1,3,3,3,6]],"rotation":0,"hidden":false,"locked":false,"edits":[]},{"id":"boat","name":"Harbor skiff","origin":[61,1,43],"size":[6,4,15],"boxes":[[1,0,1,4,1,13,7],[0,1,2,1,2,11,5],[5,1,2,1,2,11,5],[1,1,0,4,2,1,5],[1,1,14,4,2,1,5],[1,1,5,4,1,1,4],[1,1,10,4,1,1,4],[2,3,7,1,1,1,12]],"rotation":0,"hidden":false,"locked":false,"edits":[]}],"spawn":{"position":[31.5,4,46.5],"yaw":3.141592653589793},"stops":[{"id":"quay","name":"The public quay","description":"Workshops face a generous walking street.","position":[30.5,4,29.5]},{"id":"pier","name":"East pier","description":"A removable pier module, ready for another scene.","position":[67.5,4,31.5]},{"id":"beacon","name":"Lighthouse court","description":"The beacon keeps its own identity in the 3D export.","position":[47.5,4,15.5]}],"notes":"One voxel is 30 cm. Visitor height 1.7 m. Buildings and props are independently editable. Synthetic authored example; not a generated user commission.","revision":"892bf6367fff5842ed5f9a31c9bb7290f085025d81a8e63431e3f8d510fe606b"},"mode":"edit"}</script><script>(()=>{var Cn={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},Ei={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},jh=0,$l=1,Jh=2;var Rr=1,la=2,zs=3,Ti=0,Ze=1,_n=2,Hn=0,ks=1,Kl=2,Ql=3,tc=4,$h=5;var Yi=100,Kh=101,Qh=102,tu=103,eu=104,nu=200,iu=201,su=202,ru=203,ec=204,nc=205,ou=206,au=207,lu=208,cu=209,hu=210,uu=211,du=212,fu=213,pu=214,Ro=0,Po=1,Io=2,As=3,Lo=4,Do=5,No=6,Uo=7,ic=0,mu=1,gu=2,Rn=0,sc=1,rc=2,oc=3,Pr=4,ac=5,lc=6,cc=7;var hc=300,Ai=301,qi=302,ca=303,ha=304,Ir=306,Fo=1e3,zn=1001,Oo=1002,De=1003,_u=1004;var Lr=1005;var Fe=1006,ua=1007;var Ci=1008;var Qe=1009,uc=1010,dc=1011,Vs=1012,da=1013,Pn=1014,In=1015,Ln=1016,fa=1017,pa=1018,Hs=1020,fc=35902,pc=35899,mc=1021,gc=1022,xn=1023,kn=1026,Ri=1027,_c=1028,ma=1029,Pi=1030,ga=1031;var _a=1033,Dr=33776,Nr=33777,Ur=33778,Fr=33779,xa=35840,ya=35841,va=35842,Ma=35843,Sa=36196,ba=37492,wa=37496,Ea=37488,Ta=37489,Or=37490,Aa=37491,Ca=37808,Ra=37809,Pa=37810,Ia=37811,La=37812,Da=37813,Na=37814,Ua=37815,Fa=37816,Oa=37817,Ba=37818,za=37819,ka=37820,Va=37821,Ha=36492,Ga=36494,Wa=36495,Xa=36283,Ya=36284,Br=36285,qa=36286;var lr=2300,Bo=2301,Ao=2302,Hl=2303,Gl=2400,Wl=2401,Xl=2402;var xu=3200;var Za=0,yu=1,si="",qe="srgb",cr="srgb-linear",hr="linear",Qt="srgb";var Co=7680;var vu=519,Mu=512,Su=513,bu=514,ja=515,wu=516,Eu=517,Ja=518,Tu=519,Au=35044;var xc="300 es",wn=2e3,Cs=2001;function Jd(i){for(let t=i.length-1;t>=0;--t)if(i[t]>=65535)return!0;return!1}function $d(i){return ArrayBuffer.isView(i)&&!(i instanceof DataView)}function ur(i){return document.createElementNS("http://www.w3.org/1999/xhtml",i)}function Cu(){let i=ur("canvas");return i.style.display="block",i}var Mh={},Rs=null;function yc(...i){let t="THREE."+i.shift();Rs?Rs("log",t,...i):console.log(t,...i)}function Ru(i){let t=i[0];if(typeof t=="string"&&t.startsWith("TSL:")){let e=i[1];e&&e.isStackTrace?i[0]+=" "+e.getLocation():i[1]='Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.'}return i}function It(...i){i=Ru(i);let t="THREE."+i.shift();if(Rs)Rs("warn",t,...i);else{let e=i[0];e&&e.isStackTrace?console.warn(e.getError(t)):console.warn(t,...i)}}function Dt(...i){i=Ru(i);let t="THREE."+i.shift();if(Rs)Rs("error",t,...i);else{let e=i[0];e&&e.isStackTrace?console.error(e.getError(t)):console.error(t,...i)}}function Hi(...i){let t=i.join(" ");t in Mh||(Mh[t]=!0,It(...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 Iu={[Ro]:Po,[Io]:No,[Lo]:Uo,[As]:Do,[Po]:Ro,[No]:Io,[Uo]:Lo,[Do]:As},En=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<o;r++)s[r].call(this,t);t.target=null}}},ke=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"],Sh=1234567,or=Math.PI/180,Ps=180/Math.PI;function Gs(){let i=Math.random()*4294967295|0,t=Math.random()*4294967295|0,e=Math.random()*4294967295|0,n=Math.random()*4294967295|0;return(ke[i&255]+ke[i>>8&255]+ke[i>>16&255]+ke[i>>24&255]+"-"+ke[t&255]+ke[t>>8&255]+"-"+ke[t>>16&15|64]+ke[t>>24&255]+"-"+ke[e&63|128]+ke[e>>8&255]+"-"+ke[e>>16&255]+ke[e>>24&255]+ke[n&255]+ke[n>>8&255]+ke[n>>16&255]+ke[n>>24&255]).toLowerCase()}function Vt(i,t,e){return Math.max(t,Math.min(e,i))}function vc(i,t){return(i%t+t)%t}function Kd(i,t,e,n,s){return n+(i-t)*(s-n)/(e-t)}function Qd(i,t,e){return i!==t?(e-i)/(t-i):0}function ar(i,t,e){return(1-e)*i+e*t}function tf(i,t,e,n){return ar(i,t,1-Math.exp(-e*n))}function ef(i,t=1){return t-Math.abs(vc(i,t*2)-t)}function nf(i,t,e){return i<=t?0:i>=e?1:(i=(i-t)/(e-t),i*i*(3-2*i))}function sf(i,t,e){return i<=t?0:i>=e?1:(i=(i-t)/(e-t),i*i*i*(i*(i*6-15)+10))}function rf(i,t){return i+Math.floor(Math.random()*(t-i+1))}function of(i,t){return i+Math.random()*(t-i)}function af(i){return i*(.5-Math.random())}function lf(i){i!==void 0&&(Sh=i);let t=Sh+=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 cf(i){return i*or}function hf(i){return i*Ps}function uf(i){return i>0&&Number.isInteger(i)&&2**Math.round(Math.log2(i))===i}function df(i){return Math.pow(2,Math.ceil(Math.log(i)/Math.LN2))}function ff(i){return Math.pow(2,Math.floor(Math.log(i)/Math.LN2))}function pf(i,t,e,n,s){let r=Math.cos,o=Math.sin,a=r(e/2),c=o(e/2),l=r((t+n)/2),u=o((t+n)/2),f=r((t-n)/2),h=o((t-n)/2),p=r((n-t)/2),g=o((n-t)/2);switch(s){case"XYX":i.set(a*u,c*f,c*h,a*l);break;case"YZY":i.set(c*h,a*u,c*f,a*l);break;case"ZXZ":i.set(c*f,c*h,a*u,a*l);break;case"XZX":i.set(a*u,c*g,c*p,a*l);break;case"YXY":i.set(c*p,a*u,c*g,a*l);break;case"ZYZ":i.set(c*g,c*p,a*u,a*l);break;default:It("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+s)}}function Es(i,t){switch(t.constructor){case Float32Array:return i;case Uint32Array:return i/4294967295;case Uint16Array:return i/65535;case Uint8Array:case Uint8ClampedArray: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("THREE.MathUtils: Invalid component type.")}}function Ye(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:case Uint8ClampedArray: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("THREE.MathUtils: Invalid component type.")}}var Mc={DEG2RAD:or,RAD2DEG:Ps,generateUUID:Gs,clamp:Vt,euclideanModulo:vc,mapLinear:Kd,inverseLerp:Qd,lerp:ar,damp:tf,pingpong:ef,smoothstep:nf,smootherstep:sf,randInt:rf,randFloat:of,randFloatSpread:af,seededRandom:lf,degToRad:cf,radToDeg:hf,isPowerOfTwo:uf,ceilPowerOfTwo:df,floorPowerOfTwo:ff,setQuaternionFromProperEuler:pf,normalize:Ye,denormalize:Es},Pt=class i{static{i.prototype.isVector2=!0}constructor(t=0,e=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("THREE.Vector2: 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("THREE.Vector2: 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=Vt(this.x,t.x,e.x),this.y=Vt(this.y,t.y,e.y),this}clampScalar(t,e){return this.x=Vt(this.x,t,e),this.y=Vt(this.y,t,e),this}clampLength(t,e){let n=this.length();return this.divideScalar(n||1).multiplyScalar(Vt(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(Vt(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}},pe=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 c=n[s+0],l=n[s+1],u=n[s+2],f=n[s+3],h=r[o+0],p=r[o+1],g=r[o+2],v=r[o+3];if(f!==v||c!==h||l!==p||u!==g){let m=c*h+l*p+u*g+f*v;m<0&&(h=-h,p=-p,g=-g,v=-v,m=-m);let d=1-a;if(m<.9995){let S=Math.acos(m),T=Math.sin(S);d=Math.sin(d*S)/T,a=Math.sin(a*S)/T,c=c*d+h*a,l=l*d+p*a,u=u*d+g*a,f=f*d+v*a}else{c=c*d+h*a,l=l*d+p*a,u=u*d+g*a,f=f*d+v*a;let S=1/Math.sqrt(c*c+l*l+u*u+f*f);c*=S,l*=S,u*=S,f*=S}}t[e]=c,t[e+1]=l,t[e+2]=u,t[e+3]=f}static multiplyQuaternionsFlat(t,e,n,s,r,o){let a=n[s],c=n[s+1],l=n[s+2],u=n[s+3],f=r[o],h=r[o+1],p=r[o+2],g=r[o+3];return t[e]=a*g+u*f+c*p-l*h,t[e+1]=c*g+u*h+l*f-a*p,t[e+2]=l*g+u*p+a*h-c*f,t[e+3]=u*g-a*f-c*h-l*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,c=Math.sin,l=a(n/2),u=a(s/2),f=a(r/2),h=c(n/2),p=c(s/2),g=c(r/2);switch(o){case"XYZ":this._x=h*u*f+l*p*g,this._y=l*p*f-h*u*g,this._z=l*u*g+h*p*f,this._w=l*u*f-h*p*g;break;case"YXZ":this._x=h*u*f+l*p*g,this._y=l*p*f-h*u*g,this._z=l*u*g-h*p*f,this._w=l*u*f+h*p*g;break;case"ZXY":this._x=h*u*f-l*p*g,this._y=l*p*f+h*u*g,this._z=l*u*g+h*p*f,this._w=l*u*f-h*p*g;break;case"ZYX":this._x=h*u*f-l*p*g,this._y=l*p*f+h*u*g,this._z=l*u*g-h*p*f,this._w=l*u*f+h*p*g;break;case"YZX":this._x=h*u*f+l*p*g,this._y=l*p*f+h*u*g,this._z=l*u*g-h*p*f,this._w=l*u*f-h*p*g;break;case"XZY":this._x=h*u*f-l*p*g,this._y=l*p*f-h*u*g,this._z=l*u*g+h*p*f,this._w=l*u*f+h*p*g;break;default:It("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],c=e[9],l=e[2],u=e[6],f=e[10],h=n+a+f;if(h>0){let p=.5/Math.sqrt(h+1);this._w=.25/p,this._x=(u-c)*p,this._y=(r-l)*p,this._z=(o-s)*p}else if(n>a&&n>f){let p=2*Math.sqrt(1+n-a-f);this._w=(u-c)/p,this._x=.25*p,this._y=(s+o)/p,this._z=(r+l)/p}else if(a>f){let p=2*Math.sqrt(1+a-n-f);this._w=(r-l)/p,this._x=(s+o)/p,this._y=.25*p,this._z=(c+u)/p}else{let p=2*Math.sqrt(1+f-n-a);this._w=(o-s)/p,this._x=(r+l)/p,this._y=(c+u)/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(Vt(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,c=e._y,l=e._z,u=e._w;return this._x=n*u+o*a+s*l-r*c,this._y=s*u+o*c+r*a-n*l,this._z=r*u+o*l+n*c-s*a,this._w=o*u-n*a-s*c-r*l,this._onChangeCallback(),this}slerp(t,e){let n=t._x,s=t._y,r=t._z,o=t._w,a=this.dot(t);a<0&&(n=-n,s=-s,r=-r,o=-o,a=-a);let c=1-e;if(a<.9995){let l=Math.acos(a),u=Math.sin(l);c=Math.sin(c*l)/u,e=Math.sin(e*l)/u,this._x=this._x*c+n*e,this._y=this._y*c+s*e,this._z=this._z*c+r*e,this._w=this._w*c+o*e,this._onChangeCallback()}else this._x=this._x*c+n*e,this._y=this._y*c+s*e,this._z=this._z*c+r*e,this._w=this._w*c+o*e,this.normalize();return 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}},P=class i{static{i.prototype.isVector3=!0}constructor(t=0,e=0,n=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("THREE.Vector3: 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("THREE.Vector3: 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(bh.setFromEuler(t))}applyAxisAngle(t,e){return this.applyQuaternion(bh.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,c=t.w,l=2*(o*s-a*n),u=2*(a*e-r*s),f=2*(r*n-o*e);return this.x=e+c*l+o*f-a*u,this.y=n+c*u+a*l-r*f,this.z=s+c*f+r*u-o*l,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=Vt(this.x,t.x,e.x),this.y=Vt(this.y,t.y,e.y),this.z=Vt(this.z,t.z,e.z),this}clampScalar(t,e){return this.x=Vt(this.x,t,e),this.y=Vt(this.y,t,e),this.z=Vt(this.z,t,e),this}clampLength(t,e){let n=this.length();return this.divideScalar(n||1).multiplyScalar(Vt(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,c=e.z;return this.x=s*c-r*a,this.y=r*o-n*c,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 vl.copy(this).projectOnVector(t),this.sub(vl)}reflect(t){return this.sub(vl.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(Vt(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}},vl=new P,bh=new pe,Ut=class i{static{i.prototype.isMatrix3=!0}constructor(t,e,n,s,r,o,a,c,l){this.elements=[1,0,0,0,1,0,0,0,1],t!==void 0&&this.set(t,e,n,s,r,o,a,c,l)}set(t,e,n,s,r,o,a,c,l){let u=this.elements;return u[0]=t,u[1]=s,u[2]=a,u[3]=e,u[4]=r,u[5]=c,u[6]=n,u[7]=o,u[8]=l,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],c=n[6],l=n[1],u=n[4],f=n[7],h=n[2],p=n[5],g=n[8],v=s[0],m=s[3],d=s[6],S=s[1],T=s[4],y=s[7],b=s[2],w=s[5],C=s[8];return r[0]=o*v+a*S+c*b,r[3]=o*m+a*T+c*w,r[6]=o*d+a*y+c*C,r[1]=l*v+u*S+f*b,r[4]=l*m+u*T+f*w,r[7]=l*d+u*y+f*C,r[2]=h*v+p*S+g*b,r[5]=h*m+p*T+g*w,r[8]=h*d+p*y+g*C,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],c=t[6],l=t[7],u=t[8];return e*o*u-e*a*l-n*r*u+n*a*c+s*r*l-s*o*c}invert(){let t=this.elements,e=t[0],n=t[1],s=t[2],r=t[3],o=t[4],a=t[5],c=t[6],l=t[7],u=t[8],f=u*o-a*l,h=a*c-u*r,p=l*r-o*c,g=e*f+n*h+s*p;if(g===0)return this.set(0,0,0,0,0,0,0,0,0);let v=1/g;return t[0]=f*v,t[1]=(s*l-u*n)*v,t[2]=(a*n-s*o)*v,t[3]=h*v,t[4]=(u*e-s*c)*v,t[5]=(s*r-a*e)*v,t[6]=p*v,t[7]=(n*c-l*e)*v,t[8]=(o*e-n*r)*v,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 c=Math.cos(r),l=Math.sin(r);return this.set(n*c,n*l,-n*(c*o+l*a)+o+t,-s*l,s*c,-s*(-l*o+c*a)+a+e,0,0,1),this}scale(t,e){return Hi("Matrix3: .scale() is deprecated. Use .makeScale() instead."),this.premultiply(Ml.makeScale(t,e)),this}rotate(t){return Hi("Matrix3: .rotate() is deprecated. Use .makeRotation() instead."),this.premultiply(Ml.makeRotation(-t)),this}translate(t,e){return Hi("Matrix3: .translate() is deprecated. Use .makeTranslation() instead."),this.premultiply(Ml.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)}},Ml=new Ut,wh=new Ut().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),Eh=new Ut().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function mf(){let i={enabled:!0,workingColorSpace:cr,spaces:{},convert:function(s,r,o){return this.enabled===!1||r===o||!r||!o||(this.spaces[r].transfer===Qt&&(s.r=ti(s.r),s.g=ti(s.g),s.b=ti(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===Qt&&(s.r=Ts(s.r),s.g=Ts(s.g),s.b=Ts(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===si?hr: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 Hi("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),i.workingToColorSpace(s,r)},toWorkingColorSpace:function(s,r){return Hi("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({[cr]:{primaries:t,whitePoint:n,transfer:hr,toXYZ:wh,fromXYZ:Eh,luminanceCoefficients:e,workingColorSpaceConfig:{unpackColorSpace:qe},outputColorSpaceConfig:{drawingBufferColorSpace:qe}},[qe]:{primaries:t,whitePoint:n,transfer:Qt,toXYZ:wh,fromXYZ:Eh,luminanceCoefficients:e,outputColorSpaceConfig:{drawingBufferColorSpace:qe}}}),i}var Xt=mf();function ti(i){return i<.04045?i*.0773993808:Math.pow(i*.9478672986+.0521327014,2.4)}function Ts(i){return i<.0031308?i*12.92:1.055*Math.pow(i,.41666)-.055}var ds,zo=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{ds===void 0&&(ds=ur("canvas")),ds.width=t.width,ds.height=t.height;let s=ds.getContext("2d");t instanceof ImageData?s.putImageData(t,0,0):s.drawImage(t,0,0,t.width,t.height),n=ds}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=ur("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;o<r.length;o++)r[o]=ti(r[o]/255)*255;return n.putImageData(s,0,0),e}else if(t.data){let e=t.data.slice(0);for(let n=0;n<e.length;n++)e instanceof Uint8Array||e instanceof Uint8ClampedArray?e[n]=Math.floor(ti(e[n]/255)*255):e[n]=ti(e[n]);return{data:e,width:t.width,height:t.height}}else return It("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),t}},gf=0,Is=class{constructor(t=null){this.isTextureSource=!0,Object.defineProperty(this,"id",{value:gf++}),this.uuid=Gs(),this.data=t,this.dataReady=!0,this.version=0}getSize(t){let e=this.data;return typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement?t.set(e.videoWidth,e.videoHeight,0):typeof VideoFrame<"u"&&e instanceof VideoFrame?t.set(e.displayWidth,e.displayHeight,0):e!==null?t.set(e.width,e.height,e.depth||0):t.set(0,0,0),t}set needsUpdate(t){t===!0&&this.version++}toJSON(t){let e=t===void 0||typeof t=="string";if(!e&&t.images[this.uuid]!==void 0)return t.images[this.uuid];let n={uuid:this.uuid,url:""},s=this.data;if(s!==null){let r;if(Array.isArray(s)){r=[];for(let o=0,a=s.length;o<a;o++)s[o].isDataTexture?r.push(Sl(s[o].image)):r.push(Sl(s[o]))}else r=Sl(s);n.url=r}return e||(t.images[this.uuid]=n),n}};function Sl(i){return typeof HTMLImageElement<"u"&&i instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&i instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&i instanceof ImageBitmap?zo.getDataURL(i):i.data?{data:Array.from(i.data),width:i.width,height:i.height,type:i.data.constructor.name}:(It("Texture: Unable to serialize Texture."),{})}var _f=0,bl=new P,$e=class i extends En{constructor(t=i.DEFAULT_IMAGE,e=i.DEFAULT_MAPPING,n=zn,s=zn,r=Fe,o=Ci,a=xn,c=Qe,l=i.DEFAULT_ANISOTROPY,u=si){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:_f++}),this.uuid=Gs(),this.name="",this.source=new Is(t),this.mipmaps=[],this.mapping=e,this.channel=0,this.wrapS=n,this.wrapT=s,this.magFilter=r,this.minFilter=o,this.anisotropy=l,this.format=a,this.internalFormat=null,this.type=c,this.offset=new Pt(0,0),this.repeat=new Pt(1,1),this.center=new Pt(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new Ut,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=u,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(t&&t.depth&&t.depth>1),this.pmremVersion=0,this.normalized=!1}get width(){return this.source.getSize(bl).x}get height(){return this.source.getSize(bl).y}get depth(){return this.source.getSize(bl).z}get image(){return this.source.data}set image(t){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.normalized=t.normalized,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){It(`Texture.setValues(): parameter '${e}' has value of undefined.`);continue}let s=this[e];if(s===void 0){It(`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,normalized:this.normalized,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!==hc)return t;if(t.applyMatrix3(this.matrix),t.x<0||t.x>1)switch(this.wrapS){case Fo:t.x=t.x-Math.floor(t.x);break;case zn:t.x=t.x<0?0:1;break;case Oo: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 Fo:t.y=t.y-Math.floor(t.y);break;case zn:t.y=t.y<0?0:1;break;case Oo: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++}};$e.DEFAULT_IMAGE=null;$e.DEFAULT_MAPPING=hc;$e.DEFAULT_ANISOTROPY=1;var me=class i{static{i.prototype.isVector4=!0}constructor(t=0,e=0,n=0,s=1){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("THREE.Vector4: 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("THREE.Vector4: 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,c=t.elements,l=c[0],u=c[4],f=c[8],h=c[1],p=c[5],g=c[9],v=c[2],m=c[6],d=c[10];if(Math.abs(u-h)<.01&&Math.abs(f-v)<.01&&Math.abs(g-m)<.01){if(Math.abs(u+h)<.1&&Math.abs(f+v)<.1&&Math.abs(g+m)<.1&&Math.abs(l+p+d-3)<.1)return this.set(1,0,0,0),this;e=Math.PI;let T=(l+1)/2,y=(p+1)/2,b=(d+1)/2,w=(u+h)/4,C=(f+v)/4,_=(g+m)/4;return T>y&&T>b?T<.01?(n=0,s=.707106781,r=.707106781):(n=Math.sqrt(T),s=w/n,r=C/n):y>b?y<.01?(n=.707106781,s=0,r=.707106781):(s=Math.sqrt(y),n=w/s,r=_/s):b<.01?(n=.707106781,s=.707106781,r=0):(r=Math.sqrt(b),n=C/r,s=_/r),this.set(n,s,r,e),this}let S=Math.sqrt((m-g)*(m-g)+(f-v)*(f-v)+(h-u)*(h-u));return Math.abs(S)<.001&&(S=1),this.x=(m-g)/S,this.y=(f-v)/S,this.z=(h-u)/S,this.w=Math.acos((l+p+d-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=Vt(this.x,t.x,e.x),this.y=Vt(this.y,t.y,e.y),this.z=Vt(this.z,t.z,e.z),this.w=Vt(this.w,t.w,e.w),this}clampScalar(t,e){return this.x=Vt(this.x,t,e),this.y=Vt(this.y,t,e),this.z=Vt(this.z,t,e),this.w=Vt(this.w,t,e),this}clampLength(t,e){let n=this.length();return this.divideScalar(n||1).multiplyScalar(Vt(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}},ko=class extends En{constructor(t=1,e=1,n={}){super(),n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Fe,depthBuffer:!0,stencilBuffer:!1,resolveColorBuffer:!0,resolveDepthBuffer:!0,resolveStencilBuffer:!0,storeMultisampledColorBuffer:!0,storeMultisampledDepthBuffer:!0,storeMultisampledStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1,useArrayDepthTexture:!1},n),this.isRenderTarget=!0,this.width=t,this.height=e,this.depth=n.depth,this.scissor=new me(0,0,t,e),this.scissorTest=!1,this.viewport=new me(0,0,t,e),this.textures=[];let s={width:t,height:e,depth:n.depth},r=new $e(s),o=n.count;for(let a=0;a<o;a++)this.textures[a]=r.clone(),this.textures[a].isRenderTargetTexture=!0,this.textures[a].renderTarget=this;this._setTextureOptions(n),this.depthBuffer=n.depthBuffer,this.stencilBuffer=n.stencilBuffer,this.resolveColorBuffer=n.resolveColorBuffer,this.resolveDepthBuffer=n.resolveDepthBuffer,this.resolveStencilBuffer=n.resolveStencilBuffer,this.storeMultisampledColorBuffer=n.storeMultisampledColorBuffer,this.storeMultisampledDepthBuffer=n.storeMultisampledDepthBuffer,this.storeMultisampledStencilBuffer=n.storeMultisampledStencilBuffer,this._depthTexture=null,this.depthTexture=n.depthTexture,this.samples=n.samples,this.multiview=n.multiview,this.useArrayDepthTexture=n.useArrayDepthTexture}_setTextureOptions(t={}){let e={minFilter:Fe,generateMipmaps:!1,flipY:!1,internalFormat:null};t.mapping!==void 0&&(e.mapping=t.mapping),t.wrapS!==void 0&&(e.wrapS=t.wrapS),t.wrapT!==void 0&&(e.wrapT=t.wrapT),t.wrapR!==void 0&&(e.wrapR=t.wrapR),t.magFilter!==void 0&&(e.magFilter=t.magFilter),t.minFilter!==void 0&&(e.minFilter=t.minFilter),t.format!==void 0&&(e.format=t.format),t.type!==void 0&&(e.type=t.type),t.anisotropy!==void 0&&(e.anisotropy=t.anisotropy),t.colorSpace!==void 0&&(e.colorSpace=t.colorSpace),t.flipY!==void 0&&(e.flipY=t.flipY),t.generateMipmaps!==void 0&&(e.generateMipmaps=t.generateMipmaps),t.internalFormat!==void 0&&(e.internalFormat=t.internalFormat);for(let n=0;n<this.textures.length;n++)this.textures[n].setValues(e)}get texture(){return this.textures[0]}set texture(t){this.textures[0]=t}set depthTexture(t){this._depthTexture!==null&&this._depthTexture.renderTarget===this&&(this._depthTexture.renderTarget=null),t!==null&&t.renderTarget===null&&(t.renderTarget=this),this._depthTexture=t}get depthTexture(){return this._depthTexture}setSize(t,e,n=1){if(this.width!==t||this.height!==e||this.depth!==n){this.width=t,this.height=e,this.depth=n;for(let s=0,r=this.textures.length;s<r;s++)this.textures[s].image.width=t,this.textures[s].image.height=e,this.textures[s].image.depth=n,this.textures[s].isData3DTexture!==!0&&(this.textures[s].isArrayTexture=this.textures[s].image.depth>1);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<n;e++){this.textures[e]=t.textures[e].clone(),this.textures[e].isRenderTargetTexture=!0,this.textures[e].renderTarget=this;let s=Object.assign({},t.textures[e].image);this.textures[e].source=new Is(s)}if(this.depthBuffer=t.depthBuffer,this.stencilBuffer=t.stencilBuffer,this.resolveColorBuffer=t.resolveColorBuffer,this.resolveDepthBuffer=t.resolveDepthBuffer,this.resolveStencilBuffer=t.resolveStencilBuffer,this.storeMultisampledColorBuffer=t.storeMultisampledColorBuffer,this.storeMultisampledDepthBuffer=t.storeMultisampledDepthBuffer,this.storeMultisampledStencilBuffer=t.storeMultisampledStencilBuffer,t.depthTexture!==null)if(t.depthTexture.renderTarget===t){let e=t.depthTexture.clone();e.renderTarget=null,this.depthTexture=e}else this.depthTexture=t.depthTexture;return this.samples=t.samples,this.multiview=t.multiview,this.useArrayDepthTexture=t.useArrayDepthTexture,this}dispose(){this.dispatchEvent({type:"dispose"})}},Ke=class extends ko{constructor(t=1,e=1,n={}){super(t,e,n),this.isWebGLRenderTarget=!0}},dr=class extends $e{constructor(t=null,e=1,n=1,s=1){super(null),this.isDataArrayTexture=!0,this.image={data:t,width:e,height:n,depth:s},this.magFilter=De,this.minFilter=De,this.wrapR=zn,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}copy(t){return super.copy(t),this.wrapR=t.wrapR,this}addLayerUpdate(t){this.layerUpdates.add(t)}clearLayerUpdates(){this.layerUpdates.clear()}};var Vo=class extends $e{constructor(t=null,e=1,n=1,s=1){super(null),this.isData3DTexture=!0,this.image={data:t,width:e,height:n,depth:s},this.magFilter=De,this.minFilter=De,this.wrapR=zn,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}copy(t){return super.copy(t),this.wrapR=t.wrapR,this}};var se=class i{static{i.prototype.isMatrix4=!0}constructor(t,e,n,s,r,o,a,c,l,u,f,h,p,g,v,m){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,c,l,u,f,h,p,g,v,m)}set(t,e,n,s,r,o,a,c,l,u,f,h,p,g,v,m){let d=this.elements;return d[0]=t,d[4]=e,d[8]=n,d[12]=s,d[1]=r,d[5]=o,d[9]=a,d[13]=c,d[2]=l,d[6]=u,d[10]=f,d[14]=h,d[3]=p,d[7]=g,d[11]=v,d[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 this.determinantAffine()===0?(t.set(1,0,0),e.set(0,1,0),n.set(0,0,1),this):(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){if(t.determinantAffine()===0)return this.identity();let e=this.elements,n=t.elements,s=1/fs.setFromMatrixColumn(t,0).length(),r=1/fs.setFromMatrixColumn(t,1).length(),o=1/fs.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),c=Math.cos(s),l=Math.sin(s),u=Math.cos(r),f=Math.sin(r);if(t.order==="XYZ"){let h=o*u,p=o*f,g=a*u,v=a*f;e[0]=c*u,e[4]=-c*f,e[8]=l,e[1]=p+g*l,e[5]=h-v*l,e[9]=-a*c,e[2]=v-h*l,e[6]=g+p*l,e[10]=o*c}else if(t.order==="YXZ"){let h=c*u,p=c*f,g=l*u,v=l*f;e[0]=h+v*a,e[4]=g*a-p,e[8]=o*l,e[1]=o*f,e[5]=o*u,e[9]=-a,e[2]=p*a-g,e[6]=v+h*a,e[10]=o*c}else if(t.order==="ZXY"){let h=c*u,p=c*f,g=l*u,v=l*f;e[0]=h-v*a,e[4]=-o*f,e[8]=g+p*a,e[1]=p+g*a,e[5]=o*u,e[9]=v-h*a,e[2]=-o*l,e[6]=a,e[10]=o*c}else if(t.order==="ZYX"){let h=o*u,p=o*f,g=a*u,v=a*f;e[0]=c*u,e[4]=g*l-p,e[8]=h*l+v,e[1]=c*f,e[5]=v*l+h,e[9]=p*l-g,e[2]=-l,e[6]=a*c,e[10]=o*c}else if(t.order==="YZX"){let h=o*c,p=o*l,g=a*c,v=a*l;e[0]=c*u,e[4]=v-h*f,e[8]=g*f+p,e[1]=f,e[5]=o*u,e[9]=-a*u,e[2]=-l*u,e[6]=p*f+g,e[10]=h-v*f}else if(t.order==="XZY"){let h=o*c,p=o*l,g=a*c,v=a*l;e[0]=c*u,e[4]=-f,e[8]=l*u,e[1]=h*f+v,e[5]=o*u,e[9]=p*f-g,e[2]=g*f-p,e[6]=a*u,e[10]=v*f+h}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(xf,t,yf)}lookAt(t,e,n){let s=this.elements;return on.subVectors(t,e),on.lengthSq()===0&&(on.z=1),on.normalize(),di.crossVectors(n,on),di.lengthSq()===0&&(Math.abs(n.z)===1?on.x+=1e-4:on.z+=1e-4,on.normalize(),di.crossVectors(n,on)),di.normalize(),ro.crossVectors(on,di),s[0]=di.x,s[4]=ro.x,s[8]=on.x,s[1]=di.y,s[5]=ro.y,s[9]=on.y,s[2]=di.z,s[6]=ro.z,s[10]=on.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],c=n[8],l=n[12],u=n[1],f=n[5],h=n[9],p=n[13],g=n[2],v=n[6],m=n[10],d=n[14],S=n[3],T=n[7],y=n[11],b=n[15],w=s[0],C=s[4],_=s[8],E=s[12],R=s[1],L=s[5],F=s[9],z=s[13],I=s[2],O=s[6],G=s[10],X=s[14],et=s[3],Y=s[7],K=s[11],nt=s[15];return r[0]=o*w+a*R+c*I+l*et,r[4]=o*C+a*L+c*O+l*Y,r[8]=o*_+a*F+c*G+l*K,r[12]=o*E+a*z+c*X+l*nt,r[1]=u*w+f*R+h*I+p*et,r[5]=u*C+f*L+h*O+p*Y,r[9]=u*_+f*F+h*G+p*K,r[13]=u*E+f*z+h*X+p*nt,r[2]=g*w+v*R+m*I+d*et,r[6]=g*C+v*L+m*O+d*Y,r[10]=g*_+v*F+m*G+d*K,r[14]=g*E+v*z+m*X+d*nt,r[3]=S*w+T*R+y*I+b*et,r[7]=S*C+T*L+y*O+b*Y,r[11]=S*_+T*F+y*G+b*K,r[15]=S*E+T*z+y*X+b*nt,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],c=t[9],l=t[13],u=t[2],f=t[6],h=t[10],p=t[14],g=t[3],v=t[7],m=t[11],d=t[15],S=c*p-l*h,T=a*p-l*f,y=a*h-c*f,b=o*p-l*u,w=o*h-c*u,C=o*f-a*u;return e*(v*S-m*T+d*y)-n*(g*S-m*b+d*w)+s*(g*T-v*b+d*C)-r*(g*y-v*w+m*C)}determinantAffine(){let t=this.elements,e=t[0],n=t[4],s=t[8],r=t[1],o=t[5],a=t[9],c=t[2],l=t[6],u=t[10];return e*(o*u-a*l)-n*(r*u-a*c)+s*(r*l-o*c)}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],c=t[6],l=t[7],u=t[8],f=t[9],h=t[10],p=t[11],g=t[12],v=t[13],m=t[14],d=t[15],S=e*a-n*o,T=e*c-s*o,y=e*l-r*o,b=n*c-s*a,w=n*l-r*a,C=s*l-r*c,_=u*v-f*g,E=u*m-h*g,R=u*d-p*g,L=f*m-h*v,F=f*d-p*v,z=h*d-p*m,I=S*z-T*F+y*L+b*R-w*E+C*_;if(I===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);let O=1/I;return t[0]=(a*z-c*F+l*L)*O,t[1]=(s*F-n*z-r*L)*O,t[2]=(v*C-m*w+d*b)*O,t[3]=(h*w-f*C-p*b)*O,t[4]=(c*R-o*z-l*E)*O,t[5]=(e*z-s*R+r*E)*O,t[6]=(m*y-g*C-d*T)*O,t[7]=(u*C-h*y+p*T)*O,t[8]=(o*F-a*R+l*_)*O,t[9]=(n*R-e*F-r*_)*O,t[10]=(g*w-v*y+d*S)*O,t[11]=(f*y-u*w-p*S)*O,t[12]=(a*E-o*L-c*_)*O,t[13]=(e*L-n*E+s*_)*O,t[14]=(v*T-g*b-m*S)*O,t[15]=(u*b-f*T+h*S)*O,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,c=t.z,l=r*o,u=r*a;return this.set(l*o+n,l*a-s*c,l*c+s*a,0,l*a+s*c,u*a+n,u*c-s*o,0,l*c-s*a,u*c+s*o,r*c*c+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,c=e._w,l=r+r,u=o+o,f=a+a,h=r*l,p=r*u,g=r*f,v=o*u,m=o*f,d=a*f,S=c*l,T=c*u,y=c*f,b=n.x,w=n.y,C=n.z;return s[0]=(1-(v+d))*b,s[1]=(p+y)*b,s[2]=(g-T)*b,s[3]=0,s[4]=(p-y)*w,s[5]=(1-(h+d))*w,s[6]=(m+S)*w,s[7]=0,s[8]=(g+T)*C,s[9]=(m-S)*C,s[10]=(1-(h+v))*C,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;t.x=s[12],t.y=s[13],t.z=s[14];let r=this.determinantAffine();if(r===0)return n.set(1,1,1),e.identity(),this;let o=fs.set(s[0],s[1],s[2]).length(),a=fs.set(s[4],s[5],s[6]).length(),c=fs.set(s[8],s[9],s[10]).length();r<0&&(o=-o),Mn.copy(this);let l=1/o,u=1/a,f=1/c;return Mn.elements[0]*=l,Mn.elements[1]*=l,Mn.elements[2]*=l,Mn.elements[4]*=u,Mn.elements[5]*=u,Mn.elements[6]*=u,Mn.elements[8]*=f,Mn.elements[9]*=f,Mn.elements[10]*=f,e.setFromRotationMatrix(Mn),n.x=o,n.y=a,n.z=c,this}makePerspective(t,e,n,s,r,o,a=wn,c=!1){let l=this.elements,u=2*r/(e-t),f=2*r/(n-s),h=(e+t)/(e-t),p=(n+s)/(n-s),g,v;if(c)g=r/(o-r),v=o*r/(o-r);else if(a===wn)g=-(o+r)/(o-r),v=-2*o*r/(o-r);else if(a===Cs)g=-o/(o-r),v=-o*r/(o-r);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);return l[0]=u,l[4]=0,l[8]=h,l[12]=0,l[1]=0,l[5]=f,l[9]=p,l[13]=0,l[2]=0,l[6]=0,l[10]=g,l[14]=v,l[3]=0,l[7]=0,l[11]=-1,l[15]=0,this}makeOrthographic(t,e,n,s,r,o,a=wn,c=!1){let l=this.elements,u=2/(e-t),f=2/(n-s),h=-(e+t)/(e-t),p=-(n+s)/(n-s),g,v;if(c)g=1/(o-r),v=o/(o-r);else if(a===wn)g=-2/(o-r),v=-(o+r)/(o-r);else if(a===Cs)g=-1/(o-r),v=-r/(o-r);else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);return l[0]=u,l[4]=0,l[8]=0,l[12]=h,l[1]=0,l[5]=f,l[9]=0,l[13]=p,l[2]=0,l[6]=0,l[10]=g,l[14]=v,l[3]=0,l[7]=0,l[11]=0,l[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}},fs=new P,Mn=new se,xf=new P(0,0,0),yf=new P(1,1,1),di=new P,ro=new P,on=new P,Th=new se,Ah=new pe,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],c=s[1],l=s[5],u=s[9],f=s[2],h=s[6],p=s[10];switch(e){case"XYZ":this._y=Math.asin(Vt(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-u,p),this._z=Math.atan2(-o,r)):(this._x=Math.atan2(h,l),this._z=0);break;case"YXZ":this._x=Math.asin(-Vt(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(a,p),this._z=Math.atan2(c,l)):(this._y=Math.atan2(-f,r),this._z=0);break;case"ZXY":this._x=Math.asin(Vt(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(-f,p),this._z=Math.atan2(-o,l)):(this._y=0,this._z=Math.atan2(c,r));break;case"ZYX":this._y=Math.asin(-Vt(f,-1,1)),Math.abs(f)<.9999999?(this._x=Math.atan2(h,p),this._z=Math.atan2(c,r)):(this._x=0,this._z=Math.atan2(-o,l));break;case"YZX":this._z=Math.asin(Vt(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(-u,l),this._y=Math.atan2(-f,r)):(this._x=0,this._y=Math.atan2(a,p));break;case"XZY":this._z=Math.asin(-Vt(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(h,l),this._y=Math.atan2(a,r)):(this._x=Math.atan2(-u,p),this._y=0);break;default:It("Euler: .setFromRotationMatrix() encountered an unknown order: "+e)}return this._order=e,n===!0&&this._onChangeCallback(),this}setFromQuaternion(t,e,n){return Th.makeRotationFromQuaternion(t),this.setFromRotationMatrix(Th,e,n)}setFromVector3(t,e=this._order){return this.set(t.x,t.y,t.z,e)}reorder(t){return Ah.setFromEuler(this),this.setFromQuaternion(Ah,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 Ls=class{constructor(){this.mask=1}set(t){this.mask=(1<<t|0)>>>0}enable(t){this.mask|=1<<t|0}enableAll(){this.mask=-1}toggle(t){this.mask^=1<<t|0}disable(t){this.mask&=~(1<<t|0)}disableAll(){this.mask=0}test(t){return(this.mask&t.mask)!==0}isEnabled(t){return(this.mask&(1<<t|0))!==0}},vf=0,Ch=new P,ps=new pe,jn=new se,oo=new P,er=new P,Mf=new P,Sf=new pe,Rh=new P(1,0,0),Ph=new P(0,1,0),Ih=new P(0,0,1),Lh={type:"added"},bf={type:"removed"},ms={type:"childadded",child:null},wl={type:"childremoved",child:null},ye=class i extends En{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:vf++}),this.uuid=Gs(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=i.DEFAULT_UP.clone();let t=new P,e=new Tn,n=new pe,s=new P(1,1,1);function r(){n.setFromEuler(e,!1)}function o(){e.setFromQuaternion(n,void 0,!1)}e._onChange(r),n._onChange(o),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:t},rotation:{configurable:!0,enumerable:!0,value:e},quaternion:{configurable:!0,enumerable:!0,value:n},scale:{configurable:!0,enumerable:!0,value:s},modelViewMatrix:{value:new se},normalMatrix:{value:new Ut}}),this.matrix=new se,this.matrixWorld=new se,this.matrixAutoUpdate=i.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=i.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new Ls,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.static=!1,this.userData={},this.pivot=null}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(t){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(t),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(t){return this.quaternion.premultiply(t),this}setRotationFromAxisAngle(t,e){this.quaternion.setFromAxisAngle(t,e)}setRotationFromEuler(t){this.quaternion.setFromEuler(t,!0)}setRotationFromMatrix(t){this.quaternion.setFromRotationMatrix(t)}setRotationFromQuaternion(t){this.quaternion.copy(t)}rotateOnAxis(t,e){return ps.setFromAxisAngle(t,e),this.quaternion.multiply(ps),this}rotateOnWorldAxis(t,e){return ps.setFromAxisAngle(t,e),this.quaternion.premultiply(ps),this}rotateX(t){return this.rotateOnAxis(Rh,t)}rotateY(t){return this.rotateOnAxis(Ph,t)}rotateZ(t){return this.rotateOnAxis(Ih,t)}translateOnAxis(t,e){return Ch.copy(t).applyQuaternion(this.quaternion),this.position.add(Ch.multiplyScalar(e)),this}translateX(t){return this.translateOnAxis(Rh,t)}translateY(t){return this.translateOnAxis(Ph,t)}translateZ(t){return this.translateOnAxis(Ih,t)}localToWorld(t){return this.updateWorldMatrix(!0,!1),t.applyMatrix4(this.matrixWorld)}worldToLocal(t){return this.updateWorldMatrix(!0,!1),t.applyMatrix4(jn.copy(this.matrixWorld).invert())}lookAt(t,e,n){t.isVector3?oo.copy(t):oo.set(t,e,n);let s=this.parent;this.updateWorldMatrix(!0,!1),er.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?jn.lookAt(er,oo,this.up):jn.lookAt(oo,er,this.up),this.quaternion.setFromRotationMatrix(jn),s&&(jn.extractRotation(s.matrixWorld),ps.setFromRotationMatrix(jn),this.quaternion.premultiply(ps.invert()))}add(t){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.add(arguments[e]);return this}return t===this?(Dt("Object3D.add: object can't be added as a child of itself.",t),this):(t&&t.isObject3D?(t.removeFromParent(),t.parent=this,this.children.push(t),t.dispatchEvent(Lh),ms.child=t,this.dispatchEvent(ms),ms.child=null):Dt("Object3D.add: object not an instance of THREE.Object3D.",t),this)}remove(t){if(arguments.length>1){for(let n=0;n<arguments.length;n++)this.remove(arguments[n]);return this}let e=this.children.indexOf(t);return e!==-1&&(t.parent=null,this.children.splice(e,1),t.dispatchEvent(bf),wl.child=t,this.dispatchEvent(wl),wl.child=null),this}removeFromParent(){let t=this.parent;return t!==null&&t.remove(this),this}clear(){return this.remove(...this.children)}attach(t){return this.updateWorldMatrix(!0,!1),jn.copy(this.matrixWorld).invert(),t.parent!==null&&(t.parent.updateWorldMatrix(!0,!1),jn.multiply(t.parent.matrixWorld)),t.applyMatrix4(jn),t.removeFromParent(),t.parent=this,this.children.push(t),t.updateWorldMatrix(!1,!0),t.dispatchEvent(Lh),ms.child=t,this.dispatchEvent(ms),ms.child=null,this}getObjectById(t){return this.getObjectByProperty("id",t)}getObjectByName(t){return this.getObjectByProperty("name",t)}getObjectByProperty(t,e){if(this[t]===e)return this;for(let n=0,s=this.children.length;n<s;n++){let o=this.children[n].getObjectByProperty(t,e);if(o!==void 0)return o}}getObjectsByProperty(t,e,n=[]){this[t]===e&&n.push(this);let s=this.children;for(let r=0,o=s.length;r<o;r++)s[r].getObjectsByProperty(t,e,n);return n}getWorldPosition(t){return this.updateWorldMatrix(!0,!1),t.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(t){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(er,t,Mf),t}getWorldScale(t){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(er,Sf,t),t}getWorldDirection(t){this.updateWorldMatrix(!0,!1);let e=this.matrixWorld.elements;return t.set(e[8],e[9],e[10]).normalize()}raycast(){}intersectsFrustum(){}traverse(t){t(this);let e=this.children;for(let n=0,s=e.length;n<s;n++)e[n].traverse(t)}traverseVisible(t){if(this.visible===!1)return;t(this);let e=this.children;for(let n=0,s=e.length;n<s;n++)e[n].traverseVisible(t)}traverseAncestors(t){let e=this.parent;e!==null&&(t(e),e.traverseAncestors(t))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale);let t=this.pivot;if(t!==null){let e=t.x,n=t.y,s=t.z,r=this.matrix.elements;r[12]+=e-r[0]*e-r[4]*n-r[8]*s,r[13]+=n-r[1]*e-r[5]*n-r[9]*s,r[14]+=s-r[2]*e-r[6]*n-r[10]*s}this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(t){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||t)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,t=!0);let e=this.children;for(let n=0,s=e.length;n<s;n++)e[n].updateMatrixWorld(t)}updateWorldMatrix(t,e,n=!1){let s=this.parent;if(t===!0&&s!==null&&s.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||n)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,n=!0),e===!0){let r=this.children;for(let o=0,a=r.length;o<a;o++)r[o].updateWorldMatrix(!1,!0,n)}}toJSON(t){let e=t===void 0||typeof t=="string",n={};e&&(t={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},n.metadata={version:4.7,type:"Object",generator:"Object3D.toJSON"});let s={};s.uuid=this.uuid,s.type=this.type,s.name=this.name,s.castShadow=this.castShadow,s.receiveShadow=this.receiveShadow,s.visible=this.visible,s.frustumCulled=this.frustumCulled,s.renderOrder=this.renderOrder,s.static=this.static,s.matrixAutoUpdate=this.matrixAutoUpdate,Object.keys(this.userData).length>0&&(s.userData=this.userData),s.layers=this.layers.mask,s.matrix=this.matrix.toArray(),s.up=this.up.toArray(),this.pivot!==null&&(s.pivot=this.pivot.toArray()),this.morphTargetDictionary!==void 0&&(s.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),this.morphTargetInfluences!==void 0&&(s.morphTargetInfluences=this.morphTargetInfluences.slice()),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,c){return a[c.uuid]===void 0&&(a[c.uuid]=c.toJSON(t)),c.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 c=a.shapes;if(Array.isArray(c))for(let l=0,u=c.length;l<u;l++){let f=c[l];r(t.shapes,f)}else r(t.shapes,c)}}if(this.isSkinnedMesh&&(s.bindMode=this.bindMode,s.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(r(t.skeletons,this.skeleton),s.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){let a=[];for(let c=0,l=this.material.length;c<l;c++)a.push(r(t.materials,this.material[c]));s.material=a}else s.material=r(t.materials,this.material);if(this.children.length>0){s.children=[];for(let a=0;a<this.children.length;a++)s.children.push(this.children[a].toJSON(t).object)}if(this.animations.length>0){s.animations=[];for(let a=0;a<this.animations.length;a++){let c=this.animations[a];s.animations.push(r(t.animations,c))}}if(e){let a=o(t.geometries),c=o(t.materials),l=o(t.textures),u=o(t.images),f=o(t.shapes),h=o(t.skeletons),p=o(t.animations),g=o(t.nodes);a.length>0&&(n.geometries=a),c.length>0&&(n.materials=c),l.length>0&&(n.textures=l),u.length>0&&(n.images=u),f.length>0&&(n.shapes=f),h.length>0&&(n.skeletons=h),p.length>0&&(n.animations=p),g.length>0&&(n.nodes=g)}return n.object=s,n;function o(a){let c=[];for(let l in a){let u=a[l];delete u.metadata,c.push(u)}return c}}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.pivot=t.pivot!==null?t.pivot.clone():null,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.static=t.static,this.animations=t.animations.slice(),this.userData=JSON.parse(JSON.stringify(t.userData)),e===!0)for(let n=0;n<t.children.length;n++){let s=t.children[n];this.add(s.clone())}return this}dispose(){this.dispatchEvent({type:"dispose"})}};ye.DEFAULT_UP=new P(0,1,0);ye.DEFAULT_MATRIX_AUTO_UPDATE=!0;ye.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;var Vi=class extends ye{constructor(){super(),this.isGroup=!0,this.type="Group"}},wf={type:"move"},Ds=class{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new Vi,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 Vi,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new P,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new P),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new Vi,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new P,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new P,this._grip.eventsEnabled=!1),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,c=this._grip,l=this._hand;if(t&&e.session.visibilityState!=="visible-blurred"){if(l&&t.hand){o=!0;for(let v of t.hand.values()){let m=e.getJointPose(v,n),d=this._getHandJoint(l,v);m!==null&&(d.matrix.fromArray(m.transform.matrix),d.matrix.decompose(d.position,d.rotation,d.scale),d.matrixWorldNeedsUpdate=!0,d.jointRadius=m.radius),d.visible=m!==null}let u=l.joints["index-finger-tip"],f=l.joints["thumb-tip"],h=u.position.distanceTo(f.position),p=.02,g=.005;l.inputState.pinching&&h>p+g?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:t.handedness,target:this})):!l.inputState.pinching&&h<=p-g&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:t.handedness,target:this}))}else c!==null&&t.gripSpace&&(r=e.getPose(t.gripSpace,n),r!==null&&(c.matrix.fromArray(r.transform.matrix),c.matrix.decompose(c.position,c.rotation,c.scale),c.matrixWorldNeedsUpdate=!0,r.linearVelocity?(c.hasLinearVelocity=!0,c.linearVelocity.copy(r.linearVelocity)):c.hasLinearVelocity=!1,r.angularVelocity?(c.hasAngularVelocity=!0,c.angularVelocity.copy(r.angularVelocity)):c.hasAngularVelocity=!1,c.eventsEnabled&&c.dispatchEvent({type:"gripUpdated",data:t,target:this})));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(wf)))}return a!==null&&(a.visible=s!==null),c!==null&&(c.visible=r!==null),l!==null&&(l.visible=o!==null),this}_getHandJoint(t,e){if(t.joints[e.jointName]===void 0){let n=new Vi;n.matrixAutoUpdate=!1,n.visible=!1,t.joints[e.jointName]=n,t.add(n)}return t.joints[e.jointName]}},Lu={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},fi={h:0,s:0,l:0},ao={h:0,s:0,l:0};function El(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 Nt=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=qe){return t=Math.floor(t),this.r=(t>>16&255)/255,this.g=(t>>8&255)/255,this.b=(t&255)/255,Xt.colorSpaceToWorking(this,e),this}setRGB(t,e,n,s=Xt.workingColorSpace){return this.r=t,this.g=e,this.b=n,Xt.colorSpaceToWorking(this,s),this}setHSL(t,e,n,s=Xt.workingColorSpace){if(t=vc(t,1),e=Vt(e,0,1),n=Vt(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=El(o,r,t+1/3),this.g=El(o,r,t),this.b=El(o,r,t-1/3)}return Xt.colorSpaceToWorking(this,s),this}setStyle(t,e=qe){function n(r){r!==void 0&&parseFloat(r)<1&&It("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:It("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);It("Color: Invalid hex color "+t)}else if(t&&t.length>0)return this.setColorName(t,e);return this}setColorName(t,e=qe){let n=Lu[t.toLowerCase()];return n!==void 0?this.setHex(n,e):It("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=ti(t.r),this.g=ti(t.g),this.b=ti(t.b),this}copyLinearToSRGB(t){return this.r=Ts(t.r),this.g=Ts(t.g),this.b=Ts(t.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(t=qe){return Xt.workingToColorSpace(Ve.copy(this),t),Math.round(Vt(Ve.r*255,0,255))*65536+Math.round(Vt(Ve.g*255,0,255))*256+Math.round(Vt(Ve.b*255,0,255))}getHexString(t=qe){return("000000"+this.getHex(t).toString(16)).slice(-6)}getHSL(t,e=Xt.workingColorSpace){Xt.workingToColorSpace(Ve.copy(this),e);let n=Ve.r,s=Ve.g,r=Ve.b,o=Math.max(n,s,r),a=Math.min(n,s,r),c,l,u=(a+o)/2;if(a===o)c=0,l=0;else{let f=o-a;switch(l=u<=.5?f/(o+a):f/(2-o-a),o){case n:c=(s-r)/f+(s<r?6:0);break;case s:c=(r-n)/f+2;break;case r:c=(n-s)/f+4;break}c/=6}return t.h=c,t.s=l,t.l=u,t}getRGB(t,e=Xt.workingColorSpace){return Xt.workingToColorSpace(Ve.copy(this),e),t.r=Ve.r,t.g=Ve.g,t.b=Ve.b,t}getStyle(t=qe){Xt.workingToColorSpace(Ve.copy(this),t);let e=Ve.r,n=Ve.g,s=Ve.b;return t!==qe?`color(${t} ${e.toFixed(3)} ${n.toFixed(3)} ${s.toFixed(3)})`:`rgb(${Math.round(e*255)},${Math.round(n*255)},${Math.round(s*255)})`}offsetHSL(t,e,n){return this.getHSL(fi),this.setHSL(fi.h+t,fi.s+e,fi.l+n)}add(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this}addColors(t,e){return this.r=t.r+e.r,this.g=t.g+e.g,this.b=t.b+e.b,this}addScalar(t){return this.r+=t,this.g+=t,this.b+=t,this}sub(t){return this.r=Math.max(0,this.r-t.r),this.g=Math.max(0,this.g-t.g),this.b=Math.max(0,this.b-t.b),this}multiply(t){return this.r*=t.r,this.g*=t.g,this.b*=t.b,this}multiplyScalar(t){return this.r*=t,this.g*=t,this.b*=t,this}lerp(t,e){return this.r+=(t.r-this.r)*e,this.g+=(t.g-this.g)*e,this.b+=(t.b-this.b)*e,this}lerpColors(t,e,n){return this.r=t.r+(e.r-t.r)*n,this.g=t.g+(e.g-t.g)*n,this.b=t.b+(e.b-t.b)*n,this}lerpHSL(t,e){this.getHSL(fi),t.getHSL(ao);let n=ar(fi.h,ao.h,e),s=ar(fi.s,ao.s,e),r=ar(fi.l,ao.l,e);return this.setHSL(n,s,r),this}setFromVector3(t){return this.r=t.x,this.g=t.y,this.b=t.z,this}applyMatrix3(t){let e=this.r,n=this.g,s=this.b,r=t.elements;return this.r=r[0]*e+r[3]*n+r[6]*s,this.g=r[1]*e+r[4]*n+r[7]*s,this.b=r[2]*e+r[5]*n+r[8]*s,this}equals(t){return t.r===this.r&&t.g===this.g&&t.b===this.b}fromArray(t,e=0){return this.r=t[e],this.g=t[e+1],this.b=t[e+2],this}toArray(t=[],e=0){return t[e]=this.r,t[e+1]=this.g,t[e+2]=this.b,t}fromBufferAttribute(t,e){return this.r=t.getX(e),this.g=t.getY(e),this.b=t.getZ(e),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}},Ve=new Nt;Nt.NAMES=Lu;var fr=class i{constructor(t,e=1,n=1e3){this.isFog=!0,this.name="",this.color=new Nt(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}}},pr=class extends ye{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()),e.object.backgroundBlurriness=this.backgroundBlurriness,e.object.backgroundIntensity=this.backgroundIntensity,e.object.backgroundRotation=this.backgroundRotation.toArray(),e.object.environmentIntensity=this.environmentIntensity,e.object.environmentRotation=this.environmentRotation.toArray(),e}},Sn=new P,Jn=new P,Tl=new P,$n=new P,gs=new P,_s=new P,Dh=new P,Al=new P,Cl=new P,Rl=new P,Pl=new me,Il=new me,Ll=new me,_i=class i{constructor(t=new P,e=new P,n=new P){this.a=t,this.b=e,this.c=n}static getNormal(t,e,n,s){s.subVectors(n,e),Sn.subVectors(t,e),s.cross(Sn);let r=s.lengthSq();return r>0?s.multiplyScalar(1/Math.sqrt(r)):s.set(0,0,0)}static getBarycoord(t,e,n,s,r){Sn.subVectors(s,e),Jn.subVectors(n,e),Tl.subVectors(t,e);let o=Sn.dot(Sn),a=Sn.dot(Jn),c=Sn.dot(Tl),l=Jn.dot(Jn),u=Jn.dot(Tl),f=o*l-a*a;if(f===0)return r.set(0,0,0),null;let h=1/f,p=(l*c-a*u)*h,g=(o*u-a*c)*h;return r.set(1-p-g,g,p)}static containsPoint(t,e,n,s){return this.getBarycoord(t,e,n,s,$n)===null?!1:$n.x>=0&&$n.y>=0&&$n.x+$n.y<=1}static getInterpolation(t,e,n,s,r,o,a,c){return this.getBarycoord(t,e,n,s,$n)===null?(c.x=0,c.y=0,"z"in c&&(c.z=0),"w"in c&&(c.w=0),null):(c.setScalar(0),c.addScaledVector(r,$n.x),c.addScaledVector(o,$n.y),c.addScaledVector(a,$n.z),c)}static getInterpolatedAttribute(t,e,n,s,r,o){return Pl.setScalar(0),Il.setScalar(0),Ll.setScalar(0),Pl.fromBufferAttribute(t,e),Il.fromBufferAttribute(t,n),Ll.fromBufferAttribute(t,s),o.setScalar(0),o.addScaledVector(Pl,r.x),o.addScaledVector(Il,r.y),o.addScaledVector(Ll,r.z),o}static isFrontFacing(t,e,n,s){return Sn.subVectors(n,e),Jn.subVectors(t,e),Sn.cross(Jn).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 Sn.subVectors(this.c,this.b),Jn.subVectors(this.a,this.b),Sn.cross(Jn).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;gs.subVectors(s,n),_s.subVectors(r,n),Al.subVectors(t,n);let c=gs.dot(Al),l=_s.dot(Al);if(c<=0&&l<=0)return e.copy(n);Cl.subVectors(t,s);let u=gs.dot(Cl),f=_s.dot(Cl);if(u>=0&&f<=u)return e.copy(s);let h=c*f-u*l;if(h<=0&&c>=0&&u<=0)return o=c/(c-u),e.copy(n).addScaledVector(gs,o);Rl.subVectors(t,r);let p=gs.dot(Rl),g=_s.dot(Rl);if(g>=0&&p<=g)return e.copy(r);let v=p*l-c*g;if(v<=0&&l>=0&&g<=0)return a=l/(l-g),e.copy(n).addScaledVector(_s,a);let m=u*g-p*f;if(m<=0&&f-u>=0&&p-g>=0)return Dh.subVectors(r,s),a=(f-u)/(f-u+(p-g)),e.copy(s).addScaledVector(Dh,a);let d=1/(m+v+h);return o=v*d,a=h*d,e.copy(n).addScaledVector(gs,o).addScaledVector(_s,a)}equals(t){return t.a.equals(this.a)&&t.b.equals(this.b)&&t.c.equals(this.c)}},An=class{constructor(t=new P(1/0,1/0,1/0),e=new P(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=t,this.max=e}set(t,e){return this.min.copy(t),this.max.copy(e),this}setFromArray(t){this.makeEmpty();for(let e=0,n=t.length;e<n;e+=3)this.expandByPoint(bn.fromArray(t,e));return this}setFromBufferAttribute(t){this.makeEmpty();for(let e=0,n=t.count;e<n;e++)this.expandByPoint(bn.fromBufferAttribute(t,e));return this}setFromPoints(t){this.makeEmpty();for(let e=0,n=t.length;e<n;e++)this.expandByPoint(t[e]);return this}setFromCenterAndSize(t,e){let n=bn.copy(e).multiplyScalar(.5);return this.min.copy(t).sub(n),this.max.copy(t).add(n),this}setFromObject(t,e=!1){return this.makeEmpty(),this.expandByObject(t,e)}clone(){return new this.constructor().copy(this)}copy(t){return this.min.copy(t.min),this.max.copy(t.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(t){return this.isEmpty()?t.set(0,0,0):t.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(t){return this.isEmpty()?t.set(0,0,0):t.subVectors(this.max,this.min)}expandByPoint(t){return this.min.min(t),this.max.max(t),this}expandByVector(t){return this.min.sub(t),this.max.add(t),this}expandByScalar(t){return this.min.addScalar(-t),this.max.addScalar(t),this}expandByObject(t,e=!1){t.updateWorldMatrix(!1,!1);let n=t.geometry;if(n!==void 0){let r=n.getAttribute("position");if(e===!0&&r!==void 0&&t.isInstancedMesh!==!0)for(let o=0,a=r.count;o<a;o++)t.isMesh===!0?t.getVertexPosition(o,bn):bn.fromBufferAttribute(r,o),bn.applyMatrix4(t.matrixWorld),this.expandByPoint(bn);else t.boundingBox!==void 0?(t.boundingBox===null&&t.computeBoundingBox(),lo.copy(t.boundingBox)):(n.boundingBox===null&&n.computeBoundingBox(),lo.copy(n.boundingBox)),lo.applyMatrix4(t.matrixWorld),this.union(lo)}let s=t.children;for(let r=0,o=s.length;r<o;r++)this.expandByObject(s[r],e);return this}containsPoint(t){return t.x>=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,bn),bn.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(nr),co.subVectors(this.max,nr),xs.subVectors(t.a,nr),ys.subVectors(t.b,nr),vs.subVectors(t.c,nr),pi.subVectors(ys,xs),mi.subVectors(vs,ys),Oi.subVectors(xs,vs);let e=[0,-pi.z,pi.y,0,-mi.z,mi.y,0,-Oi.z,Oi.y,pi.z,0,-pi.x,mi.z,0,-mi.x,Oi.z,0,-Oi.x,-pi.y,pi.x,0,-mi.y,mi.x,0,-Oi.y,Oi.x,0];return!Dl(e,xs,ys,vs,co)||(e=[1,0,0,0,1,0,0,0,1],!Dl(e,xs,ys,vs,co))?!1:(ho.crossVectors(pi,mi),e=[ho.x,ho.y,ho.z],Dl(e,xs,ys,vs,co))}clampPoint(t,e){return e.copy(t).clamp(this.min,this.max)}distanceToPoint(t){return this.clampPoint(t,bn).distanceTo(t)}getBoundingSphere(t){return this.isEmpty()?t.makeEmpty():(this.getCenter(t.center),t.radius=this.getSize(bn).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 P,new P,new P,new P,new P,new P,new P,new P],bn=new P,lo=new An,xs=new P,ys=new P,vs=new P,pi=new P,mi=new P,Oi=new P,nr=new P,co=new P,ho=new P,Bi=new P;function Dl(i,t,e,n,s){for(let r=0,o=i.length-3;r<=o;r+=3){Bi.fromArray(i,r);let a=s.x*Math.abs(Bi.x)+s.y*Math.abs(Bi.y)+s.z*Math.abs(Bi.z),c=t.dot(Bi),l=e.dot(Bi),u=n.dot(Bi);if(Math.max(-Math.max(c,l,u),Math.min(c,l,u))>a)return!1}return!0}var Te=new P,uo=new Pt,Ef=0,cn=class extends En{constructor(t,e,n=!1){if(super(),Array.isArray(t))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:Ef++}),this.name="",this.array=t,this.itemSize=e,this.count=t!==void 0?t.length/e:0,this.normalized=n,this.usage=Au,this.updateRanges=[],this.gpuType=In,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;s<r;s++)this.array[t+s]=e.array[n+s];return this}copyArray(t){return this.array.set(t),this}applyMatrix3(t){if(this.itemSize===2)for(let e=0,n=this.count;e<n;e++)uo.fromBufferAttribute(this,e),uo.applyMatrix3(t),this.setXY(e,uo.x,uo.y);else if(this.itemSize===3)for(let e=0,n=this.count;e<n;e++)Te.fromBufferAttribute(this,e),Te.applyMatrix3(t),this.setXYZ(e,Te.x,Te.y,Te.z);return this}applyMatrix4(t){for(let e=0,n=this.count;e<n;e++)Te.fromBufferAttribute(this,e),Te.applyMatrix4(t),this.setXYZ(e,Te.x,Te.y,Te.z);return this}applyNormalMatrix(t){for(let e=0,n=this.count;e<n;e++)Te.fromBufferAttribute(this,e),Te.applyNormalMatrix(t),this.setXYZ(e,Te.x,Te.y,Te.z);return this}transformDirection(t){for(let e=0,n=this.count;e<n;e++)Te.fromBufferAttribute(this,e),Te.transformDirection(t),this.setXYZ(e,Te.x,Te.y,Te.z);return this}set(t,e=0){return this.array.set(t,e),this}getComponent(t,e){let n=this.array[t*this.itemSize+e];return this.normalized&&(n=Es(n,this.array)),n}setComponent(t,e,n){return this.normalized&&(n=Ye(n,this.array)),this.array[t*this.itemSize+e]=n,this}getX(t){let e=this.array[t*this.itemSize];return this.normalized&&(e=Es(e,this.array)),e}setX(t,e){return this.normalized&&(e=Ye(e,this.array)),this.array[t*this.itemSize]=e,this}getY(t){let e=this.array[t*this.itemSize+1];return this.normalized&&(e=Es(e,this.array)),e}setY(t,e){return this.normalized&&(e=Ye(e,this.array)),this.array[t*this.itemSize+1]=e,this}getZ(t){let e=this.array[t*this.itemSize+2];return this.normalized&&(e=Es(e,this.array)),e}setZ(t,e){return this.normalized&&(e=Ye(e,this.array)),this.array[t*this.itemSize+2]=e,this}getW(t){let e=this.array[t*this.itemSize+3];return this.normalized&&(e=Es(e,this.array)),e}setW(t,e){return this.normalized&&(e=Ye(e,this.array)),this.array[t*this.itemSize+3]=e,this}setXY(t,e,n){return t*=this.itemSize,this.normalized&&(e=Ye(e,this.array),n=Ye(n,this.array)),this.array[t+0]=e,this.array[t+1]=n,this}setXYZ(t,e,n,s){return t*=this.itemSize,this.normalized&&(e=Ye(e,this.array),n=Ye(n,this.array),s=Ye(s,this.array)),this.array[t+0]=e,this.array[t+1]=n,this.array[t+2]=s,this}setXYZW(t,e,n,s,r){return t*=this.itemSize,this.normalized&&(e=Ye(e,this.array),n=Ye(n,this.array),s=Ye(s,this.array),r=Ye(r,this.array)),this.array[t+0]=e,this.array[t+1]=n,this.array[t+2]=s,this.array[t+3]=r,this}onUpload(t){return this.onUploadCallback=t,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){let t={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return t.name=this.name,t.usage=this.usage,t.gpuType=this.gpuType,t}dispose(){this.dispatchEvent({type:"dispose"})}};var mr=class extends cn{constructor(t,e,n){super(new Uint16Array(t),e,n)}};var gr=class extends cn{constructor(t,e,n){super(new Uint32Array(t),e,n)}};var Yt=class extends cn{constructor(t,e,n){super(new Float32Array(t),e,n)}},Tf=new An,ir=new P,Nl=new P,Gi=class{constructor(t=new P,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):Tf.setFromPoints(t).getCenter(n);let s=0;for(let r=0,o=t.length;r<o;r++)s=Math.max(s,n.distanceToSquared(t[r]));return this.radius=Math.sqrt(s),this}copy(t){return this.center.copy(t.center),this.radius=t.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(t){return t.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(t){return t.distanceTo(this.center)-this.radius}intersectsSphere(t){let e=this.radius+t.radius;return t.center.distanceToSquared(this.center)<=e*e}intersectsBox(t){return t.intersectsSphere(this)}intersectsPlane(t){return Math.abs(t.distanceToPoint(this.center))<=this.radius}clampPoint(t,e){let n=this.center.distanceToSquared(t);return e.copy(t),n>this.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;ir.subVectors(t,this.center);let e=ir.lengthSq();if(e>this.radius*this.radius){let n=Math.sqrt(e),s=(n-this.radius)*.5;this.center.addScaledVector(ir,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):(Nl.subVectors(t.center,this.center).setLength(t.radius),this.expandByPoint(ir.copy(t.center).add(Nl)),this.expandByPoint(ir.copy(t.center).sub(Nl))),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}},Af=0,gn=new se,Ul=new ye,Ms=new P,an=new An,sr=new An,Le=new P,ve=class i extends En{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:Af++}),this.uuid=Gs(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={},this._transformed=!1}getIndex(){return this.index}setIndex(t){return Array.isArray(t)?this.index=new(Jd(t)?gr:mr)(t,1):this.index=t,this}setIndirect(t,e=0){return this.indirect=t,this.indirectOffset=e,this}getIndirect(){return this.indirect}getAttribute(t){return this.attributes[t]}setAttribute(t,e){return this.attributes[t]=e,this}deleteAttribute(t){return delete this.attributes[t],this}hasAttribute(t){return this.attributes[t]!==void 0}addGroup(t,e,n=0){this.groups.push({start:t,count:e,materialIndex:n})}clearGroups(){this.groups=[]}setDrawRange(t,e){this.drawRange.start=t,this.drawRange.count=e}applyMatrix4(t){let e=this.attributes.position;e!==void 0&&(e.applyMatrix4(t),e.needsUpdate=!0);let n=this.attributes.normal;if(n!==void 0){let r=new Ut().getNormalMatrix(t);n.applyNormalMatrix(r),n.needsUpdate=!0}let s=this.attributes.tangent;return s!==void 0&&(s.transformDirection(t),s.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this._transformed=!0,this}applyQuaternion(t){return gn.makeRotationFromQuaternion(t),this.applyMatrix4(gn),this}rotateX(t){return gn.makeRotationX(t),this.applyMatrix4(gn),this}rotateY(t){return gn.makeRotationY(t),this.applyMatrix4(gn),this}rotateZ(t){return gn.makeRotationZ(t),this.applyMatrix4(gn),this}translate(t,e,n){return gn.makeTranslation(t,e,n),this.applyMatrix4(gn),this}scale(t,e,n){return gn.makeScale(t,e,n),this.applyMatrix4(gn),this}lookAt(t){return Ul.lookAt(t),Ul.updateMatrix(),this.applyMatrix4(Ul.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(Ms).negate(),this.translate(Ms.x,Ms.y,Ms.z),this}setFromPoints(t){let e=this.getAttribute("position");if(e===void 0){let n=[];for(let s=0,r=t.length;s<r;s++){let o=t[s];n.push(o.x,o.y,o.z||0)}this.setAttribute("position",new Yt(n,3))}else{let n=Math.min(t.length,e.count);for(let s=0;s<n;s++){let r=t[s];e.setXYZ(s,r.x,r.y,r.z||0)}t.length>e.count&&It("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 An);let t=this.attributes.position,e=this.morphAttributes.position;if(t&&t.isGLBufferAttribute){Dt("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new P(-1/0,-1/0,-1/0),new P(1/0,1/0,1/0));return}if(t!==void 0){if(this.boundingBox.setFromBufferAttribute(t),e)for(let n=0,s=e.length;n<s;n++){let r=e[n];an.setFromBufferAttribute(r),this.morphTargetsRelative?(Le.addVectors(this.boundingBox.min,an.min),this.boundingBox.expandByPoint(Le),Le.addVectors(this.boundingBox.max,an.max),this.boundingBox.expandByPoint(Le)):(this.boundingBox.expandByPoint(an.min),this.boundingBox.expandByPoint(an.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&Dt('BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new Gi);let t=this.attributes.position,e=this.morphAttributes.position;if(t&&t.isGLBufferAttribute){Dt("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new P,1/0);return}if(t){let n=this.boundingSphere.center;if(an.setFromBufferAttribute(t),e)for(let r=0,o=e.length;r<o;r++){let a=e[r];sr.setFromBufferAttribute(a),this.morphTargetsRelative?(Le.addVectors(an.min,sr.min),an.expandByPoint(Le),Le.addVectors(an.max,sr.max),an.expandByPoint(Le)):(an.expandByPoint(sr.min),an.expandByPoint(sr.max))}an.getCenter(n);let s=0;for(let r=0,o=t.count;r<o;r++)Le.fromBufferAttribute(t,r),s=Math.max(s,n.distanceToSquared(Le));if(e)for(let r=0,o=e.length;r<o;r++){let a=e[r],c=this.morphTargetsRelative;for(let l=0,u=a.count;l<u;l++)Le.fromBufferAttribute(a,l),c&&(Ms.fromBufferAttribute(t,l),Le.add(Ms)),s=Math.max(s,n.distanceToSquared(Le))}this.boundingSphere.radius=Math.sqrt(s),isNaN(this.boundingSphere.radius)&&Dt('BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){let t=this.index,e=this.attributes;if(t===null||e.position===void 0||e.normal===void 0||e.uv===void 0){Dt("BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}let n=e.position,s=e.normal,r=e.uv,o=this.getAttribute("tangent");(o===void 0||o.count!==n.count)&&(o=new cn(new Float32Array(4*n.count),4),this.setAttribute("tangent",o));let a=[],c=[];for(let _=0;_<n.count;_++)a[_]=new P,c[_]=new P;let l=new P,u=new P,f=new P,h=new Pt,p=new Pt,g=new Pt,v=new P,m=new P;function d(_,E,R){l.fromBufferAttribute(n,_),u.fromBufferAttribute(n,E),f.fromBufferAttribute(n,R),h.fromBufferAttribute(r,_),p.fromBufferAttribute(r,E),g.fromBufferAttribute(r,R),u.sub(l),f.sub(l),p.sub(h),g.sub(h);let L=1/(p.x*g.y-g.x*p.y);isFinite(L)&&(v.copy(u).multiplyScalar(g.y).addScaledVector(f,-p.y).multiplyScalar(L),m.copy(f).multiplyScalar(p.x).addScaledVector(u,-g.x).multiplyScalar(L),a[_].add(v),a[E].add(v),a[R].add(v),c[_].add(m),c[E].add(m),c[R].add(m))}let S=this.groups;S.length===0&&(S=[{start:0,count:t.count}]);for(let _=0,E=S.length;_<E;++_){let R=S[_],L=R.start,F=R.count;for(let z=L,I=L+F;z<I;z+=3)d(t.getX(z+0),t.getX(z+1),t.getX(z+2))}let T=new P,y=new P,b=new P,w=new P;function C(_){b.fromBufferAttribute(s,_),w.copy(b);let E=a[_];T.copy(E),T.sub(b.multiplyScalar(b.dot(E))).normalize(),y.crossVectors(w,E);let L=y.dot(c[_])<0?-1:1;o.setXYZW(_,T.x,T.y,T.z,L)}for(let _=0,E=S.length;_<E;++_){let R=S[_],L=R.start,F=R.count;for(let z=L,I=L+F;z<I;z+=3)C(t.getX(z+0)),C(t.getX(z+1)),C(t.getX(z+2))}this._transformed=!0}computeVertexNormals(){let t=this.index,e=this.getAttribute("position");if(e!==void 0){let n=this.getAttribute("normal");if(n===void 0||n.count!==e.count)n=new cn(new Float32Array(e.count*3),3),this.setAttribute("normal",n);else for(let h=0,p=n.count;h<p;h++)n.setXYZ(h,0,0,0);let s=new P,r=new P,o=new P,a=new P,c=new P,l=new P,u=new P,f=new P;if(t)for(let h=0,p=t.count;h<p;h+=3){let g=t.getX(h+0),v=t.getX(h+1),m=t.getX(h+2);s.fromBufferAttribute(e,g),r.fromBufferAttribute(e,v),o.fromBufferAttribute(e,m),u.subVectors(o,r),f.subVectors(s,r),u.cross(f),a.fromBufferAttribute(n,g),c.fromBufferAttribute(n,v),l.fromBufferAttribute(n,m),a.add(u),c.add(u),l.add(u),n.setXYZ(g,a.x,a.y,a.z),n.setXYZ(v,c.x,c.y,c.z),n.setXYZ(m,l.x,l.y,l.z)}else for(let h=0,p=e.count;h<p;h+=3)s.fromBufferAttribute(e,h+0),r.fromBufferAttribute(e,h+1),o.fromBufferAttribute(e,h+2),u.subVectors(o,r),f.subVectors(s,r),u.cross(f),n.setXYZ(h+0,u.x,u.y,u.z),n.setXYZ(h+1,u.x,u.y,u.z),n.setXYZ(h+2,u.x,u.y,u.z);this.normalizeNormals(),n.needsUpdate=!0}}normalizeNormals(){let t=this.attributes.normal;for(let e=0,n=t.count;e<n;e++)Le.fromBufferAttribute(t,e),Le.normalize(),t.setXYZ(e,Le.x,Le.y,Le.z)}toNonIndexed(){function t(a,c){let l=a.array,u=a.itemSize,f=a.normalized,h=new l.constructor(c.length*u),p=0,g=0;for(let v=0,m=c.length;v<m;v++){a.isInterleavedBufferAttribute?p=c[v]*a.data.stride+a.offset:p=c[v]*u;for(let d=0;d<u;d++)h[g++]=l[p++]}return new cn(h,u,f)}if(this.index===null)return It("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;let e=new i,n=this.index.array,s=this.attributes;for(let a in s){let c=s[a],l=t(c,n);e.setAttribute(a,l)}let r=this.morphAttributes;for(let a in r){let c=[],l=r[a];for(let u=0,f=l.length;u<f;u++){let h=l[u],p=t(h,n);c.push(p)}e.morphAttributes[a]=c}e.morphTargetsRelative=this.morphTargetsRelative;let o=this.groups;for(let a=0,c=o.length;a<c;a++){let l=o[a];e.addGroup(l.start,l.count,l.materialIndex)}return e}toJSON(){let t={metadata:{version:4.7,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(t.uuid=this.uuid,t.type=this.parameters!==void 0&&this._transformed===!0?"BufferGeometry":this.type,t.name=this.name,Object.keys(this.userData).length>0&&(t.userData=this.userData),this.parameters!==void 0&&this._transformed!==!0){let c=this.parameters;for(let l in c)c[l]!==void 0&&(t[l]=c[l]);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 c in n){let l=n[c];t.data.attributes[c]=l.toJSON(t.data)}let s={},r=!1;for(let c in this.morphAttributes){let l=this.morphAttributes[c],u=[];for(let f=0,h=l.length;f<h;f++){let p=l[f];u.push(p.toJSON(t.data))}u.length>0&&(s[c]=u,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 l in s){let u=s[l];this.setAttribute(l,u.clone(e))}let r=t.morphAttributes;for(let l in r){let u=[],f=r[l];for(let h=0,p=f.length;h<p;h++)u.push(f[h].clone(e));this.morphAttributes[l]=u}this.morphTargetsRelative=t.morphTargetsRelative;let o=t.groups;for(let l=0,u=o.length;l<u;l++){let f=o[l];this.addGroup(f.start,f.count,f.materialIndex)}let a=t.boundingBox;a!==null&&(this.boundingBox=a.clone());let c=t.boundingSphere;return c!==null&&(this.boundingSphere=c.clone()),this.drawRange.start=t.drawRange.start,this.drawRange.count=t.drawRange.count,this.userData=t.userData,this._transformed=t._transformed,this}dispose(){this.dispatchEvent({type:"dispose"})}};var Fl=new P,Cf=new P,Rf=new Ut,ln=class{constructor(t=new P(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=Fl.subVectors(n,e).cross(Cf.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,n=!0){let s=t.delta(Fl),r=this.normal.dot(s);if(r===0)return this.distanceToPoint(t.start)===0?e.copy(t.start):null;let o=-(t.start.dot(this.normal)+this.constant)/r;return n===!0&&(o<0||o>1)?null:e.copy(t.start).addScaledVector(s,o)}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||Rf.getNormalMatrix(t),s=this.coplanarPoint(Fl).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)}toJSON(){return{normal:this.normal.toArray(),constant:this.constant}}fromJSON(t){return this.normal.fromArray(t.normal),this.constant=t.constant,this}},Pf=0,ei=class extends En{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:Pf++}),this.uuid=Gs(),this.name="",this.type="Material",this.blending=ks,this.side=Ti,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=ec,this.blendDst=nc,this.blendEquation=Yi,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new Nt(0,0,0),this.blendAlpha=0,this.depthFunc=As,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=vu,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=Co,this.stencilZFail=Co,this.stencilZPass=Co,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(t){this._alphaTest>0!=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){It(`Material: parameter '${e}' has value of undefined.`);continue}let s=this[e];if(s===void 0){It(`Material: '${e}' is not a property of THREE.${this.type}.`);continue}s&&s.isColor?s.set(n):s&&s.isVector2&&n&&n.isVector2||s&&s.isEuler&&n&&n.isEuler||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,n.blending=this.blending,n.side=this.side,n.shadowSide=this.shadowSide,n.vertexColors=this.vertexColors,n.opacity=this.opacity,n.transparent=this.transparent,n.blendSrc=this.blendSrc,n.blendDst=this.blendDst,n.blendEquation=this.blendEquation,n.blendSrcAlpha=this.blendSrcAlpha,n.blendDstAlpha=this.blendDstAlpha,n.blendEquationAlpha=this.blendEquationAlpha,n.blendColor=this.blendColor.getHex(),n.blendAlpha=this.blendAlpha,n.depthFunc=this.depthFunc,n.depthTest=this.depthTest,n.depthWrite=this.depthWrite,n.colorWrite=this.colorWrite,n.clipIntersection=this.clipIntersection,n.clipShadows=this.clipShadows,n.stencilWriteMask=this.stencilWriteMask,n.stencilFunc=this.stencilFunc,n.stencilRef=this.stencilRef,n.stencilFuncMask=this.stencilFuncMask,n.stencilFail=this.stencilFail,n.stencilZFail=this.stencilZFail,n.stencilZPass=this.stencilZPass,n.stencilWrite=this.stencilWrite,n.polygonOffset=this.polygonOffset,n.polygonOffsetFactor=this.polygonOffsetFactor,n.polygonOffsetUnits=this.polygonOffsetUnits,n.dithering=this.dithering,n.alphaTest=this.alphaTest,n.alphaHash=this.alphaHash,n.alphaToCoverage=this.alphaToCoverage,n.premultipliedAlpha=this.premultipliedAlpha,n.forceSinglePass=this.forceSinglePass,n.allowOverride=this.allowOverride,n.visible=this.visible,n.toneMapped=this.toneMapped,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&&(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.retroreflectivity!==void 0&&(n.retroreflectivity=this.retroreflectivity),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&&(n.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(n.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(n.size=this.size),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),Array.isArray(this.clippingPlanes)&&this.clippingPlanes.length>0&&(n.clippingPlanes=this.clippingPlanes.map(r=>r.toJSON())),this.rotation!==void 0&&(n.rotation=this.rotation),this.depthPacking!==void 0&&(n.depthPacking=this.depthPacking),this.linewidth!==void 0&&(n.linewidth=this.linewidth),this.linecap!==void 0&&(n.linecap=this.linecap),this.linejoin!==void 0&&(n.linejoin=this.linejoin),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.wireframe!==void 0&&(n.wireframe=this.wireframe),this.wireframeLinewidth!==void 0&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!==void 0&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!==void 0&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading!==void 0&&(n.flatShading=this.flatShading),this.fog!==void 0&&(n.fog=this.fog),Object.keys(this.userData).length>0&&(n.userData=this.userData);function s(r){let o=[];for(let a in r){let c=r[a];delete c.metadata,o.push(c)}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}fromJSON(t,e){if(t.uuid!==void 0&&(this.uuid=t.uuid),t.name!==void 0&&(this.name=t.name),t.color!==void 0&&this.color!==void 0&&this.color.setHex(t.color),t.roughness!==void 0&&(this.roughness=t.roughness),t.metalness!==void 0&&(this.metalness=t.metalness),t.sheen!==void 0&&(this.sheen=t.sheen),t.sheenColor!==void 0&&(this.sheenColor=new Nt().setHex(t.sheenColor)),t.sheenRoughness!==void 0&&(this.sheenRoughness=t.sheenRoughness),t.emissive!==void 0&&this.emissive!==void 0&&this.emissive.setHex(t.emissive),t.specular!==void 0&&this.specular!==void 0&&this.specular.setHex(t.specular),t.specularIntensity!==void 0&&(this.specularIntensity=t.specularIntensity),t.specularColor!==void 0&&this.specularColor!==void 0&&this.specularColor.setHex(t.specularColor),t.shininess!==void 0&&(this.shininess=t.shininess),t.clearcoat!==void 0&&(this.clearcoat=t.clearcoat),t.clearcoatRoughness!==void 0&&(this.clearcoatRoughness=t.clearcoatRoughness),t.dispersion!==void 0&&(this.dispersion=t.dispersion),t.retroreflectivity!==void 0&&(this.retroreflectivity=t.retroreflectivity),t.iridescence!==void 0&&(this.iridescence=t.iridescence),t.iridescenceIOR!==void 0&&(this.iridescenceIOR=t.iridescenceIOR),t.iridescenceThicknessRange!==void 0&&(this.iridescenceThicknessRange=t.iridescenceThicknessRange),t.transmission!==void 0&&(this.transmission=t.transmission),t.thickness!==void 0&&(this.thickness=t.thickness),t.attenuationDistance!==void 0&&(this.attenuationDistance=t.attenuationDistance),t.attenuationColor!==void 0&&this.attenuationColor!==void 0&&this.attenuationColor.setHex(t.attenuationColor),t.anisotropy!==void 0&&(this.anisotropy=t.anisotropy),t.anisotropyRotation!==void 0&&(this.anisotropyRotation=t.anisotropyRotation),t.fog!==void 0&&(this.fog=t.fog),t.flatShading!==void 0&&(this.flatShading=t.flatShading),t.blending!==void 0&&(this.blending=t.blending),t.combine!==void 0&&(this.combine=t.combine),t.side!==void 0&&(this.side=t.side),t.shadowSide!==void 0&&(this.shadowSide=t.shadowSide),t.opacity!==void 0&&(this.opacity=t.opacity),t.transparent!==void 0&&(this.transparent=t.transparent),t.alphaTest!==void 0&&(this.alphaTest=t.alphaTest),t.alphaHash!==void 0&&(this.alphaHash=t.alphaHash),t.depthFunc!==void 0&&(this.depthFunc=t.depthFunc),t.depthTest!==void 0&&(this.depthTest=t.depthTest),t.depthWrite!==void 0&&(this.depthWrite=t.depthWrite),t.colorWrite!==void 0&&(this.colorWrite=t.colorWrite),t.clippingPlanes!==void 0&&(this.clippingPlanes=t.clippingPlanes.map(n=>new ln().fromJSON(n))),t.clipIntersection!==void 0&&(this.clipIntersection=t.clipIntersection),t.clipShadows!==void 0&&(this.clipShadows=t.clipShadows),t.depthPacking!==void 0&&(this.depthPacking=t.depthPacking),t.blendSrc!==void 0&&(this.blendSrc=t.blendSrc),t.blendDst!==void 0&&(this.blendDst=t.blendDst),t.blendEquation!==void 0&&(this.blendEquation=t.blendEquation),t.blendSrcAlpha!==void 0&&(this.blendSrcAlpha=t.blendSrcAlpha),t.blendDstAlpha!==void 0&&(this.blendDstAlpha=t.blendDstAlpha),t.blendEquationAlpha!==void 0&&(this.blendEquationAlpha=t.blendEquationAlpha),t.blendColor!==void 0&&this.blendColor!==void 0&&this.blendColor.setHex(t.blendColor),t.blendAlpha!==void 0&&(this.blendAlpha=t.blendAlpha),t.stencilWriteMask!==void 0&&(this.stencilWriteMask=t.stencilWriteMask),t.stencilFunc!==void 0&&(this.stencilFunc=t.stencilFunc),t.stencilRef!==void 0&&(this.stencilRef=t.stencilRef),t.stencilFuncMask!==void 0&&(this.stencilFuncMask=t.stencilFuncMask),t.stencilFail!==void 0&&(this.stencilFail=t.stencilFail),t.stencilZFail!==void 0&&(this.stencilZFail=t.stencilZFail),t.stencilZPass!==void 0&&(this.stencilZPass=t.stencilZPass),t.stencilWrite!==void 0&&(this.stencilWrite=t.stencilWrite),t.wireframe!==void 0&&(this.wireframe=t.wireframe),t.wireframeLinewidth!==void 0&&(this.wireframeLinewidth=t.wireframeLinewidth),t.wireframeLinecap!==void 0&&(this.wireframeLinecap=t.wireframeLinecap),t.wireframeLinejoin!==void 0&&(this.wireframeLinejoin=t.wireframeLinejoin),t.rotation!==void 0&&(this.rotation=t.rotation),t.linewidth!==void 0&&(this.linewidth=t.linewidth),t.linecap!==void 0&&(this.linecap=t.linecap),t.linejoin!==void 0&&(this.linejoin=t.linejoin),t.dashSize!==void 0&&(this.dashSize=t.dashSize),t.gapSize!==void 0&&(this.gapSize=t.gapSize),t.scale!==void 0&&(this.scale=t.scale),t.polygonOffset!==void 0&&(this.polygonOffset=t.polygonOffset),t.polygonOffsetFactor!==void 0&&(this.polygonOffsetFactor=t.polygonOffsetFactor),t.polygonOffsetUnits!==void 0&&(this.polygonOffsetUnits=t.polygonOffsetUnits),t.dithering!==void 0&&(this.dithering=t.dithering),t.alphaToCoverage!==void 0&&(this.alphaToCoverage=t.alphaToCoverage),t.premultipliedAlpha!==void 0&&(this.premultipliedAlpha=t.premultipliedAlpha),t.forceSinglePass!==void 0&&(this.forceSinglePass=t.forceSinglePass),t.allowOverride!==void 0&&(this.allowOverride=t.allowOverride),t.visible!==void 0&&(this.visible=t.visible),t.toneMapped!==void 0&&(this.toneMapped=t.toneMapped),t.userData!==void 0&&(this.userData=t.userData),t.vertexColors!==void 0&&(typeof t.vertexColors=="number"?this.vertexColors=t.vertexColors>0:this.vertexColors=t.vertexColors),t.size!==void 0&&(this.size=t.size),t.sizeAttenuation!==void 0&&(this.sizeAttenuation=t.sizeAttenuation),t.map!==void 0&&(this.map=e[t.map]||null),t.matcap!==void 0&&(this.matcap=e[t.matcap]||null),t.alphaMap!==void 0&&(this.alphaMap=e[t.alphaMap]||null),t.bumpMap!==void 0&&(this.bumpMap=e[t.bumpMap]||null),t.bumpScale!==void 0&&(this.bumpScale=t.bumpScale),t.normalMap!==void 0&&(this.normalMap=e[t.normalMap]||null),t.normalMapType!==void 0&&(this.normalMapType=t.normalMapType),t.normalScale!==void 0){let n=t.normalScale;Array.isArray(n)===!1&&(n=[n,n]),this.normalScale=new Pt().fromArray(n)}return t.displacementMap!==void 0&&(this.displacementMap=e[t.displacementMap]||null),t.displacementScale!==void 0&&(this.displacementScale=t.displacementScale),t.displacementBias!==void 0&&(this.displacementBias=t.displacementBias),t.roughnessMap!==void 0&&(this.roughnessMap=e[t.roughnessMap]||null),t.metalnessMap!==void 0&&(this.metalnessMap=e[t.metalnessMap]||null),t.emissiveMap!==void 0&&(this.emissiveMap=e[t.emissiveMap]||null),t.emissiveIntensity!==void 0&&(this.emissiveIntensity=t.emissiveIntensity),t.specularMap!==void 0&&(this.specularMap=e[t.specularMap]||null),t.specularIntensityMap!==void 0&&(this.specularIntensityMap=e[t.specularIntensityMap]||null),t.specularColorMap!==void 0&&(this.specularColorMap=e[t.specularColorMap]||null),t.envMap!==void 0&&(this.envMap=e[t.envMap]||null),t.envMapRotation!==void 0&&this.envMapRotation.fromArray(t.envMapRotation),t.envMapIntensity!==void 0&&(this.envMapIntensity=t.envMapIntensity),t.reflectivity!==void 0&&(this.reflectivity=t.reflectivity),t.refractionRatio!==void 0&&(this.refractionRatio=t.refractionRatio),t.lightMap!==void 0&&(this.lightMap=e[t.lightMap]||null),t.lightMapIntensity!==void 0&&(this.lightMapIntensity=t.lightMapIntensity),t.aoMap!==void 0&&(this.aoMap=e[t.aoMap]||null),t.aoMapIntensity!==void 0&&(this.aoMapIntensity=t.aoMapIntensity),t.gradientMap!==void 0&&(this.gradientMap=e[t.gradientMap]||null),t.clearcoatMap!==void 0&&(this.clearcoatMap=e[t.clearcoatMap]||null),t.clearcoatRoughnessMap!==void 0&&(this.clearcoatRoughnessMap=e[t.clearcoatRoughnessMap]||null),t.clearcoatNormalMap!==void 0&&(this.clearcoatNormalMap=e[t.clearcoatNormalMap]||null),t.clearcoatNormalScale!==void 0&&(this.clearcoatNormalScale=new Pt().fromArray(t.clearcoatNormalScale)),t.iridescenceMap!==void 0&&(this.iridescenceMap=e[t.iridescenceMap]||null),t.iridescenceThicknessMap!==void 0&&(this.iridescenceThicknessMap=e[t.iridescenceThicknessMap]||null),t.transmissionMap!==void 0&&(this.transmissionMap=e[t.transmissionMap]||null),t.thicknessMap!==void 0&&(this.thicknessMap=e[t.thicknessMap]||null),t.anisotropyMap!==void 0&&(this.anisotropyMap=e[t.anisotropyMap]||null),t.sheenColorMap!==void 0&&(this.sheenColorMap=e[t.sheenColorMap]||null),t.sheenRoughnessMap!==void 0&&(this.sheenRoughnessMap=e[t.sheenRoughnessMap]||null),this}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.allowOverride=t.allowOverride,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++}};var Qn=new P,Ol=new P,fo=new P,po=new P,xi=class{constructor(t=new P,e=new P(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,Qn)),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=Qn.subVectors(t,this.origin).dot(this.direction);return e<0?this.origin.distanceToSquared(t):(Qn.copy(this.origin).addScaledVector(this.direction,e),Qn.distanceToSquared(t))}distanceSqToSegment(t,e,n,s){Ol.copy(t).add(e).multiplyScalar(.5),fo.copy(e).sub(t).normalize(),po.copy(this.origin).sub(Ol);let r=t.distanceTo(e)*.5,o=-this.direction.dot(fo),a=po.dot(this.direction),c=-po.dot(fo),l=po.lengthSq(),u=Math.abs(1-o*o),f,h,p,g;if(u>0)if(f=o*c-a,h=o*a-c,g=r*u,f>=0)if(h>=-g)if(h<=g){let v=1/u;f*=v,h*=v,p=f*(f+o*h+2*a)+h*(o*f+h+2*c)+l}else h=r,f=Math.max(0,-(o*h+a)),p=-f*f+h*(h+2*c)+l;else h=-r,f=Math.max(0,-(o*h+a)),p=-f*f+h*(h+2*c)+l;else h<=-g?(f=Math.max(0,-(-o*r+a)),h=f>0?-r:Math.min(Math.max(-r,-c),r),p=-f*f+h*(h+2*c)+l):h<=g?(f=0,h=Math.min(Math.max(-r,-c),r),p=h*(h+2*c)+l):(f=Math.max(0,-(o*r+a)),h=f>0?r:Math.min(Math.max(-r,-c),r),p=-f*f+h*(h+2*c)+l);else h=o>0?-r:r,f=Math.max(0,-(o*h+a)),p=-f*f+h*(h+2*c)+l;return n&&n.copy(this.origin).addScaledVector(this.direction,f),s&&s.copy(Ol).addScaledVector(fo,h),p}intersectSphere(t,e){if(t.radius<0)return null;Qn.subVectors(t.center,this.origin);let n=Qn.dot(this.direction),s=Qn.dot(Qn)-n*n,r=t.radius*t.radius;if(s>r)return null;let o=Math.sqrt(r-s),a=n-o,c=n+o;return c<0?null:a<0?this.at(c,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,c,l=1/this.direction.x,u=1/this.direction.y,f=1/this.direction.z,h=this.origin;return l>=0?(n=(t.min.x-h.x)*l,s=(t.max.x-h.x)*l):(n=(t.max.x-h.x)*l,s=(t.min.x-h.x)*l),u>=0?(r=(t.min.y-h.y)*u,o=(t.max.y-h.y)*u):(r=(t.max.y-h.y)*u,o=(t.min.y-h.y)*u),n>o||r>s||((r>n||isNaN(n))&&(n=r),(o<s||isNaN(s))&&(s=o),f>=0?(a=(t.min.z-h.z)*f,c=(t.max.z-h.z)*f):(a=(t.max.z-h.z)*f,c=(t.min.z-h.z)*f),n>c||a>s)||((a>n||n!==n)&&(n=a),(c<s||s!==s)&&(s=c),s<0)?null:this.at(n>=0?n:s,e)}intersectsBox(t){return this.intersectBox(t,Qn)!==null}intersectTriangle(t,e,n,s,r){let o=this.origin,a=this.direction,c=a.x,l=a.y,u=a.z,f=t.x-o.x,h=t.y-o.y,p=t.z-o.z,g=e.x-o.x,v=e.y-o.y,m=e.z-o.z,d=n.x-o.x,S=n.y-o.y,T=n.z-o.z,y=Math.abs(c),b=Math.abs(l),w=Math.abs(u),C,_,E,R,L,F,z,I,O,G,X,et;if(y>=b&&y>=w?(E=c,F=f,O=g,et=d,c>=0?(C=l,_=u,R=h,L=p,z=v,I=m,G=S,X=T):(C=u,_=l,R=p,L=h,z=m,I=v,G=T,X=S)):b>=w?(E=l,F=h,O=v,et=S,l>=0?(C=u,_=c,R=p,L=f,z=m,I=g,G=T,X=d):(C=c,_=u,R=f,L=p,z=g,I=m,G=d,X=T)):(E=u,F=p,O=m,et=T,u>=0?(C=c,_=l,R=f,L=h,z=g,I=v,G=d,X=S):(C=l,_=c,R=h,L=f,z=v,I=g,G=S,X=d)),E===0)return null;let Y=C/E,K=_/E,nt=1/E,Et=R-Y*F,Tt=L-K*F,te=z-Y*O,qt=I-K*O,Jt=G-Y*et,Z=X-K*et,Q=Jt*qt-Z*te,vt=Et*Z-Tt*Jt,Ft=te*Tt-qt*Et;if(s){if(Q<0||vt<0||Ft<0)return null}else if((Q<0||vt<0||Ft<0)&&(Q>0||vt>0||Ft>0))return null;let xt=Q+vt+Ft;if(xt===0)return null;let kt=nt*(Q*F+vt*O+Ft*et);return(xt>0?kt<0:kt>0)?null:this.at(kt/xt,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)}},Vn=class extends ei{constructor(t){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Nt(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=ic,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}},Nh=new se,zi=new xi,mo=new Gi,Uh=new P,go=new P,_o=new P,xo=new P,Bl=new P,yo=new P,Fh=new P,vo=new P,ut=class extends ye{constructor(t=new ve,e=new Vn){super(),this.isMesh=!0,this.type="Mesh",this.geometry=t,this.material=e,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(t,e){return super.copy(t,e),t.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=t.morphTargetInfluences.slice()),t.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},t.morphTargetDictionary)),this.material=Array.isArray(t.material)?t.material.slice():t.material,this.geometry=t.geometry,this}updateMorphTargets(){let e=this.geometry.morphAttributes,n=Object.keys(e);if(n.length>0){let s=e[n[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,o=s.length;r<o;r++){let a=s[r].name||String(r);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=r}}}}getVertexPosition(t,e){let n=this.geometry,s=n.attributes.position,r=n.morphAttributes.position,o=n.morphTargetsRelative;e.fromBufferAttribute(s,t);let a=this.morphTargetInfluences;if(r&&a){yo.set(0,0,0);for(let c=0,l=r.length;c<l;c++){let u=a[c],f=r[c];u!==0&&(Bl.fromBufferAttribute(f,t),o?yo.addScaledVector(Bl,u):yo.addScaledVector(Bl.sub(e),u))}e.add(yo)}return e}intersectsFrustum(t){return t.intersectsObject(this)}raycast(t,e){let n=this.geometry,s=this.material,r=this.matrixWorld;s!==void 0&&(n.boundingSphere===null&&n.computeBoundingSphere(),mo.copy(n.boundingSphere),mo.applyMatrix4(r),zi.copy(t.ray).recast(t.near),!(mo.containsPoint(zi.origin)===!1&&(zi.intersectSphere(mo,Uh)===null||zi.origin.distanceToSquared(Uh)>(t.far-t.near)**2))&&(Nh.copy(r).invert(),zi.copy(t.ray).applyMatrix4(Nh),!(n.boundingBox!==null&&zi.intersectsBox(n.boundingBox)===!1)&&this._computeIntersections(t,e,zi)))}_computeIntersections(t,e,n){let s,r=this.geometry,o=this.material,a=r.index,c=r.attributes.position,l=r.attributes.uv,u=r.attributes.uv1,f=r.attributes.normal,h=r.groups,p=r.drawRange;if(a!==null)if(Array.isArray(o))for(let g=0,v=h.length;g<v;g++){let m=h[g],d=o[m.materialIndex],S=Math.max(m.start,p.start),T=Math.min(a.count,Math.min(m.start+m.count,p.start+p.count));for(let y=S,b=T;y<b;y+=3){let w=a.getX(y),C=a.getX(y+1),_=a.getX(y+2);s=Mo(this,d,t,n,l,u,f,w,C,_),s&&(s.faceIndex=Math.floor(y/3),s.face.materialIndex=m.materialIndex,e.push(s))}}else{let g=Math.max(0,p.start),v=Math.min(a.count,p.start+p.count);for(let m=g,d=v;m<d;m+=3){let S=a.getX(m),T=a.getX(m+1),y=a.getX(m+2);s=Mo(this,o,t,n,l,u,f,S,T,y),s&&(s.faceIndex=Math.floor(m/3),e.push(s))}}else if(c!==void 0)if(Array.isArray(o))for(let g=0,v=h.length;g<v;g++){let m=h[g],d=o[m.materialIndex],S=Math.max(m.start,p.start),T=Math.min(c.count,Math.min(m.start+m.count,p.start+p.count));for(let y=S,b=T;y<b;y+=3){let w=y,C=y+1,_=y+2;s=Mo(this,d,t,n,l,u,f,w,C,_),s&&(s.faceIndex=Math.floor(y/3),s.face.materialIndex=m.materialIndex,e.push(s))}}else{let g=Math.max(0,p.start),v=Math.min(c.count,p.start+p.count);for(let m=g,d=v;m<d;m+=3){let S=m,T=m+1,y=m+2;s=Mo(this,o,t,n,l,u,f,S,T,y),s&&(s.faceIndex=Math.floor(m/3),e.push(s))}}}};function If(i,t,e,n,s,r,o,a){let c;if(t.side===Ze?c=n.intersectTriangle(o,r,s,!0,a):c=n.intersectTriangle(s,r,o,t.side===Ti,a),c===null)return null;vo.copy(a),vo.applyMatrix4(i.matrixWorld);let l=e.ray.origin.distanceTo(vo);return l<e.near||l>e.far?null:{distance:l,point:vo.clone(),object:i}}function Mo(i,t,e,n,s,r,o,a,c,l){i.getVertexPosition(a,go),i.getVertexPosition(c,_o),i.getVertexPosition(l,xo);let u=If(i,t,e,n,go,_o,xo,Fh);if(u){let f=new P;_i.getBarycoord(Fh,go,_o,xo,f),s&&(u.uv=_i.getInterpolatedAttribute(s,a,c,l,f,new Pt)),r&&(u.uv1=_i.getInterpolatedAttribute(r,a,c,l,f,new Pt)),o&&(u.normal=_i.getInterpolatedAttribute(o,a,c,l,f,new P),u.normal.dot(n.direction)>0&&u.normal.multiplyScalar(-1));let h={a,b:c,c:l,normal:new P,materialIndex:0};_i.getNormal(go,_o,xo,h.normal),u.face=h,u.barycoord=f}return u}var Ho=class extends $e{constructor(t=null,e=1,n=1,s,r,o,a,c,l=De,u=De,f,h){super(null,o,a,c,l,u,s,r,f,h),this.isDataTexture=!0,this.image={data:t,width:e,height:n},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}};var ki=new Gi,Lf=new Pt(.5,.5),So=new P,Ns=class{constructor(t=new ln,e=new ln,n=new ln,s=new ln,r=new ln,o=new ln){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=wn,n=!1){let s=this.planes,r=t.elements,o=r[0],a=r[1],c=r[2],l=r[3],u=r[4],f=r[5],h=r[6],p=r[7],g=r[8],v=r[9],m=r[10],d=r[11],S=r[12],T=r[13],y=r[14],b=r[15];if(s[0].setComponents(l-o,p-u,d-g,b-S).normalize(),s[1].setComponents(l+o,p+u,d+g,b+S).normalize(),s[2].setComponents(l+a,p+f,d+v,b+T).normalize(),s[3].setComponents(l-a,p-f,d-v,b-T).normalize(),n)s[4].setComponents(c,h,m,y).normalize(),s[5].setComponents(l-c,p-h,d-m,b-y).normalize();else if(s[4].setComponents(l-c,p-h,d-m,b-y).normalize(),e===wn)s[5].setComponents(l+c,p+h,d+m,b+y).normalize();else if(e===Cs)s[5].setComponents(c,h,m,y).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(),ki.copy(t.boundingSphere).applyMatrix4(t.matrixWorld);else{let e=t.geometry;e.boundingSphere===null&&e.computeBoundingSphere(),ki.copy(e.boundingSphere).applyMatrix4(t.matrixWorld)}return this.intersectsSphere(ki)}intersectsSprite(t){ki.center.set(0,0,0);let e=Lf.distanceTo(t.center);return ki.radius=.7071067811865476+e,ki.applyMatrix4(t.matrixWorld),this.intersectsSphere(ki)}intersectsSphere(t){let e=this.planes,n=t.center,s=-t.radius;for(let r=0;r<6;r++)if(e[r].distanceToPoint(n)<s)return!1;return!0}intersectsBox(t){let e=this.planes;for(let n=0;n<6;n++){let s=e[n];if(So.x=s.normal.x>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 yi=class extends ei{constructor(t){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new Nt(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}},Go=new P,Wo=new P,Oh=new se,rr=new xi,bo=new Gi,zl=new P,Bh=new P,hn=class extends ye{constructor(t=new ve,e=new yi){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;s<r;s++)Go.fromBufferAttribute(e,s-1),Wo.fromBufferAttribute(e,s),n[s]=n[s-1],n[s]+=Go.distanceTo(Wo);t.setAttribute("lineDistance",new Yt(n,1))}else It("Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}intersectsFrustum(t){return t.intersectsObject(this)}raycast(t,e){let n=this.geometry,s=this.matrixWorld,r=t.params.Line.threshold,o=n.drawRange;if(n.boundingSphere===null&&n.computeBoundingSphere(),bo.copy(n.boundingSphere),bo.applyMatrix4(s),bo.radius+=r,t.ray.intersectsSphere(bo)===!1)return;Oh.copy(s).invert(),rr.copy(t.ray).applyMatrix4(Oh);let a=r/((this.scale.x+this.scale.y+this.scale.z)/3),c=a*a,l=this.isLineSegments?2:1,u=n.index,h=n.attributes.position;if(u!==null){let p=Math.max(0,o.start),g=Math.min(u.count,o.start+o.count);for(let v=p,m=g-1;v<m;v+=l){let d=u.getX(v),S=u.getX(v+1),T=wo(this,t,rr,c,d,S,v);T&&e.push(T)}if(this.isLineLoop){let v=u.getX(g-1),m=u.getX(p),d=wo(this,t,rr,c,v,m,g-1);d&&e.push(d)}}else{let p=Math.max(0,o.start),g=Math.min(h.count,o.start+o.count);for(let v=p,m=g-1;v<m;v+=l){let d=wo(this,t,rr,c,v,v+1,v);d&&e.push(d)}if(this.isLineLoop){let v=wo(this,t,rr,c,g-1,p,g-1);v&&e.push(v)}}}updateMorphTargets(){let e=this.geometry.morphAttributes,n=Object.keys(e);if(n.length>0){let s=e[n[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,o=s.length;r<o;r++){let a=s[r].name||String(r);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=r}}}}};function wo(i,t,e,n,s,r,o){let a=i.geometry.attributes.position;if(Go.fromBufferAttribute(a,s),Wo.fromBufferAttribute(a,r),e.distanceSqToSegment(Go,Wo,zl,Bh)>n)return;zl.applyMatrix4(i.matrixWorld);let l=t.ray.origin.distanceTo(zl);if(!(l<t.near||l>t.far))return{distance:l,point:Bh.clone().applyMatrix4(i.matrixWorld),index:o,face:null,faceIndex:null,barycoord:null,object:i}}var zh=new P,kh=new P,_r=class extends hn{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;s<r;s+=2)zh.fromBufferAttribute(e,s),kh.fromBufferAttribute(e,s+1),n[s]=s===0?0:n[s-1],n[s+1]=n[s]+zh.distanceTo(kh);t.setAttribute("lineDistance",new Yt(n,1))}else It("LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}};var xr=class extends $e{constructor(t=[],e=Ai,n,s,r,o,a,c,l,u){super(t,e,n,s,r,o,a,c,l,u),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(t){this.image=t}};var vi=class extends $e{constructor(t,e,n=Pn,s,r,o,a=De,c=De,l,u=kn,f=1){if(u!==kn&&u!==Ri)throw new Error("THREE.DepthTexture: format must be either THREE.DepthFormat or THREE.DepthStencilFormat");let h={width:t,height:e,depth:f};super(h,s,r,o,a,c,u,n,l),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(t){return super.copy(t),this.source=new Is(Object.assign({},t.image)),this.compareFunction=t.compareFunction,this}toJSON(t){let e=super.toJSON(t);return e.compareFunction=this.compareFunction,e}},Xo=class extends vi{constructor(t,e=Pn,n=Ai,s,r,o=De,a=De,c,l=kn){let u={width:t,height:t,depth:1},f=[u,u,u,u,u,u];super(t,t,e,n,s,r,o,a,c,l),this.image=f,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(t){this.image=t}},yr=class extends $e{constructor(t=null){super(),this.sourceTexture=t,this.isExternalTexture=!0}copy(t){return super.copy(t),this.sourceTexture=t.sourceTexture,this}},ge=class i extends ve{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 c=[],l=[],u=[],f=[],h=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(c),this.setAttribute("position",new Yt(l,3)),this.setAttribute("normal",new Yt(u,3)),this.setAttribute("uv",new Yt(f,2));function g(v,m,d,S,T,y,b,w,C,_,E){let R=y/C,L=b/_,F=y/2,z=b/2,I=w/2,O=C+1,G=_+1,X=0,et=0,Y=new P;for(let K=0;K<G;K++){let nt=K*L-z;for(let Et=0;Et<O;Et++){let Tt=Et*R-F;Y[v]=Tt*S,Y[m]=nt*T,Y[d]=I,l.push(Y.x,Y.y,Y.z),Y[v]=0,Y[m]=0,Y[d]=w>0?1:-1,u.push(Y.x,Y.y,Y.z),f.push(Et/C),f.push(1-K/_),X+=1}}for(let K=0;K<_;K++)for(let nt=0;nt<C;nt++){let Et=h+nt+O*K,Tt=h+nt+O*(K+1),te=h+(nt+1)+O*(K+1),qt=h+(nt+1)+O*K;c.push(Et,Tt,qt),c.push(Tt,te,qt),et+=6}a.addGroup(p,et,E),p+=et,h+=X}}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new i(t.width,t.height,t.depth,t.widthSegments,t.heightSegments,t.depthSegments)}};var Ne=class i extends ve{constructor(t=1,e=1,n=1,s=32,r=1,o=!1,a=0,c=Math.PI*2){super(),this.type="CylinderGeometry",this.parameters={radiusTop:t,radiusBottom:e,height:n,radialSegments:s,heightSegments:r,openEnded:o,thetaStart:a,thetaLength:c};let l=this;s=Math.floor(s),r=Math.floor(r);let u=[],f=[],h=[],p=[],g=0,v=[],m=n/2,d=0;S(),o===!1&&(t>0&&T(!0),e>0&&T(!1)),this.setIndex(u),this.setAttribute("position",new Yt(f,3)),this.setAttribute("normal",new Yt(h,3)),this.setAttribute("uv",new Yt(p,2));function S(){let y=new P,b=new P,w=0,C=(e-t)/n;for(let _=0;_<=r;_++){let E=[],R=_/r,L=R*(e-t)+t;for(let F=0;F<=s;F++){let z=F/s,I=z*c+a,O=Math.sin(I),G=Math.cos(I);b.x=L*O,b.y=-R*n+m,b.z=L*G,f.push(b.x,b.y,b.z),y.set(O,C,G).normalize(),h.push(y.x,y.y,y.z),p.push(z,1-R),E.push(g++)}v.push(E)}for(let _=0;_<s;_++)for(let E=0;E<r;E++){let R=v[E][_],L=v[E+1][_],F=v[E+1][_+1],z=v[E][_+1];(t>0||E!==0)&&(u.push(R,L,z),w+=3),(e>0||E!==r-1)&&(u.push(L,F,z),w+=3)}l.addGroup(d,w,0),d+=w}function T(y){let b=g,w=new Pt,C=new P,_=0,E=y===!0?t:e,R=y===!0?1:-1;for(let F=1;F<=s;F++)f.push(0,m*R,0),h.push(0,R,0),p.push(.5,.5),g++;let L=g;for(let F=0;F<=s;F++){let I=F/s*c+a,O=Math.cos(I),G=Math.sin(I);C.x=E*G,C.y=m*R,C.z=E*O,f.push(C.x,C.y,C.z),h.push(0,R,0),w.x=O*.5+.5,w.y=G*.5*R+.5,p.push(w.x,w.y),g++}for(let F=0;F<s;F++){let z=b+F,I=L+F;y===!0?u.push(I,I+1,z):u.push(I+1,I,z),_+=3}l.addGroup(d,_,y===!0?1:2),d+=_}}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new i(t.radiusTop,t.radiusBottom,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}};var Yo=class i extends ve{constructor(t=[],e=[],n=1,s=0){super(),this.type="PolyhedronGeometry",this.parameters={vertices:t,indices:e,radius:n,detail:s};let r=[],o=[];a(s),l(n),u(),this.setAttribute("position",new Yt(r,3)),this.setAttribute("normal",new Yt(r.slice(),3)),this.setAttribute("uv",new Yt(o,2)),s===0?this.computeVertexNormals():this.normalizeNormals();function a(S){let T=new P,y=new P,b=new P;for(let w=0;w<e.length;w+=3)p(e[w+0],T),p(e[w+1],y),p(e[w+2],b),c(T,y,b,S)}function c(S,T,y,b){let w=b+1,C=[];for(let _=0;_<=w;_++){C[_]=[];let E=S.clone().lerp(y,_/w),R=T.clone().lerp(y,_/w),L=w-_;for(let F=0;F<=L;F++)F===0&&_===w?C[_][F]=E:C[_][F]=E.clone().lerp(R,F/L)}for(let _=0;_<w;_++)for(let E=0;E<2*(w-_)-1;E++){let R=Math.floor(E/2);E%2===0?(h(C[_][R+1]),h(C[_+1][R]),h(C[_][R])):(h(C[_][R+1]),h(C[_+1][R+1]),h(C[_+1][R]))}}function l(S){let T=new P;for(let y=0;y<r.length;y+=3)T.x=r[y+0],T.y=r[y+1],T.z=r[y+2],T.normalize().multiplyScalar(S),r[y+0]=T.x,r[y+1]=T.y,r[y+2]=T.z}function u(){let S=new P;for(let T=0;T<r.length;T+=3){S.x=r[T+0],S.y=r[T+1],S.z=r[T+2];let y=m(S)/2/Math.PI+.5,b=d(S)/Math.PI+.5;o.push(y,1-b)}g(),f()}function f(){for(let S=0;S<o.length;S+=6){let T=o[S+0],y=o[S+2],b=o[S+4],w=Math.max(T,y,b),C=Math.min(T,y,b);w>.9&&C<.1&&(T<.2&&(o[S+0]+=1),y<.2&&(o[S+2]+=1),b<.2&&(o[S+4]+=1))}}function h(S){r.push(S.x,S.y,S.z)}function p(S,T){let y=S*3;T.x=t[y+0],T.y=t[y+1],T.z=t[y+2]}function g(){let S=new P,T=new P,y=new P,b=new P,w=new Pt,C=new Pt,_=new Pt;for(let E=0,R=0;E<r.length;E+=9,R+=6){S.set(r[E+0],r[E+1],r[E+2]),T.set(r[E+3],r[E+4],r[E+5]),y.set(r[E+6],r[E+7],r[E+8]),w.set(o[R+0],o[R+1]),C.set(o[R+2],o[R+3]),_.set(o[R+4],o[R+5]),b.copy(S).add(T).add(y).divideScalar(3);let L=m(b);v(w,R+0,S,L),v(C,R+2,T,L),v(_,R+4,y,L)}}function v(S,T,y,b){b<0&&S.x===1&&(o[T]=S.x-1),y.x===0&&y.z===0&&(o[T]=b/2/Math.PI+.5)}function m(S){return Math.atan2(S.z,-S.x)}function d(S){return Math.atan2(-S.y,Math.sqrt(S.x*S.x+S.z*S.z))}}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new i(t.vertices,t.indices,t.radius,t.detail)}};var Mi=class i extends Yo{constructor(t=1,e=0){let n=[1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1],s=[0,2,4,0,4,3,0,3,5,0,5,2,1,2,5,1,5,3,1,3,4,1,4,2];super(n,s,t,e),this.type="OctahedronGeometry",this.parameters={radius:t,detail:e}}static fromJSON(t){return new i(t.radius,t.detail)}},ni=class i extends ve{constructor(t=1,e=1,n=1,s=1){super(),this.type="PlaneGeometry",this.parameters={width:t,height:e,widthSegments:n,heightSegments:s};let r=t/2,o=e/2,a=Math.floor(n),c=Math.floor(s),l=a+1,u=c+1,f=t/a,h=e/c,p=[],g=[],v=[],m=[];for(let d=0;d<u;d++){let S=d*h-o;for(let T=0;T<l;T++){let y=T*f-r;g.push(y,-S,0),v.push(0,0,1),m.push(T/a),m.push(1-d/c)}}for(let d=0;d<c;d++)for(let S=0;S<a;S++){let T=S+l*d,y=S+l*(d+1),b=S+1+l*(d+1),w=S+1+l*d;p.push(T,y,w),p.push(y,b,w)}this.setIndex(p),this.setAttribute("position",new Yt(g,3)),this.setAttribute("normal",new Yt(v,3)),this.setAttribute("uv",new Yt(m,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new i(t.width,t.height,t.widthSegments,t.heightSegments)}};var vr=class i extends ve{constructor(t=1,e=32,n=16,s=0,r=Math.PI*2,o=0,a=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:t,widthSegments:e,heightSegments:n,phiStart:s,phiLength:r,thetaStart:o,thetaLength:a},e=Math.max(3,Math.floor(e)),n=Math.max(2,Math.floor(n));let c=Math.min(o+a,Math.PI),l=0,u=[],f=new P,h=new P,p=[],g=[],v=[],m=[];for(let d=0;d<=n;d++){let S=[],T=d/n,y=o+T*a,b=t*Math.cos(y),w=Math.sqrt(t*t-b*b),C=0;d===0&&o===0?C=.5/e:d===n&&c===Math.PI&&(C=-.5/e);for(let _=0;_<=e;_++){let E=_/e,R=s+E*r;f.x=-w*Math.cos(R),f.y=b,f.z=w*Math.sin(R),g.push(f.x,f.y,f.z),h.copy(f).normalize(),v.push(h.x,h.y,h.z),m.push(E+C,1-T),S.push(l++)}u.push(S)}for(let d=0;d<n;d++)for(let S=0;S<e;S++){let T=u[d][S+1],y=u[d][S],b=u[d+1][S],w=u[d+1][S+1];(d!==0||o>0)&&p.push(T,y,w),(d!==n-1||c<Math.PI)&&p.push(y,b,w)}this.setIndex(p),this.setAttribute("position",new Yt(g,3)),this.setAttribute("normal",new Yt(v,3)),this.setAttribute("uv",new Yt(m,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new i(t.radius,t.widthSegments,t.heightSegments,t.phiStart,t.phiLength,t.thetaStart,t.thetaLength)}};var ii=class i extends ve{constructor(t=1,e=.4,n=12,s=48,r=Math.PI*2,o=0,a=Math.PI*2){super(),this.type="TorusGeometry",this.parameters={radius:t,tube:e,radialSegments:n,tubularSegments:s,arc:r,thetaStart:o,thetaLength:a},n=Math.floor(n),s=Math.floor(s);let c=[],l=[],u=[],f=[],h=new P,p=new P,g=new P;for(let v=0;v<=n;v++){let m=o+v/n*a;for(let d=0;d<=s;d++){let S=d/s*r;p.x=(t+e*Math.cos(m))*Math.cos(S),p.y=(t+e*Math.cos(m))*Math.sin(S),p.z=e*Math.sin(m),l.push(p.x,p.y,p.z),h.x=t*Math.cos(S),h.y=t*Math.sin(S),g.subVectors(p,h).normalize(),u.push(g.x,g.y,g.z),f.push(d/s),f.push(v/n)}}for(let v=1;v<=n;v++)for(let m=1;m<=s;m++){let d=(s+1)*v+m-1,S=(s+1)*(v-1)+m-1,T=(s+1)*(v-1)+m,y=(s+1)*v+m;c.push(d,S,y),c.push(S,T,y)}this.setIndex(c),this.setAttribute("position",new Yt(l,3)),this.setAttribute("normal",new Yt(u,3)),this.setAttribute("uv",new Yt(f,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new i(t.radius,t.tube,t.radialSegments,t.tubularSegments,t.arc,t.thetaStart,t.thetaLength)}};function Zi(i){let t={};for(let e in i){t[e]={};for(let n in i[e]){let s=i[e][n];if(Vh(s))s.isRenderTargetTexture?(It("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),t[e][n]=null):t[e][n]=s.clone();else if(Array.isArray(s))if(Vh(s[0])){let r=[];for(let o=0,a=s.length;o<a;o++)r[o]=s[o].clone();t[e][n]=r}else t[e][n]=s.slice();else t[e][n]=s}}return t}function He(i){let t={};for(let e=0;e<i.length;e++){let n=Zi(i[e]);for(let s in n)t[s]=n[s]}return t}function Vh(i){return i&&(i.isColor||i.isMatrix3||i.isMatrix4||i.isVector2||i.isVector3||i.isVector4||i.isTexture||i.isQuaternion)}function Df(i){let t=[];for(let e=0;e<i.length;e++)t.push(i[e].clone());return t}function Sc(i){let t=i.getRenderTarget();return t===null?i.outputColorSpace:t.isXRRenderTarget===!0?t.texture.colorSpace:Xt.workingColorSpace}var Du={clone:Zi,merge:He},Nf=`void main() {+ gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );+}`,Uf=`void main() {+ gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );+}`,un=class extends ei{constructor(t){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=Nf,this.fragmentShader=Uf,this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,t!==void 0&&this.setValues(t)}copy(t){return super.copy(t),this.fragmentShader=t.fragmentShader,this.vertexShader=t.vertexShader,this.uniforms=Zi(t.uniforms),this.uniformsGroups=Df(t.uniformsGroups),this.defines=Object.assign({},t.defines),this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.fog=t.fog,this.lights=t.lights,this.clipping=t.clipping,this.extensions=Object.assign({},t.extensions),this.glslVersion=t.glslVersion,this.defaultAttributeValues=Object.assign({},t.defaultAttributeValues),this.index0AttributeName=t.index0AttributeName,this.uniformsNeedUpdate=t.uniformsNeedUpdate,this}toJSON(t){let e=super.toJSON(t);e.glslVersion=this.glslVersion,e.uniforms={};for(let s in this.uniforms){let o=this.uniforms[s].value;o&&o.isTexture?e.uniforms[s]={type:"t",value:o.toJSON(t).uuid}:o&&o.isColor?e.uniforms[s]={type:"c",value:o.getHex()}:o&&o.isVector2?e.uniforms[s]={type:"v2",value:o.toArray()}:o&&o.isVector3?e.uniforms[s]={type:"v3",value:o.toArray()}:o&&o.isVector4?e.uniforms[s]={type:"v4",value:o.toArray()}:o&&o.isMatrix3?e.uniforms[s]={type:"m3",value:o.toArray()}:o&&o.isMatrix4?e.uniforms[s]={type:"m4",value:o.toArray()}:e.uniforms[s]={value:o}}Object.keys(this.defines).length>0&&(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}fromJSON(t,e){if(super.fromJSON(t,e),t.uniforms!==void 0)for(let n in t.uniforms){let s=t.uniforms[n];switch(this.uniforms[n]={},s.type){case"t":this.uniforms[n].value=e[s.value]||null;break;case"c":this.uniforms[n].value=new Nt().setHex(s.value);break;case"v2":this.uniforms[n].value=new Pt().fromArray(s.value);break;case"v3":this.uniforms[n].value=new P().fromArray(s.value);break;case"v4":this.uniforms[n].value=new me().fromArray(s.value);break;case"m3":this.uniforms[n].value=new Ut().fromArray(s.value);break;case"m4":this.uniforms[n].value=new se().fromArray(s.value);break;default:this.uniforms[n].value=s.value}}if(t.defines!==void 0&&(this.defines=t.defines),t.vertexShader!==void 0&&(this.vertexShader=t.vertexShader),t.fragmentShader!==void 0&&(this.fragmentShader=t.fragmentShader),t.glslVersion!==void 0&&(this.glslVersion=t.glslVersion),t.extensions!==void 0)for(let n in t.extensions)this.extensions[n]=t.extensions[n];return t.lights!==void 0&&(this.lights=t.lights),t.clipping!==void 0&&(this.clipping=t.clipping),this}},qo=class extends un{constructor(t){super(t),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}},Us=class extends ei{constructor(t){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new Nt(16777215),this.roughness=1,this.metalness=0,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Nt(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Za,this.normalScale=new Pt(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Tn,this.envMapIntensity=1,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.defines={STANDARD:""},this.color.copy(t.color),this.roughness=t.roughness,this.metalness=t.metalness,this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive.copy(t.emissive),this.emissiveMap=t.emissiveMap,this.emissiveIntensity=t.emissiveIntensity,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.roughnessMap=t.roughnessMap,this.metalnessMap=t.metalnessMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapRotation.copy(t.envMapRotation),this.envMapIntensity=t.envMapIntensity,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.flatShading=t.flatShading,this.fog=t.fog,this}};var Zo=class extends ei{constructor(t){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=xu,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(t)}copy(t){return super.copy(t),this.depthPacking=t.depthPacking,this.map=t.map,this.alphaMap=t.alphaMap,this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this}},jo=class extends ei{constructor(t){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(t)}copy(t){return super.copy(t),this.map=t.map,this.alphaMap=t.alphaMap,this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this}};function Ss(i,t){return!i||i.constructor===t?i:typeof t.BYTES_PER_ELEMENT=="number"?new t(i):Array.prototype.slice.call(i)}function kl(i){return i!==void 0&&i.inTangents!==void 0&&i.outTangents!==void 0}var Si=class{constructor(t,e,n,s){this.parameterPositions=t,this._cachedIndex=0,this.resultBuffer=s!==void 0?s:new e.constructor(n),this.sampleValues=e,this.valueSize=n,this.settings=null,this.DefaultSettings_={}}evaluate(t){let e=this.parameterPositions,n=this._cachedIndex,s=e[n],r=e[n-1];n:{t:{let o;e:{i:if(!(t<s)){for(let a=n+2;;){if(s===void 0){if(t<r)break i;return n=e.length,this._cachedIndex=n,this.copySampleValue_(n-1)}if(n===a)break;if(r=s,s=e[++n],t<s)break t}o=e.length;break e}if(!(t>=r)){let a=e[1];t<a&&(n=2,r=a);for(let c=n-2;;){if(r===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(n===c)break;if(s=r,r=e[--n-1],t>=r)break t}o=n,n=0;break e}break n}for(;n<o;){let a=n+o>>>1;t<e[a]?o=a:n=a+1}if(s=e[n],r=e[n-1],r===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(s===void 0)return n=e.length,this._cachedIndex=n,this.copySampleValue_(n-1)}this._cachedIndex=n,this.intervalChanged_(n,r,s)}return this.interpolate_(n,r,t,s)}getSettings_(){return this.settings||this.DefaultSettings_}copySampleValue_(t){let e=this.resultBuffer,n=this.sampleValues,s=this.valueSize,r=t*s;for(let o=0;o!==s;++o)e[o]=n[r+o];return e}interpolate_(){throw new Error("THREE.Interpolant: Call to abstract method.")}intervalChanged_(){}},Jo=class extends Si{constructor(t,e,n,s){super(t,e,n,s),this._weightPrev=-0,this._offsetPrev=-0,this._weightNext=-0,this._offsetNext=-0,this.DefaultSettings_={endingStart:Gl,endingEnd:Gl}}intervalChanged_(t,e,n){let s=this.parameterPositions,r=t-2,o=t+1,a=s[r],c=s[o];if(a===void 0)switch(this.getSettings_().endingStart){case Wl:r=t,a=2*e-n;break;case Xl:r=s.length-2,a=e+s[r]-s[r+1];break;default:r=t,a=n}if(c===void 0)switch(this.getSettings_().endingEnd){case Wl:o=t,c=2*n-e;break;case Xl:o=1,c=n+s[1]-s[0];break;default:o=t-1,c=e}let l=(n-e)*.5,u=this.valueSize;this._weightPrev=l/(e-a),this._weightNext=l/(c-n),this._offsetPrev=r*u,this._offsetNext=o*u}interpolate_(t,e,n,s){let r=this.resultBuffer,o=this.sampleValues,a=this.valueSize,c=t*a,l=c-a,u=this._offsetPrev,f=this._offsetNext,h=this._weightPrev,p=this._weightNext,g=(n-e)/(s-e),v=g*g,m=v*g,d=-h*m+2*h*v-h*g,S=(1+h)*m+(-1.5-2*h)*v+(-.5+h)*g+1,T=(-1-p)*m+(1.5+p)*v+.5*g,y=p*m-p*v;for(let b=0;b!==a;++b)r[b]=d*o[u+b]+S*o[l+b]+T*o[c+b]+y*o[f+b];return r}},$o=class extends Si{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,c=t*a,l=c-a,u=(n-e)/(s-e),f=1-u;for(let h=0;h!==a;++h)r[h]=o[l+h]*f+o[c+h]*u;return r}},Ko=class extends Si{constructor(t,e,n,s){super(t,e,n,s)}interpolate_(t){return this.copySampleValue_(t-1)}},Qo=class extends Si{interpolate_(t,e,n,s){let r=this.resultBuffer,o=this.sampleValues,a=this.valueSize,c=t*a,l=c-a,u=this.inTangents,f=this.outTangents;if(!u||!f){let g=(n-e)/(s-e),v=1-g;for(let m=0;m!==a;++m)r[m]=o[l+m]*v+o[c+m]*g;return r}let h=a*2,p=t-1;for(let g=0;g!==a;++g){let v=o[l+g],m=o[c+g],d=p*h+g*2,S=f[d],T=f[d+1],y=t*h+g*2,b=u[y],w=u[y+1],C=Of(n,e,S,b,s);r[g]=Nu(C,v,T,w,m)}return r}};function Nu(i,t,e,n,s){let r=1-i;return r*r*r*t+3*r*r*i*e+3*r*i*i*n+i*i*i*s}function Ff(i,t,e,n,s){let r=1-i;return 3*r*r*(e-t)+6*r*i*(n-e)+3*i*i*(s-n)}function Of(i,t,e,n,s){let r=(i-t)/(s-t);for(let o=0;o<8;o++){let a=Nu(r,t,e,n,s)-i;if(Math.abs(a)<1e-10)break;let c=Ff(r,t,e,n,s);if(Math.abs(c)<1e-10)break;r=Math.max(0,Math.min(1,r-a/c))}return r}var dn=class{constructor(t,e,n,s){if(t===void 0)throw new Error("THREE.KeyframeTrack: track name is undefined");if(e===void 0||e.length===0)throw new Error("THREE.KeyframeTrack: no keyframes in track named "+t);this.name=t,this.times=Ss(e,this.TimeBufferType),this.values=Ss(n,this.ValueBufferType),this.setInterpolation(s||this.DefaultInterpolation)}static toJSON(t){let e=t.constructor,n;if(e.toJSON!==this.toJSON)n=e.toJSON(t);else{n={name:t.name,times:Ss(t.times,Array),values:Ss(t.values,Array)};let s=t.getInterpolation();s!==t.DefaultInterpolation&&(n.interpolation=s),kl(t.settings)&&(n.settings={inTangents:Ss(t.settings.inTangents,Array),outTangents:Ss(t.settings.outTangents,Array)})}return n.type=t.ValueTypeName,n}InterpolantFactoryMethodDiscrete(t){return new Ko(this.times,this.values,this.getValueSize(),t)}InterpolantFactoryMethodLinear(t){return new $o(this.times,this.values,this.getValueSize(),t)}InterpolantFactoryMethodSmooth(t){return new Jo(this.times,this.values,this.getValueSize(),t)}InterpolantFactoryMethodBezier(t){let e=new Qo(this.times,this.values,this.getValueSize(),t);return this.settings&&(e.inTangents=this.settings.inTangents,e.outTangents=this.settings.outTangents),e}setInterpolation(t){let e;switch(t){case lr:e=this.InterpolantFactoryMethodDiscrete;break;case Bo:e=this.InterpolantFactoryMethodLinear;break;case Ao:e=this.InterpolantFactoryMethodSmooth;break;case Hl:e=this.InterpolantFactoryMethodBezier;break}if(e===void 0){let n="unsupported interpolation for "+this.ValueTypeName+" keyframe track named "+this.name;if(this.createInterpolant===void 0)if(t!==this.DefaultInterpolation)this.setInterpolation(this.DefaultInterpolation);else throw new Error(n);return It("KeyframeTrack:",n),this}return this.createInterpolant=e,this}getInterpolation(){switch(this.createInterpolant){case this.InterpolantFactoryMethodDiscrete:return lr;case this.InterpolantFactoryMethodLinear:return Bo;case this.InterpolantFactoryMethodSmooth:return Ao;case this.InterpolantFactoryMethodBezier:return Hl}}getValueSize(){return this.values.length/this.times.length}shift(t){if(t!==0){let e=this.times;for(let n=0,s=e.length;n!==s;++n)e[n]+=t}return this}scale(t){if(t!==1){let e=this.times;for(let n=0,s=e.length;n!==s;++n)e[n]*=t;kl(this.settings)&&(Hh(this.settings.inTangents,t),Hh(this.settings.outTangents,t))}return this}trim(t,e){let n=this.times,s=n.length,r=0,o=s-1;for(;r!==s&&n[r]<t;)++r;for(;o!==-1&&n[o]>e;)--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&&(Dt("KeyframeTrack: Invalid value size in track.",this),t=!1);let n=this.times,s=this.values,r=n.length;r===0&&(Dt("KeyframeTrack: Track is empty.",this),t=!1);let o=null;for(let a=0;a!==r;a++){let c=n[a];if(typeof c=="number"&&isNaN(c)){Dt("KeyframeTrack: Time is not a valid number.",this,a,c),t=!1;break}if(o!==null&&o>c){Dt("KeyframeTrack: Out of order keys.",this,a,c,o),t=!1;break}o=c}if(s!==void 0&&$d(s))for(let a=0,c=s.length;a!==c;++a){let l=s[a];if(isNaN(l)){Dt("KeyframeTrack: Value is not a valid number.",this,a,l),t=!1;break}}return t}optimize(){let t=this.times.slice(),e=this.values.slice(),n=this.getValueSize(),s=this.getInterpolation()===Ao,r=t.length-1,o=1;for(let a=1;a<r;++a){let c=!1,l=t[a],u=t[a+1];if(l!==u&&(a!==1||l!==t[0]))if(s)c=!0;else{let f=a*n,h=f-n,p=f+n;for(let g=0;g!==n;++g){let v=e[f+g];if(v!==e[h+g]||v!==e[p+g]){c=!0;break}}}if(c){if(a!==o){t[o]=t[a];let f=a*n,h=o*n;for(let p=0;p!==n;++p)e[h+p]=e[f+p]}++o}}if(r>0){t[o]=t[r];for(let a=r*n,c=o*n,l=0;l!==n;++l)e[c+l]=e[a+l];++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,kl(this.settings)&&(s.settings={inTangents:this.settings.inTangents.slice(),outTangents:this.settings.outTangents.slice()}),s}};function Hh(i,t){for(let e=0,n=i.length;e!==n;e+=2)i[e]*=t}dn.prototype.ValueTypeName="";dn.prototype.TimeBufferType=Float32Array;dn.prototype.ValueBufferType=Float32Array;dn.prototype.DefaultInterpolation=Bo;var bi=class extends dn{constructor(t,e,n){super(t,e,n)}};bi.prototype.ValueTypeName="bool";bi.prototype.ValueBufferType=Array;bi.prototype.DefaultInterpolation=lr;bi.prototype.InterpolantFactoryMethodLinear=void 0;bi.prototype.InterpolantFactoryMethodSmooth=void 0;var ta=class extends dn{constructor(t,e,n,s){super(t,e,n,s)}};ta.prototype.ValueTypeName="color";var ea=class extends dn{constructor(t,e,n,s){super(t,e,n,s)}};ea.prototype.ValueTypeName="number";var na=class extends Si{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,c=(n-e)/(s-e),l=t*a;for(let u=l+a;l!==u;l+=4)pe.slerpFlat(r,0,o,l-a,o,l,c);return r}},Mr=class extends dn{constructor(t,e,n,s){super(t,e,n,s)}InterpolantFactoryMethodLinear(t){return new na(this.times,this.values,this.getValueSize(),t)}};Mr.prototype.ValueTypeName="quaternion";Mr.prototype.InterpolantFactoryMethodSmooth=void 0;var wi=class extends dn{constructor(t,e,n){super(t,e,n)}};wi.prototype.ValueTypeName="string";wi.prototype.ValueBufferType=Array;wi.prototype.DefaultInterpolation=lr;wi.prototype.InterpolantFactoryMethodLinear=void 0;wi.prototype.InterpolantFactoryMethodSmooth=void 0;var ia=class extends dn{constructor(t,e,n,s){super(t,e,n,s)}};ia.prototype.ValueTypeName="vector";var sa=class{constructor(t,e,n){let s=this,r=!1,o=0,a=0,c,l=[];this.onStart=void 0,this.onLoad=t,this.onProgress=e,this.onError=n,this._abortController=null,this.itemStart=function(u){a++,r===!1&&s.onStart!==void 0&&s.onStart(u,o,a),r=!0},this.itemEnd=function(u){o++,s.onProgress!==void 0&&s.onProgress(u,o,a),o===a&&(r=!1,s.onLoad!==void 0&&s.onLoad())},this.itemError=function(u){s.onError!==void 0&&s.onError(u)},this.resolveURL=function(u){return u=u.normalize("NFC"),c?c(u):u},this.setURLModifier=function(u){return c=u,this},this.addHandler=function(u,f){return l.push(u,f),this},this.removeHandler=function(u){let f=l.indexOf(u);return f!==-1&&l.splice(f,2),this},this.getHandler=function(u){for(let f=0,h=l.length;f<h;f+=2){let p=l[f],g=l[f+1];if(p.global&&(p.lastIndex=0),p.test(u))return g}return null},this.abort=function(){return this.abortController.abort(),this._abortController=null,this}}get abortController(){return this._abortController||(this._abortController=new AbortController),this._abortController}},Uu=new sa,ra=class{constructor(t){this.manager=t!==void 0?t:Uu,this.crossOrigin="anonymous",this.withCredentials=!1,this.path="",this.resourcePath="",this.requestHeader={},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}load(){}loadAsync(t,e){let n=this;return new Promise(function(s,r){n.load(t,s,e,r)})}parse(){}setCrossOrigin(t){return this.crossOrigin=t,this}setWithCredentials(t){return this.withCredentials=t,this}setPath(t){return this.path=t,this}setResourcePath(t){return this.resourcePath=t,this}setRequestHeader(t){return this.requestHeader=t,this}abort(){return this}};ra.DEFAULT_MATERIAL_NAME="__DEFAULT";var Fs=class extends ye{constructor(t,e=1){super(),this.isLight=!0,this.type="Light",this.color=new Nt(t),this.intensity=e}copy(t,e){return super.copy(t,e),this.color.copy(t.color),this.intensity=t.intensity,this}toJSON(t){let e=super.toJSON(t);return e.object.color=this.color.getHex(),e.object.intensity=this.intensity,e}},Sr=class extends Fs{constructor(t,e,n){super(t,n),this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(ye.DEFAULT_UP),this.updateMatrix(),this.groundColor=new Nt(e)}copy(t,e){return super.copy(t,e),this.groundColor.copy(t.groundColor),this}toJSON(t){let e=super.toJSON(t);return e.object.groundColor=this.groundColor.getHex(),e}},Vl=new se,Gh=new P,Wh=new P,br=class{constructor(t){this.camera=t,this.intensity=1,this.bias=0,this.biasNode=null,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new Pt(512,512),this.mapType=Qe,this.map=null,this.mapPass=null,this.matrix=new se,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new Ns,this._frameExtents=new Pt(1,1),this._viewportCount=1,this._viewports=[new me(0,0,1,1)]}getViewportCount(){return this._viewportCount}getCamera(){return this.camera}getFrustum(){return this._frustum}updateMatrices(t){let e=this.camera;Gh.setFromMatrixPosition(t.matrixWorld),e.position.copy(Gh),Wh.setFromMatrixPosition(t.target.matrixWorld),e.lookAt(Wh),e.updateMatrixWorld(),this._updateMatrix(e,this.matrix,this._frustum)}_updateMatrix(t,e,n,s){Vl.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),n.setFromProjectionMatrix(Vl,t.coordinateSystem,t.reversedDepth);let r=this._frameExtents,o=s?s.z/r.x:1,a=s?s.w/r.y:1,c=s?s.x/r.x:0,l=s?s.y/r.y:0;t.coordinateSystem===Cs||t.reversedDepth?e.set(.5*o,0,0,.5*o+c,0,.5*a,0,.5*a+l,0,0,1,0,0,0,0,1):e.set(.5*o,0,0,.5*o+c,0,.5*a,0,.5*a+l,0,0,.5,.5,0,0,0,1),e.multiply(Vl)}getViewport(t){return this._viewports[t]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(t){return this.camera=t.camera.clone(),this.intensity=t.intensity,this.bias=t.bias,this.radius=t.radius,this.autoUpdate=t.autoUpdate,this.needsUpdate=t.needsUpdate,this.normalBias=t.normalBias,this.blurSamples=t.blurSamples,this.mapSize.copy(t.mapSize),this.biasNode=t.biasNode,this}clone(){return new this.constructor().copy(this)}toJSON(){let t={};return t.intensity=this.intensity,t.bias=this.bias,t.normalBias=this.normalBias,t.radius=this.radius,t.blurSamples=this.blurSamples,t.mapSize=this.mapSize.toArray(),t.camera=this.camera.toJSON(!1).object,delete t.camera.matrix,t}},Eo=new P,To=new pe,Bn=new P,wr=class extends ye{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new se,this.projectionMatrix=new se,this.projectionMatrixInverse=new se,this.coordinateSystem=wn,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.matrixWorld.decompose(Eo,To,Bn),Bn.x===1&&Bn.y===1&&Bn.z===1?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(Eo,To,Bn.set(1,1,1)).invert()}updateWorldMatrix(t,e,n=!1){super.updateWorldMatrix(t,e,n),this.matrixWorld.decompose(Eo,To,Bn),Bn.x===1&&Bn.y===1&&Bn.z===1?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(Eo,To,Bn.set(1,1,1)).invert()}clone(){return new this.constructor().copy(this)}},gi=new P,Xh=new Pt,Yh=new Pt,Ue=class extends wr{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=Ps*2*Math.atan(e),this.updateProjectionMatrix()}getFocalLength(){let t=Math.tan(or*.5*this.fov);return .5*this.getFilmHeight()/t}getEffectiveFOV(){return Ps*2*Math.atan(Math.tan(or*.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){gi.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),e.set(gi.x,gi.y).multiplyScalar(-t/gi.z),gi.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(gi.x,gi.y).multiplyScalar(-t/gi.z)}getViewSize(t,e){return this.getViewBounds(t,Xh,Yh),e.subVectors(Yh,Xh)}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(or*.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 c=o.fullWidth,l=o.fullHeight;r+=o.offsetX*s/c,e-=o.offsetY*n/l,s*=o.width/c,n*=o.height/l}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}};var Yl=class extends br{constructor(){super(new Ue(90,1,.5,500)),this.isPointLightShadow=!0}},Er=class extends Fs{constructor(t,e,n=0,s=2){super(t,e),this.isPointLight=!0,this.type="PointLight",this.distance=n,this.decay=s,this.shadow=new Yl}get power(){return this.intensity*4*Math.PI}set power(t){this.intensity=t/(4*Math.PI)}dispose(){super.dispose(),this.shadow.dispose()}copy(t,e){return super.copy(t,e),this.distance=t.distance,this.decay=t.decay,this.shadow=t.shadow.clone(),this}toJSON(t){let e=super.toJSON(t);return e.object.distance=this.distance,e.object.decay=this.decay,e.object.shadow=this.shadow.toJSON(),e}},Os=class extends wr{constructor(t=-1,e=1,n=1,s=-1,r=.1,o=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=t,this.right=e,this.top=n,this.bottom=s,this.near=r,this.far=o,this.updateProjectionMatrix()}copy(t,e){return super.copy(t,e),this.left=t.left,this.right=t.right,this.top=t.top,this.bottom=t.bottom,this.near=t.near,this.far=t.far,this.zoom=t.zoom,this.view=t.view===null?null:Object.assign({},t.view),this}setViewOffset(t,e,n,s,r,o){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.right-this.left)/(2*this.zoom),e=(this.top-this.bottom)/(2*this.zoom),n=(this.right+this.left)/2,s=(this.top+this.bottom)/2,r=n-t,o=n+t,a=s+e,c=s-e;if(this.view!==null&&this.view.enabled){let l=(this.right-this.left)/this.view.fullWidth/this.zoom,u=(this.top-this.bottom)/this.view.fullHeight/this.zoom;r+=l*this.view.offsetX,o=r+l*this.view.width,a-=u*this.view.offsetY,c=a-u*this.view.height}this.projectionMatrix.makeOrthographic(r,o,a,c,this.near,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(t){let e=super.toJSON(t);return e.object.zoom=this.zoom,e.object.left=this.left,e.object.right=this.right,e.object.top=this.top,e.object.bottom=this.bottom,e.object.near=this.near,e.object.far=this.far,this.view!==null&&(e.object.view=Object.assign({},this.view)),e}},ql=class extends br{constructor(){super(new Os(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}},Tr=class extends Fs{constructor(t,e){super(t,e),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(ye.DEFAULT_UP),this.updateMatrix(),this.target=new ye,this.shadow=new ql}dispose(){super.dispose(),this.shadow.dispose()}copy(t){return super.copy(t),this.target=t.target.clone(),this.shadow=t.shadow.clone(),this}toJSON(t){let e=super.toJSON(t);return e.object.shadow=this.shadow.toJSON(),e.object.target=this.target.uuid,e}};var bs=-90,ws=1,oa=class extends ye{constructor(t,e,n){super(),this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;let s=new Ue(bs,ws,t,e);s.layers=this.layers,this.add(s);let r=new Ue(bs,ws,t,e);r.layers=this.layers,this.add(r);let o=new Ue(bs,ws,t,e);o.layers=this.layers,this.add(o);let a=new Ue(bs,ws,t,e);a.layers=this.layers,this.add(a);let c=new Ue(bs,ws,t,e);c.layers=this.layers,this.add(c);let l=new Ue(bs,ws,t,e);l.layers=this.layers,this.add(l)}updateCoordinateSystem(){let t=this.coordinateSystem,e=this.children.concat(),[n,s,r,o,a,c]=e;for(let l of e)this.remove(l);if(t===wn)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),c.up.set(0,1,0),c.lookAt(0,0,-1);else if(t===Cs)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),c.up.set(0,-1,0),c.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+t);for(let l of e)this.add(l),l.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,c,l,u]=this.children,f=t.getRenderTarget(),h=t.getActiveCubeFace(),p=t.getActiveMipmapLevel(),g=t.xr.enabled;t.xr.enabled=!1;let v=n.texture.generateMipmaps;n.texture.generateMipmaps=!1;let m=!1;t.isWebGLRenderer===!0?m=t.state.buffers.depth.getReversed():m=t.reversedDepthBuffer,t.setRenderTarget(n,0,s),m&&t.autoClear===!1&&t.clearDepth(),t.render(e,r),t.setRenderTarget(n,1,s),m&&t.autoClear===!1&&t.clearDepth(),t.render(e,o),t.setRenderTarget(n,2,s),m&&t.autoClear===!1&&t.clearDepth(),t.render(e,a),t.setRenderTarget(n,3,s),m&&t.autoClear===!1&&t.clearDepth(),t.render(e,c),t.setRenderTarget(n,4,s),m&&t.autoClear===!1&&t.clearDepth(),t.render(e,l),n.texture.generateMipmaps=v,t.setRenderTarget(n,5,s),m&&t.autoClear===!1&&t.clearDepth(),t.render(e,u),t.setRenderTarget(f,h,p),t.xr.enabled=g,n.texture.needsPMREMUpdate=!0}},aa=class extends Ue{constructor(t=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=t}};var bc="\\[\\]\\.:\\/",Bf=new RegExp("["+bc+"]","g"),wc="[^"+bc+"]",zf="[^"+bc.replace("\\.","")+"]",kf=/((?:WC+[\/:])*)/.source.replace("WC",wc),Vf=/(WCOD+)?/.source.replace("WCOD",zf),Hf=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",wc),Gf=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",wc),Wf=new RegExp("^"+kf+Vf+Hf+Gf+"$"),Xf=["material","materials","bones","map"],Zl=class{constructor(t,e,n){let s=n||ue.parseTrackName(e);this._targetGroup=t,this._bindings=t.subscribe_(e,s)}getValue(t,e){this.bind();let n=this._targetGroup.nCachedObjects_,s=this._bindings[n];s!==void 0&&s.getValue(t,e)}setValue(t,e){let n=this._bindings;for(let s=this._targetGroup.nCachedObjects_,r=n.length;s!==r;++s)n[s].setValue(t,e)}bind(){let t=this._bindings;for(let e=this._targetGroup.nCachedObjects_,n=t.length;e!==n;++e)t[e].bind()}unbind(){let t=this._bindings;for(let e=this._targetGroup.nCachedObjects_,n=t.length;e!==n;++e)t[e].unbind()}},ue=class i{constructor(t,e,n){this.path=e,this.parsedPath=n||i.parseTrackName(e),this.node=i.findNode(t,this.parsedPath.nodeName),this.rootNode=t,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(t,e,n){return t&&t.isAnimationObjectGroup?new i.Composite(t,e,n):new i(t,e,n)}static sanitizeNodeName(t){return t.replace(/\s/g,"_").replace(Bf,"")}static parseTrackName(t){let e=Wf.exec(t);if(e===null)throw new Error("THREE.PropertyBinding: Cannot parse trackName: "+t);let n={nodeName:e[2],objectName:e[3],objectIndex:e[4],propertyName:e[5],propertyIndex:e[6]},s=n.nodeName&&n.nodeName.lastIndexOf(".");if(s!==void 0&&s!==-1){let r=n.nodeName.substring(s+1);Xf.indexOf(r)!==-1&&(n.nodeName=n.nodeName.substring(0,s),n.objectName=r)}if(n.propertyName===null||n.propertyName.length===0)throw new Error("THREE.PropertyBinding: can not parse propertyName from trackName: "+t);return n}static findNode(t,e){if(e===void 0||e===""||e==="."||e===-1||e===t.name||e===t.uuid)return t;if(t.skeleton){let n=t.skeleton.getBoneByName(e);if(n!==void 0)return n}if(t.children){let n=function(r){for(let o=0;o<r.length;o++){let a=r[o];if(a.name===e||a.uuid===e)return a;let c=n(a.children);if(c)return c}return null},s=n(t.children);if(s)return s}return null}_getValue_unavailable(){}_setValue_unavailable(){}_getValue_direct(t,e){t[e]=this.targetObject[this.propertyName]}_getValue_array(t,e){let n=this.resolvedProperty;for(let s=0,r=n.length;s!==r;++s)t[e++]=n[s]}_getValue_arrayElement(t,e){t[e]=this.resolvedProperty[this.propertyIndex]}_getValue_toArray(t,e){this.resolvedProperty.toArray(t,e)}_setValue_direct(t,e){this.targetObject[this.propertyName]=t[e]}_setValue_direct_setNeedsUpdate(t,e){this.targetObject[this.propertyName]=t[e],this.targetObject.needsUpdate=!0}_setValue_direct_setMatrixWorldNeedsUpdate(t,e){this.targetObject[this.propertyName]=t[e],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_array(t,e){let n=this.resolvedProperty;for(let s=0,r=n.length;s!==r;++s)n[s]=t[e++]}_setValue_array_setNeedsUpdate(t,e){let n=this.resolvedProperty;for(let s=0,r=n.length;s!==r;++s)n[s]=t[e++];this.targetObject.needsUpdate=!0}_setValue_array_setMatrixWorldNeedsUpdate(t,e){let n=this.resolvedProperty;for(let s=0,r=n.length;s!==r;++s)n[s]=t[e++];this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_arrayElement(t,e){this.resolvedProperty[this.propertyIndex]=t[e]}_setValue_arrayElement_setNeedsUpdate(t,e){this.resolvedProperty[this.propertyIndex]=t[e],this.targetObject.needsUpdate=!0}_setValue_arrayElement_setMatrixWorldNeedsUpdate(t,e){this.resolvedProperty[this.propertyIndex]=t[e],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_fromArray(t,e){this.resolvedProperty.fromArray(t,e)}_setValue_fromArray_setNeedsUpdate(t,e){this.resolvedProperty.fromArray(t,e),this.targetObject.needsUpdate=!0}_setValue_fromArray_setMatrixWorldNeedsUpdate(t,e){this.resolvedProperty.fromArray(t,e),this.targetObject.matrixWorldNeedsUpdate=!0}_getValue_unbound(t,e){this.bind(),this.getValue(t,e)}_setValue_unbound(t,e){this.bind(),this.setValue(t,e)}bind(){let t=this.node,e=this.parsedPath,n=e.objectName,s=e.propertyName,r=e.propertyIndex;if(t||(t=i.findNode(this.rootNode,e.nodeName),this.node=t),this.getValue=this._getValue_unavailable,this.setValue=this._setValue_unavailable,!t){It("PropertyBinding: No target node found for track: "+this.path+".");return}if(n){let l=e.objectIndex;switch(n){case"materials":if(!t.material){Dt("PropertyBinding: Can not bind to material as node does not have a material.",this);return}if(!t.material.materials){Dt("PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.",this);return}t=t.material.materials;break;case"bones":if(!t.skeleton){Dt("PropertyBinding: Can not bind to bones as node does not have a skeleton.",this);return}t=t.skeleton.bones;for(let u=0;u<t.length;u++)if(t[u].name===l){l=u;break}break;case"map":if("map"in t){t=t.map;break}if(!t.material){Dt("PropertyBinding: Can not bind to material as node does not have a material.",this);return}if(!t.material.map){Dt("PropertyBinding: Can not bind to material.map as node.material does not have a map.",this);return}t=t.material.map;break;default:if(t[n]===void 0){Dt("PropertyBinding: Can not bind to objectName of node undefined.",this);return}t=t[n]}if(l!==void 0){if(t[l]===void 0){Dt("PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.",this,t);return}t=t[l]}}let o=t[s];if(o===void 0){let l=e.nodeName;Dt("PropertyBinding: Trying to update property for track: "+l+"."+s+" but it wasn't found.",t);return}let a=this.Versioning.None;this.targetObject=t,t.isMaterial===!0?a=this.Versioning.NeedsUpdate:t.isObject3D===!0&&(a=this.Versioning.MatrixWorldNeedsUpdate);let c=this.BindingType.Direct;if(r!==void 0){if(s==="morphTargetInfluences"){if(!t.geometry){Dt("PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.",this);return}if(!t.geometry.morphAttributes){Dt("PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.",this);return}t.morphTargetDictionary[r]!==void 0&&(r=t.morphTargetDictionary[r])}c=this.BindingType.ArrayElement,this.resolvedProperty=o,this.propertyIndex=r}else o.fromArray!==void 0&&o.toArray!==void 0?(c=this.BindingType.HasFromToArray,this.resolvedProperty=o):Array.isArray(o)?(c=this.BindingType.EntireArray,this.resolvedProperty=o):this.propertyName=s;this.getValue=this.GetterByBindingType[c],this.setValue=this.SetterByBindingTypeAndVersioning[c][a]}unbind(){this.node=null,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}};ue.Composite=Zl;ue.prototype.BindingType={Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3};ue.prototype.Versioning={None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2};ue.prototype.GetterByBindingType=[ue.prototype._getValue_direct,ue.prototype._getValue_array,ue.prototype._getValue_arrayElement,ue.prototype._getValue_toArray];ue.prototype.SetterByBindingTypeAndVersioning=[[ue.prototype._setValue_direct,ue.prototype._setValue_direct_setNeedsUpdate,ue.prototype._setValue_direct_setMatrixWorldNeedsUpdate],[ue.prototype._setValue_array,ue.prototype._setValue_array_setNeedsUpdate,ue.prototype._setValue_array_setMatrixWorldNeedsUpdate],[ue.prototype._setValue_arrayElement,ue.prototype._setValue_arrayElement_setNeedsUpdate,ue.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate],[ue.prototype._setValue_fromArray,ue.prototype._setValue_fromArray_setNeedsUpdate,ue.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];var cx=new Float32Array(1);var qh=new se,Wi=class{constructor(t,e,n=0,s=1/0){this.ray=new xi(t,e),this.near=n,this.far=s,this.camera=null,this.layers=new Ls,this.params={Mesh:{},Line:{threshold:1},LOD:{},Points:{threshold:1},Sprite:{}}}set(t,e){this.ray.set(t,e)}setFromCamera(t,e){e.isPerspectiveCamera?(this.ray.origin.setFromMatrixPosition(e.matrixWorld),this.ray.direction.set(t.x,t.y,.5).unproject(e).sub(this.ray.origin).normalize(),this.camera=e):e.isOrthographicCamera?(this.ray.origin.set(t.x,t.y,e.projectionMatrix.elements[14]).unproject(e),this.ray.direction.set(0,0,-1).transformDirection(e.matrixWorld),this.camera=e):Dt("Raycaster: Unsupported camera type: "+e.type)}setFromXRController(t){return qh.identity().extractRotation(t.matrixWorld),this.ray.origin.setFromMatrixPosition(t.matrixWorld),this.ray.direction.set(0,0,-1).applyMatrix4(qh),this}intersectObject(t,e=!0,n=[]){return jl(t,this,n,e),n.sort(Zh),n}intersectObjects(t,e=!0,n=[]){for(let s=0,r=t.length;s<r;s++)jl(t[s],this,n,e);return n.sort(Zh),n}};function Zh(i,t){return i.distance-t.distance}function jl(i,t,e,n){let s=!0;if(i.layers.test(t.layers)&&i.raycast(t,e)===!1&&(s=!1),s===!0&&n===!0){let r=i.children;for(let o=0,a=r.length;o<a;o++)jl(r[o],t,e,!0)}}var Bs=class{constructor(t=1,e=0,n=0){this.radius=t,this.phi=e,this.theta=n}set(t,e,n){return this.radius=t,this.phi=e,this.theta=n,this}copy(t){return this.radius=t.radius,this.phi=t.phi,this.theta=t.theta,this}makeSafe(){return this.phi=Vt(this.phi,1e-6,Math.PI-1e-6),this}setFromVector3(t){return this.setFromCartesianCoords(t.x,t.y,t.z)}setFromCartesianCoords(t,e,n){return this.radius=Math.sqrt(t*t+e*e+n*n),this.radius===0?(this.theta=0,this.phi=0):(this.theta=Math.atan2(t,n),this.phi=Math.acos(Vt(e/this.radius,-1,1))),this}clone(){return new this.constructor().copy(this)}};var Jl=class i{static{i.prototype.isMatrix2=!0}constructor(t,e,n,s){this.elements=[1,0,0,1],t!==void 0&&this.set(t,e,n,s)}identity(){return this.set(1,0,0,1),this}fromArray(t,e=0){for(let n=0;n<4;n++)this.elements[n]=t[n+e];return this}set(t,e,n,s){let r=this.elements;return r[0]=t,r[2]=e,r[1]=n,r[3]=s,this}};var Ar=class extends _r{constructor(t=10,e=10,n=4473924,s=8947848){n=new Nt(n),s=new Nt(s);let r=e/2,o=t/e,a=t/2,c=[],l=[];for(let h=0,p=0,g=-a;h<=e;h++,g+=o){c.push(-a,0,g,a,0,g),c.push(g,0,-a,g,0,a);let v=h===r?n:s;v.toArray(l,p),p+=3,v.toArray(l,p),p+=3,v.toArray(l,p),p+=3,v.toArray(l,p),p+=3}let u=new ve;u.setAttribute("position",new Yt(c,3)),u.setAttribute("color",new Yt(l,3));let f=new yi({vertexColors:!0,toneMapped:!1});super(u,f),this.type="GridHelper"}dispose(){super.dispose(),this.geometry.dispose(),this.material.dispose()}};var Cr=class extends _r{constructor(t,e=16776960){let n=new Uint16Array([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,4,1,5,2,6,3,7]),s=[1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1],r=new ve;r.setIndex(new cn(n,1)),r.setAttribute("position",new Yt(s,3)),super(r,new yi({color:e,toneMapped:!1})),this.box=t,this.type="Box3Helper",this.geometry.computeBoundingSphere()}updateMatrixWorld(t){let e=this.box;e.isEmpty()||(e.getCenter(this.position),e.getSize(this.scale),this.scale.multiplyScalar(.5),super.updateMatrixWorld(t))}dispose(){super.dispose(),this.geometry.dispose(),this.material.dispose()}};var Xi=class extends En{constructor(t,e=null){super(),this.object=t,this.domElement=e,this.enabled=!0,this.state=-1,this.keys={},this.mouseButtons={LEFT:null,MIDDLE:null,RIGHT:null},this.touches={ONE:null,TWO:null}}connect(t){this.domElement!==null&&this.disconnect(),this.domElement=t}disconnect(){}dispose(){}update(){}};function Ec(i,t,e,n){let s=Yf(n);switch(e){case mc:return i*t;case _c:return i*t/s.components*s.byteLength;case ma:return i*t/s.components*s.byteLength;case Pi:return i*t*2/s.components*s.byteLength;case ga:return i*t*2/s.components*s.byteLength;case gc:return i*t*3/s.components*s.byteLength;case xn:return i*t*4/s.components*s.byteLength;case _a:return i*t*4/s.components*s.byteLength;case Dr:case Nr:return Math.floor((i+3)/4)*Math.floor((t+3)/4)*8;case Ur:case Fr:return Math.floor((i+3)/4)*Math.floor((t+3)/4)*16;case ya:case Ma:return Math.max(i,16)*Math.max(t,8)/4;case xa:case va:return Math.max(i,8)*Math.max(t,8)/2;case Sa:case ba:case Ea:case Ta:return Math.floor((i+3)/4)*Math.floor((t+3)/4)*8;case wa:case Or:case Aa:return Math.floor((i+3)/4)*Math.floor((t+3)/4)*16;case Ca:return Math.floor((i+3)/4)*Math.floor((t+3)/4)*16;case Ra:return Math.floor((i+4)/5)*Math.floor((t+3)/4)*16;case Pa:return Math.floor((i+4)/5)*Math.floor((t+4)/5)*16;case Ia:return Math.floor((i+5)/6)*Math.floor((t+4)/5)*16;case La:return Math.floor((i+5)/6)*Math.floor((t+5)/6)*16;case Da:return Math.floor((i+7)/8)*Math.floor((t+4)/5)*16;case Na:return Math.floor((i+7)/8)*Math.floor((t+5)/6)*16;case Ua:return Math.floor((i+7)/8)*Math.floor((t+7)/8)*16;case Fa:return Math.floor((i+9)/10)*Math.floor((t+4)/5)*16;case Oa:return Math.floor((i+9)/10)*Math.floor((t+5)/6)*16;case Ba:return Math.floor((i+9)/10)*Math.floor((t+7)/8)*16;case za:return Math.floor((i+9)/10)*Math.floor((t+9)/10)*16;case ka:return Math.floor((i+11)/12)*Math.floor((t+9)/10)*16;case Va:return Math.floor((i+11)/12)*Math.floor((t+11)/12)*16;case Ha:case Ga:case Wa:return Math.ceil(i/4)*Math.ceil(t/4)*16;case Xa:case Ya:return Math.ceil(i/4)*Math.ceil(t/4)*8;case Br:case qa:return Math.ceil(i/4)*Math.ceil(t/4)*16}throw new Error(`Unable to determine texture byte length for ${e} format.`)}function Yf(i){switch(i){case Qe:case uc:return{byteLength:1,components:1};case Vs:case dc:case Ln:return{byteLength:2,components:1};case fa:case pa:return{byteLength:2,components:4};case Pn:case da:case In:return{byteLength:4,components:1};case fc:case pc:return{byteLength:4,components:3}}throw new Error(`THREE.TextureUtils: Unknown texture type ${i}.`)}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:"186"}}));typeof window<"u"&&(window.__THREE__?It("WARNING: Multiple instances of Three.js being imported."):window.__THREE__="186");function id(){let i=null,t=!1,e=null,n=null;function s(r,o){n=i.requestAnimationFrame(s),e(r,o)}return{start:function(){t!==!0&&e!==null&&i!==null&&(n=i.requestAnimationFrame(s),t=!0)},stop:function(){i!==null&&i.cancelAnimationFrame(n),t=!1},setAnimationLoop:function(r){e=r},setContext:function(r){i=r}}}function Zf(i){let t=new WeakMap;function e(a,c){let l=a.array,u=a.usage,f=l.byteLength,h=i.createBuffer();i.bindBuffer(c,h),i.bufferData(c,l,u),a.onUploadCallback();let p;if(l instanceof Float32Array)p=i.FLOAT;else if(typeof Float16Array<"u"&&l instanceof Float16Array)p=i.HALF_FLOAT;else if(l instanceof Uint16Array)a.isFloat16BufferAttribute?p=i.HALF_FLOAT:p=i.UNSIGNED_SHORT;else if(l instanceof Int16Array)p=i.SHORT;else if(l instanceof Uint32Array)p=i.UNSIGNED_INT;else if(l instanceof Int32Array)p=i.INT;else if(l instanceof Int8Array)p=i.BYTE;else if(l instanceof Uint8Array)p=i.UNSIGNED_BYTE;else if(l instanceof Uint8ClampedArray)p=i.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+l);return{buffer:h,type:p,bytesPerElement:l.BYTES_PER_ELEMENT,version:a.version,size:f}}function n(a,c,l){let u=c.array,f=c.updateRanges;if(i.bindBuffer(l,a),f.length===0)i.bufferSubData(l,0,u);else{f.sort((p,g)=>p.start-g.start);let h=0;for(let p=1;p<f.length;p++){let g=f[h],v=f[p];v.start<=g.start+g.count+1?g.count=Math.max(g.count,v.start+v.count-g.start):(++h,f[h]=v)}f.length=h+1;for(let p=0,g=f.length;p<g;p++){let v=f[p];i.bufferSubData(l,v.start*u.BYTES_PER_ELEMENT,u,v.start,v.count)}c.clearUpdateRanges()}c.onUploadCallback()}function s(a){return a.isInterleavedBufferAttribute&&(a=a.data),t.get(a)}function r(a){a.isInterleavedBufferAttribute&&(a=a.data);let c=t.get(a);c&&(i.deleteBuffer(c.buffer),t.delete(a))}function o(a,c){if(a.isInterleavedBufferAttribute&&(a=a.data),a.isGLBufferAttribute){let u=t.get(a);(!u||u.version<a.version)&&t.set(a,{buffer:a.buffer,type:a.type,bytesPerElement:a.elementSize,version:a.version});return}let l=t.get(a);if(l===void 0)t.set(a,e(a,c));else if(l.version<a.version){if(l.size!==a.array.byteLength)throw new Error("THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported.");n(l.buffer,a,c),l.version=a.version}}return{get:s,remove:r,update:o}}var jf=`#ifdef USE_ALPHAHASH+ if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;+#endif`,Jf=`#ifdef USE_ALPHAHASH+ const float ALPHA_HASH_SCALE = 0.05;+ float hash2D( vec2 value ) {+ return fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );+ }+ float hash3D( vec3 value ) {+ return hash2D( vec2( hash2D( value.xy ), value.z ) );+ }+ float getAlphaHashThreshold( vec3 position ) {+ float maxDeriv = max(+ length( dFdx( position.xyz ) ),+ length( dFdy( position.xyz ) )+ );+ float pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );+ vec2 pixScales = vec2(+ exp2( floor( log2( pixScale ) ) ),+ exp2( ceil( log2( pixScale ) ) )+ );+ vec2 alpha = vec2(+ hash3D( floor( pixScales.x * position.xyz ) ),+ hash3D( floor( pixScales.y * position.xyz ) )+ );+ float lerpFactor = fract( log2( pixScale ) );+ float x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;+ float a = min( lerpFactor, 1.0 - lerpFactor );+ vec3 cases = vec3(+ x * x / ( 2.0 * a * ( 1.0 - a ) ),+ ( x - 0.5 * a ) / ( 1.0 - a ),+ 1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )+ );+ float threshold = ( x < ( 1.0 - a ) )+ ? ( ( x < a ) ? cases.x : cases.y )+ : cases.z;+ return clamp( threshold , 1.0e-6, 1.0 );+ }+#endif`,$f=`#ifdef USE_ALPHAMAP+ diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;+#endif`,Kf=`#ifdef USE_ALPHAMAP+ uniform sampler2D alphaMap;+#endif`,Qf=`#ifdef USE_ALPHATEST+ #ifdef ALPHA_TO_COVERAGE+ diffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );+ if ( diffuseColor.a == 0.0 ) discard;+ #else+ if ( diffuseColor.a < alphaTest ) discard;+ #endif+#endif`,tp=`#ifdef USE_ALPHATEST+ uniform float alphaTest;+#endif`,ep=`#ifdef USE_AOMAP+ float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;+ reflectedLight.indirectDiffuse *= ambientOcclusion;+ #if defined( USE_CLEARCOAT )+ clearcoatSpecularIndirect *= ambientOcclusion;+ #endif+ #if defined( USE_SHEEN )+ sheenSpecularIndirect *= ambientOcclusion;+ #endif+ #if defined( USE_ENVMAP ) && defined( STANDARD )+ float dotNV = saturate( dot( geometryNormal, geometryViewDir ) );+ reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );+ #endif+#endif`,np=`#ifdef USE_AOMAP+ uniform sampler2D aoMap;+ uniform float aoMapIntensity;+#endif`,ip=`#ifdef USE_BATCHING+ #if ! defined( GL_ANGLE_multi_draw )+ #define gl_DrawID _gl_DrawID+ uniform int _gl_DrawID;+ #endif+ uniform highp sampler2D batchingTexture;+ uniform highp usampler2D batchingIdTexture;+ mat4 getBatchingMatrix( const in float i ) {+ int size = textureSize( batchingTexture, 0 ).x;+ int j = int( i ) * 4;+ int x = j % size;+ int y = j / size;+ vec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 );+ vec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );+ vec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );+ vec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );+ return mat4( v1, v2, v3, v4 );+ }+ float getIndirectIndex( const in int i ) {+ int size = textureSize( batchingIdTexture, 0 ).x;+ int x = i % size;+ int y = i / size;+ return float( texelFetch( batchingIdTexture, ivec2( x, y ), 0 ).r );+ }+#endif+#ifdef USE_BATCHING_COLOR+ uniform sampler2D batchingColorTexture;+ vec4 getBatchingColor( const in float i ) {+ int size = textureSize( batchingColorTexture, 0 ).x;+ int j = int( i );+ int x = j % size;+ int y = j / size;+ return texelFetch( batchingColorTexture, ivec2( x, y ), 0 );+ }+#endif`,sp=`#ifdef USE_BATCHING+ mat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );+#endif`,rp=`vec3 transformed = vec3( position );+#ifdef USE_ALPHAHASH+ vPosition = vec3( position );+#endif`,op=`vec3 objectNormal = vec3( normal );+#ifdef USE_TANGENT+ vec3 objectTangent = vec3( tangent.xyz );+#endif`,ap=`float G_BlinnPhong_Implicit( ) {+ return 0.25;}-.mark svg {- display: block;- width: 100%;- height: 100%;+float D_BlinnPhong( const in float shininess, const in float dotNH ) {+ return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );}-.seed-form {- display: flex;- align-items: center;- gap: 6px;+vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {+ vec3 halfDir = normalize( lightDir + viewDir );+ float dotNH = saturate( dot( normal, halfDir ) );+ float dotVH = saturate( dot( viewDir, halfDir ) );+ vec3 F = F_Schlick( specularColor, 1.0, dotVH );+ float G = G_BlinnPhong_Implicit( );+ float D = D_BlinnPhong( shininess, dotNH );+ return F * ( G * D );+} // validated`,lp=`#ifdef USE_IRIDESCENCE+ const mat3 XYZ_TO_REC709 = mat3(+ 3.2404542, -0.9692660, 0.0556434,+ -1.5371385, 1.8760108, -0.2040259,+ -0.4985314, 0.0415560, 1.0572252+ );+ vec3 Fresnel0ToIor( vec3 fresnel0 ) {+ vec3 sqrtF0 = sqrt( fresnel0 );+ return ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );+ }+ vec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {+ return pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );+ }+ float IorToFresnel0( float transmittedIor, float incidentIor ) {+ return pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));+ }+ vec3 evalSensitivity( float OPD, vec3 shift ) {+ float phase = 2.0 * PI * OPD * 1.0e-9;+ vec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );+ vec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );+ vec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );+ vec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );+ xyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );+ xyz /= 1.0685e-7;+ vec3 rgb = XYZ_TO_REC709 * xyz;+ return rgb;+ }+ vec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {+ vec3 I;+ float iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );+ float sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );+ float cosTheta2Sq = 1.0 - sinTheta2Sq;+ if ( cosTheta2Sq < 0.0 ) {+ return vec3( 1.0 );+ }+ float cosTheta2 = sqrt( cosTheta2Sq );+ float R0 = IorToFresnel0( iridescenceIOR, outsideIOR );+ float R12 = F_Schlick( R0, 1.0, cosTheta1 );+ float T121 = 1.0 - R12;+ float phi12 = 0.0;+ if ( iridescenceIOR < outsideIOR ) phi12 = PI;+ float phi21 = PI - phi12;+ vec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) ); vec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );+ vec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );+ vec3 phi23 = vec3( 0.0 );+ if ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;+ if ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;+ if ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;+ float OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;+ vec3 phi = vec3( phi21 ) + phi23;+ vec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );+ vec3 r123 = sqrt( R123 );+ vec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );+ vec3 C0 = R12 + Rs;+ I = C0;+ vec3 Cm = Rs - T121;+ for ( int m = 1; m <= 2; ++ m ) {+ Cm *= r123;+ vec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );+ I += Cm * Sm;+ }+ return max( I, vec3( 0.0 ) );+ }+#endif`,cp=`#ifdef USE_BUMPMAP+ uniform sampler2D bumpMap;+ uniform float bumpScale;+ vec2 dHdxy_fwd() {+ vec2 dSTdx = dFdx( vBumpMapUv );+ vec2 dSTdy = dFdy( vBumpMapUv );+ float Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;+ float dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;+ float dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;+ return vec2( dBx, dBy );+ }+ vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {+ vec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );+ vec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );+ vec3 vN = surf_norm;+ vec3 R1 = cross( vSigmaY, vN );+ vec3 R2 = cross( vN, vSigmaX );+ float fDet = dot( vSigmaX, R1 ) * faceDirection;+ vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );+ return normalize( abs( fDet ) * surf_norm - vGrad );+ }+#endif`,hp=`#if NUM_CLIPPING_PLANES > 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`,up=`#if NUM_CLIPPING_PLANES > 0+ varying vec3 vClipPosition;+ uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];+#endif`,dp=`#if NUM_CLIPPING_PLANES > 0+ varying vec3 vClipPosition;+#endif`,fp=`#if NUM_CLIPPING_PLANES > 0+ vClipPosition = - mvPosition.xyz;+#endif`,pp=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )+ diffuseColor *= vColor;+#endif`,mp=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )+ varying vec4 vColor;+#endif`,gp=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )+ varying vec4 vColor;+#endif`,_p=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )+ vColor = vec4( 1.0 );+#endif+#ifdef USE_COLOR_ALPHA+ vColor *= color;+#elif defined( USE_COLOR )+ vColor.rgb *= color;+#endif+#ifdef USE_INSTANCING_COLOR+ vColor.rgb *= instanceColor.rgb;+#endif+#ifdef USE_BATCHING_COLOR+ vColor *= getBatchingColor( getIndirectIndex( gl_DrawID ) );+#endif`,xp=`#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 );}-.seed-form label {- font:- 10px ui-monospace,- monospace;- text-transform: uppercase;- letter-spacing: 0.12em;- color: var(--muted);- margin-right: 4px;+#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 );}-.seed-form input {- width: 74px;- padding: 6px 8px;- font:- 12px ui-monospace,- monospace;+#define inverseTransformDirection transformDirectionByInverseViewMatrix+vec3 transformNormalByInverseViewMatrix( in vec3 normal, in mat4 viewMatrix ) {+ return normalize( ( vec4( normal, 0.0 ) * viewMatrix ).xyz );}-.seed-form button {- padding: 6px 10px;- font-size: 12px;+vec3 transformDirectionByInverseViewMatrix( in vec3 dir, in mat4 viewMatrix ) {+ return normalize( ( vec4( dir, 0.0 ) * viewMatrix ).xyz );}-.intro {- padding: 32px 28px;- display: flex;- align-items: flex-end;- justify-content: space-between;- gap: 20px;+bool isPerspectiveMatrix( mat4 m ) {+ return m[ 2 ][ 3 ] == - 1.0;}-.intro p {- max-width: 440px;- color: var(--muted);- margin-top: 14px;+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 );}-.intro .eyebrow {- margin-bottom: 12px;+vec3 BRDF_Lambert( const in vec3 diffuseColor ) {+ return RECIPROCAL_PI * diffuseColor;}-.actions {- display: flex;- align-items: center;- gap: 8px;- flex-wrap: wrap;+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 );}-.workspace {- display: grid;- grid-template-columns: minmax(0, 1fr) 270px;- gap: 22px;- padding: 0 28px 28px;+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`,yp=`#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`,vp=`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;+#endif`,Mp=`#ifdef USE_DISPLACEMENTMAP+ uniform sampler2D displacementMap;+ uniform float displacementScale;+ uniform float displacementBias;+#endif`,Sp=`#ifdef USE_DISPLACEMENTMAP+ transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );+#endif`,bp=`#ifdef USE_EMISSIVEMAP+ vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );+ #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE+ emissiveColor = sRGBTransferEOTF( emissiveColor );+ #endif+ totalEmissiveRadiance *= emissiveColor.rgb;+#endif`,wp=`#ifdef USE_EMISSIVEMAP+ uniform sampler2D emissiveMap;+#endif`,Ep="gl_FragColor = linearToOutputTexel( gl_FragColor );",Tp=`vec4 LinearTransferOETF( in vec4 value ) {+ return value;}-.panel {- background: var(--panel);- border: 1px solid var(--line);- border-radius: 8px;- overflow: hidden;+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 );}-.panel-head {- display: flex;- align-items: center;- justify-content: space-between;- padding: 16px 20px;- border-bottom: 1px solid var(--line);- gap: 10px;+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 );+}`,Ap=`#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 = transformNormalByInverseViewMatrix( 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 * reflectVec );+ #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+#endif`,Cp=`#ifdef USE_ENVMAP+ uniform float envMapIntensity;+ uniform mat3 envMapRotation;+ #ifdef ENVMAP_TYPE_CUBE+ uniform samplerCube envMap;+ #else+ uniform sampler2D envMap;+ #endif+#endif`,Rp=`#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`,Pp=`#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`,Ip=`#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 = transformNormalByInverseViewMatrix( transformedNormal, viewMatrix );+ #ifdef ENVMAP_MODE_REFLECTION+ vReflect = reflect( cameraToVertex, worldNormal );+ #else+ vReflect = refract( cameraToVertex, worldNormal, refractionRatio );+ #endif+ #endif+#endif`,Lp=`#ifdef USE_FOG+ vFogDepth = - mvPosition.z;+#endif`,Dp=`#ifdef USE_FOG+ varying float vFogDepth;+#endif`,Np=`#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`,Up=`#ifdef USE_FOG+ uniform vec3 fogColor;+ varying float vFogDepth;+ #ifdef FOG_EXP2+ uniform float fogDensity;+ #else+ uniform float fogNear;+ uniform float fogFar;+ #endif+#endif`,Fp=`#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+}`,Op=`#ifdef USE_LIGHTMAP+ uniform sampler2D lightMap;+ uniform float lightMapIntensity;+#endif`,Bp=`LambertMaterial material;+material.diffuseColor = diffuseColor.rgb;+material.specularStrength = specularStrength;`,zp=`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 );}-.side {- display: flex;- flex-direction: column;- gap: 20px;+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 );}-.section {- border-top: 1px solid var(--line);- padding-top: 18px;+#define RE_Direct RE_Direct_Lambert+#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,kp=`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;}-.section h3 {- margin-bottom: 15px;+vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {+ vec3 worldNormal = transformNormalByInverseViewMatrix( normal, viewMatrix );+ vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );+ return irradiance;}-.field {- display: grid;- gap: 7px;- margin: 14px 0;+vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {+ vec3 irradiance = ambientLightColor;+ return irradiance;}-.field > span {- display: flex;- justify-content: space-between;- font-size: 12px;- color: var(--muted);+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;}-.metrics {- display: grid;- grid-template-columns: repeat(3, 1fr);- gap: 1px;- background: var(--line);- border: 1px solid var(--line);- border-radius: 6px;- overflow: hidden;+float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {+ return smoothstep( coneCosine, penumbraCosine, angleCosine );}-.metric {- background: var(--bg);- padding: 13px 15px;+#if NUM_SUN_LIGHTS > 0+ struct SunLight {+ vec3 direction;+ vec3 color;+ };+ uniform SunLight sunLights[ NUM_SUN_LIGHTS ];+ void getSunLightInfo( const in SunLight sunLight, out IncidentLight light ) {+ light.color = sunLight.color;+ light.direction = sunLight.direction;+ light.visible = true;+ }+#endif+#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+#include <lightprobes_pars_fragment>`,Vp=`#ifdef USE_ENVMAP+ vec3 getIBLIrradiance( const in vec3 normal ) {+ #ifdef ENVMAP_TYPE_CUBE_UV+ vec3 worldNormal = transformNormalByInverseViewMatrix( 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, pow4( roughness ) ) );+ reflectVec = transformDirectionByInverseViewMatrix( reflectVec, viewMatrix );+ vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );+ return envMapColor.rgb * envMapIntensity;+ #else+ return vec3( 0.0 );+ #endif+ }+ #ifdef USE_RETROREFLECTION+ vec3 getIBLRetroRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {+ #ifdef ENVMAP_TYPE_CUBE_UV+ vec3 retroVec = normalize( mix( viewDir, normal, pow4( roughness ) ) );+ retroVec = transformDirectionByInverseViewMatrix( retroVec, viewMatrix );+ vec4 envMapColor = textureCubeUV( envMap, envMapRotation * retroVec, roughness );+ return envMapColor.rgb * envMapIntensity;+ #else+ return vec3( 0.0 );+ #endif+ }+ #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+ }+ #ifdef USE_RETROREFLECTION+ vec3 getIBLAnisotropyRetroRadiance( 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 getIBLRetroRadiance( viewDir, bentNormal, roughness );+ #else+ return vec3( 0.0 );+ #endif+ }+ #endif+ #endif+#endif`,Hp=`ToonMaterial material;+material.diffuseColor = diffuseColor.rgb;`,Gp=`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 );}-.metric strong {- display: block;- font:- 24px ui-monospace,- monospace;- letter-spacing: -0.06em;+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 );}-.metric span {- font-size: 10px;- color: var(--muted);- text-transform: uppercase;- letter-spacing: 0.09em;+#define RE_Direct RE_Direct_Toon+#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,Wp=`BlinnPhongMaterial material;+material.diffuseColor = diffuseColor.rgb;+material.specularColor = specular;+material.specularShininess = shininess;+material.specularStrength = specularStrength;`,Xp=`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;}-canvas {- display: block;- max-width: 100%;+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 );}-.status-line {- display: flex;- justify-content: space-between;- gap: 20px;- padding: 14px 28px;- border-top: 1px solid var(--line);- font:- 10px ui-monospace,- monospace;- color: var(--muted);+#define RE_Direct RE_Direct_BlinnPhong+#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,Yp=`PhysicalMaterial material;+material.diffuseColor = diffuseColor.rgb;+material.diffuseContribution = diffuseColor.rgb * ( 1.0 - metalnessFactor );+material.metalness = 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 = min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor;+ material.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor );+#else+ material.specularColor = vec3( 0.04 );+ material.specularColorBlended = mix( material.specularColor, 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_RETROREFLECTION+ material.retroreflectivity = retroreflectivity;+#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.0001, 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`,qp=`uniform sampler2D dfgLUT;+struct PhysicalMaterial {+ vec3 diffuseColor;+ vec3 diffuseContribution;+ vec3 specularColor;+ vec3 specularColorBlended;+ float roughness;+ float metalness;+ float specularF90;+ float dispersion;+ vec2 dfg;+ vec3 multiScatteringCompensation;+ #ifdef USE_RETROREFLECTION+ float retroreflectivity;+ #endif+ #ifdef USE_CLEARCOAT+ float clearcoat;+ float clearcoatRoughness;+ vec3 clearcoatF0;+ float clearcoatF90;+ #endif+ #ifdef USE_IRIDESCENCE+ float iridescence;+ float iridescenceIOR;+ float iridescenceThickness;+ vec3 iridescenceFresnel;+ vec3 iridescenceF0Dielectric;+ vec3 iridescenceF0Metallic;+ #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 );}-.dot {- width: 6px;- height: 6px;- display: inline-block;- background: var(--accent);- border-radius: 50%;- margin-right: 6px;+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 );}-.toast {- position: fixed;- z-index: 99;- left: 50%;- bottom: 22px;- transform: translateX(-50%);- max-width: 90vw;- background: var(--ink);- color: var(--bg);- padding: 11px 18px;- border-radius: 6px;- box-shadow: 0 3px 30px #0004;- font-size: 12px;+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 );}-.toast:empty {- display: none;+#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 ) );+ return 0.5 / max( gv + gl, EPSILON );+ }+ 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.specularColorBlended;+ 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 );}-[hidden] {- display: none !important;+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;}-.sr-only {- position: absolute;- width: 1px;- height: 1px;- padding: 0;- margin: -1px;- overflow: hidden;- clip-path: inset(50%);- white-space: nowrap;- border: 0;+float LTC_ClippedSphereFormFactor( const in vec3 f ) {+ float l = length( f );+ return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );}-@media (max-width: 800px) {- .workspace {- grid-template-columns: 1fr;- }- .side {- display: grid;- grid-template-columns: repeat(2, minmax(0, 1fr));- }- .intro {- align-items: flex-start;- flex-direction: column;- }- .intro h1 {- font-size: 44px;- }+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;}-@media (max-width: 480px) {- .masthead {- padding: 13px 16px;- gap: 8px;- flex-wrap: wrap;- }- .intro {- padding: 26px 16px;- }- .intro h1 {- font-size: 38px;- }- .workspace {- padding: 0 16px 20px;- gap: 18px;- }- .side {- grid-template-columns: 1fr;- }- .seed-form label {- display: none;- }- .status-line {- padding: 12px 16px;- }- .status-line span:last-child {- display: none;- }- .metrics .metric {- padding: 12px 10px;- }- .panel-head {- padding: 12px;- }- .actions {- gap: 6px;- }+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 * transpose( 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 );}-@media (prefers-reduced-motion: reduce) {- *,- *::before,- *::after {- scroll-behavior: auto !important;- animation: none !important;- transition: none !important;- }+#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 );}--:root {- --bg: #203b37;- --ink: #f1f0d9;- --muted: #d6e2c8;- --line: #ddeacd45;- --accent: #d3e4a5;+float V_Neubelt( float dotNV, float dotNL ) {+ return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );}-.masthead {- position: absolute;- inset: 0 0 auto;- z-index: 5;- background: linear-gradient(#112b35b0, transparent);- border: 0;+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 );}-.masthead input,-.masthead button {- background: #18353655;+#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 rInv = 1.0 / ( roughness + 0.1 );+ float a = -1.9362 + 1.0678 * roughness + 0.4573 * r2 - 0.8469 * rInv;+ float b = -0.6014 + 0.5538 * roughness - 0.4670 * r2 - 0.1255 * rInv;+ float DG = exp( a * dotNV + b );+ return saturate( DG );}-.world-stage {- position: relative;- height: 100dvh;- min-height: 560px;- background: #94b6bb;- overflow: hidden;+vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {+ float dotNV = saturate( dot( normal, viewDir ) );+ vec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg;+ return specularColor * fab.x + specularF90 * fab.y;}-#world {- position: absolute;- inset: 0;- width: 100%;- height: 100%;- max-width: none;- touch-action: none;- outline-offset: -3px;+#ifdef USE_IRIDESCENCE+void computeMultiscatteringIridescence( const in vec2 fab, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, inout vec3 singleScatter, inout vec3 multiScatter ) {+#else+void computeMultiscattering( const in vec2 fab, const in vec3 specularColor, const in float specularF90, inout vec3 singleScatter, inout vec3 multiScatter ) {+#endif+ #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;}-.world-heading {- position: absolute;- left: 30px;- top: 92px;- pointer-events: none;- text-shadow: 0 2px 25px #0d282966;+#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.specularColorBlended * t2.x + ( material.specularF90 - material.specularColorBlended ) * t2.y );+ reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );+ reflectedLight.directDiffuse += lightColor * material.diffuseContribution * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );+ #ifdef USE_CLEARCOAT+ vec3 Ncc = geometryClearcoatNormal;+ vec2 uvClearcoat = LTC_Uv( Ncc, viewDir, material.clearcoatRoughness );+ vec4 t1Clearcoat = texture2D( ltc_1, uvClearcoat );+ vec4 t2Clearcoat = texture2D( ltc_2, uvClearcoat );+ mat3 mInvClearcoat = mat3(+ vec3( t1Clearcoat.x, 0, t1Clearcoat.y ),+ vec3( 0, 1, 0 ),+ vec3( t1Clearcoat.z, 0, t1Clearcoat.w )+ );+ vec3 fresnelClearcoat = material.clearcoatF0 * t2Clearcoat.x + ( material.clearcoatF90 - material.clearcoatF0 ) * t2Clearcoat.y;+ clearcoatSpecularDirect += lightColor * fresnelClearcoat * LTC_Evaluate( Ncc, viewDir, position, mInvClearcoat, rectCoords );+ #endif+ }+#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 );++ float sheenAlbedoV = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );+ float sheenAlbedoL = IBLSheenBRDF( geometryNormal, directLight.direction, material.sheenRoughness );++ float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * max( sheenAlbedoV, sheenAlbedoL );++ irradiance *= sheenEnergyComp;++ #endif+ vec3 specularBRDF = BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );+ #ifdef USE_RETROREFLECTION+ vec3 retroViewDir = reflect( - geometryViewDir, geometryNormal );+ vec3 retroSpecularBRDF = BRDF_GGX( directLight.direction, retroViewDir, geometryNormal, material );+ specularBRDF = mix( specularBRDF, retroSpecularBRDF, saturate( material.retroreflectivity ) );+ #endif+ reflectedLight.directSpecular += irradiance * specularBRDF * material.multiScatteringCompensation;+ vec3 halfDir = normalize( directLight.direction + geometryViewDir );+ float dotVH = saturate( dot( geometryViewDir, halfDir ) );+ vec3 F = F_Schlick( material.specularColor, material.specularF90, dotVH );+ #ifdef USE_RETROREFLECTION+ vec3 retroHalfDir = normalize( directLight.direction + retroViewDir );+ float dotRetroVH = saturate( dot( retroViewDir, retroHalfDir ) );+ vec3 retroF = F_Schlick( material.specularColor, material.specularF90, dotRetroVH );+ F = mix( F, retroF, saturate( material.retroreflectivity ) );+ #endif+ reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseContribution ) * ( 1.0 - F );}-.world-heading .eyebrow {- font-size: 9px;+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 ) {+ vec3 singleScattering = vec3( 0.0 );+ vec3 multiScattering = vec3( 0.0 );+ #ifdef USE_IRIDESCENCE+ computeMultiscatteringIridescence( material.dfg, material.specularColor, material.specularF90, material.iridescence, material.iridescenceF0Dielectric, singleScattering, multiScattering );+ #else+ computeMultiscattering( material.dfg, material.specularColor, material.specularF90, singleScattering, multiScattering );+ #endif+ vec3 diffuse = irradiance * BRDF_Lambert( material.diffuseContribution ) * ( 1.0 - singleScattering - multiScattering );+ #ifdef USE_SHEEN+ float sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );+ sheenSpecularIndirect += irradiance * material.sheenColor * sheenAlbedo * RECIPROCAL_PI;+ float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo;+ diffuse *= sheenEnergyComp;+ #endif+ reflectedLight.indirectDiffuse += diffuse;}-.world-heading h1 {- font:- clamp(50px, 6.5vw, 88px) / 0.91 Georgia,- serif;- letter-spacing: -0.065em;- margin: 14px 0 18px;+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 ) * RECIPROCAL_PI;+ #endif+ vec3 singleScatteringDielectric = vec3( 0.0 );+ vec3 multiScatteringDielectric = vec3( 0.0 );+ vec3 singleScatteringMetallic = vec3( 0.0 );+ vec3 multiScatteringMetallic = vec3( 0.0 );+ #ifdef USE_IRIDESCENCE+ computeMultiscatteringIridescence( material.dfg, material.specularColor, material.specularF90, material.iridescence, material.iridescenceF0Dielectric, singleScatteringDielectric, multiScatteringDielectric );+ computeMultiscatteringIridescence( material.dfg, material.diffuseColor, material.specularF90, material.iridescence, material.iridescenceF0Metallic, singleScatteringMetallic, multiScatteringMetallic );+ #else+ computeMultiscattering( material.dfg, material.specularColor, material.specularF90, singleScatteringDielectric, multiScatteringDielectric );+ computeMultiscattering( material.dfg, material.diffuseColor, material.specularF90, singleScatteringMetallic, multiScatteringMetallic );+ #endif+ vec3 singleScattering = mix( singleScatteringDielectric, singleScatteringMetallic, material.metalness );+ vec3 multiScattering = mix( multiScatteringDielectric, multiScatteringMetallic, material.metalness );+ vec3 totalScatteringDielectric = singleScatteringDielectric + multiScatteringDielectric;+ vec3 diffuse = material.diffuseContribution * ( 1.0 - totalScatteringDielectric );+ vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;+ vec3 indirectSpecular = radiance * singleScattering;+ indirectSpecular += multiScattering * cosineWeightedIrradiance;+ vec3 indirectDiffuse = diffuse * cosineWeightedIrradiance;+ #ifdef USE_SHEEN+ float sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );+ float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo;+ indirectSpecular *= sheenEnergyComp;+ indirectDiffuse *= sheenEnergyComp;+ #endif+ reflectedLight.indirectSpecular += indirectSpecular;+ reflectedLight.indirectDiffuse += indirectDiffuse;}-.world-heading > p:last-child {- font-size: 12px;- line-height: 1.7;+#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 );+}`,Zp=`+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 ) {+ vec3 iridescenceFresnelDielectric = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );+ vec3 iridescenceFresnelMetallic = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.diffuseColor );+ material.iridescenceFresnel = mix( iridescenceFresnelDielectric, iridescenceFresnelMetallic, material.metalness );+ material.iridescenceF0Dielectric = Schlick_to_F0( iridescenceFresnelDielectric, 1.0, dotNVi );+ material.iridescenceF0Metallic = Schlick_to_F0( iridescenceFresnelMetallic, 1.0, dotNVi );+ }+#endif+#ifdef STANDARD+ float dotNVms = saturate( dot( geometryNormal, geometryViewDir ) );+ material.dfg = texture2D( dfgLUT, vec2( material.roughness, dotNVms ) ).rg;+ #if ( NUM_SUN_LIGHTS > 0 || NUM_DIR_LIGHTS > 0 || NUM_POINT_LIGHTS > 0 || NUM_SPOT_LIGHTS > 0 )+ float EssMs = material.dfg.x + material.dfg.y;+ material.multiScatteringCompensation = 1.0 + material.specularColorBlended * ( 1.0 / EssMs - 1.0 );+ #endif+#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 ) && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) )+ 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_SUN_LIGHTS > 0 ) && defined( RE_Direct )+ SunLight sunLight;+ #if defined( USE_SHADOWMAP ) && NUM_SUN_LIGHT_SHADOWS > 0+ SunLightShadow sunLightShadow;+ #endif+ #pragma unroll_loop_start+ for ( int i = 0; i < NUM_SUN_LIGHTS; i ++ ) {+ sunLight = sunLights[ i ];+ getSunLightInfo( sunLight, directLight );+ #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SUN_LIGHT_SHADOWS )+ sunLightShadow = sunLightShadows[ i ];+ directLight.color *= ( directLight.visible && receiveShadow ) ? getSunShadow( sunShadowMap[ i ], sunLightShadow, UNROLLED_LOOP_INDEX ) : 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+ #ifdef USE_LIGHT_PROBES_GRID+ vec3 probeWorldPos = ( ( vec4( geometryPosition, 1.0 ) - viewMatrix[ 3 ] ) * viewMatrix ).xyz;+ vec3 probeWorldNormal = transformNormalByInverseViewMatrix( geometryNormal, viewMatrix );+ irradiance += getLightProbeGridIrradiance( probeWorldPos, probeWorldNormal );+ #endif+#endif+#if defined( RE_IndirectSpecular )+ vec3 radiance = vec3( 0.0 );+ vec3 clearcoatRadiance = vec3( 0.0 );+#endif`,jp=`#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( ENVMAP_TYPE_CUBE_UV )+ #if defined( STANDARD ) || defined( LAMBERT ) || defined( PHONG )+ iblIrradiance += getIBLIrradiance( geometryNormal );+ #endif+ #endif+#endif+#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )+ #ifdef USE_ANISOTROPY+ vec3 iblRadiance = getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );+ #else+ vec3 iblRadiance = getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );+ #endif+ #ifdef USE_RETROREFLECTION+ #ifdef USE_ANISOTROPY+ vec3 retroIBLRadiance = getIBLAnisotropyRetroRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );+ #else+ vec3 retroIBLRadiance = getIBLRetroRadiance( geometryViewDir, geometryNormal, material.roughness );+ #endif+ iblRadiance = mix( iblRadiance, retroIBLRadiance, saturate( material.retroreflectivity ) );+ #endif+ radiance += iblRadiance;+ #ifdef USE_CLEARCOAT+ clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );+ #endif+#endif`,Jp=`#if defined( RE_IndirectDiffuse )+ #if defined( LAMBERT ) || defined( PHONG )+ irradiance += iblIrradiance;+ #endif+ 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`,$p=`#ifdef USE_LIGHT_PROBES_GRID+uniform highp sampler3D probesSH;+uniform vec3 probesMin;+uniform vec3 probesMax;+uniform vec3 probesResolution;+vec3 getLightProbeGridIrradiance( vec3 worldPos, vec3 worldNormal ) {+ vec3 res = probesResolution;+ vec3 gridRange = probesMax - probesMin;+ vec3 resMinusOne = res - 1.0;+ vec3 probeSpacing = gridRange / resMinusOne;+ vec3 samplePos = worldPos + worldNormal * probeSpacing * 0.5;+ vec3 uvw = clamp( ( samplePos - probesMin ) / gridRange, 0.0, 1.0 );+ uvw = uvw * resMinusOne / res + 0.5 / res;+ float nz = res.z;+ float paddedSlices = nz + 2.0;+ float atlasDepth = 7.0 * paddedSlices;+ float uvZBase = uvw.z * nz + 1.0;+ vec4 s0 = texture( probesSH, vec3( uvw.xy, ( uvZBase ) / atlasDepth ) );+ vec4 s1 = texture( probesSH, vec3( uvw.xy, ( uvZBase + paddedSlices ) / atlasDepth ) );+ vec4 s2 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 2.0 * paddedSlices ) / atlasDepth ) );+ vec4 s3 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 3.0 * paddedSlices ) / atlasDepth ) );+ vec4 s4 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 4.0 * paddedSlices ) / atlasDepth ) );+ vec4 s5 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 5.0 * paddedSlices ) / atlasDepth ) );+ vec4 s6 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 6.0 * paddedSlices ) / atlasDepth ) );+ vec3 c0 = s0.xyz;+ vec3 c1 = vec3( s0.w, s1.xy );+ vec3 c2 = vec3( s1.zw, s2.x );+ vec3 c3 = s2.yzw;+ vec3 c4 = s3.xyz;+ vec3 c5 = vec3( s3.w, s4.xy );+ vec3 c6 = vec3( s4.zw, s5.x );+ vec3 c7 = s5.yzw;+ vec3 c8 = s6.xyz;+ float x = worldNormal.x, y = worldNormal.y, z = worldNormal.z;+ vec3 result = c0 * 0.886227;+ result += c1 * 2.0 * 0.511664 * y;+ result += c2 * 2.0 * 0.511664 * z;+ result += c3 * 2.0 * 0.511664 * x;+ result += c4 * 2.0 * 0.429043 * x * y;+ result += c5 * 2.0 * 0.429043 * y * z;+ result += c6 * ( 0.743125 * z * z - 0.247708 );+ result += c7 * 2.0 * 0.429043 * x * z;+ result += c8 * 0.429043 * ( x * x - y * y );+ return max( result, vec3( 0.0 ) );}-.world-toolbar {- position: absolute;- right: 22px;- top: 89px;- display: grid;- gap: 7px;+#endif`,Kp=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )+ gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;+#endif`,Qp=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )+ uniform float logDepthBufFC;+ varying float vFragDepth;+ varying float vIsPerspective;+#endif`,tm=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER+ varying float vFragDepth;+ varying float vIsPerspective;+#endif`,em=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER+ vFragDepth = 1.0 + gl_Position.w;+ vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );+#endif`,nm=`#ifdef USE_MAP+ vec4 sampledDiffuseColor = texture2D( map, vMapUv );+ #ifdef DECODE_VIDEO_TEXTURE+ sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );+ #endif+ diffuseColor *= sampledDiffuseColor;+#endif`,im=`#ifdef USE_MAP+ uniform sampler2D map;+#endif`,sm=`#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`,rm=`#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`,om=`float metalnessFactor = metalness;+#ifdef USE_METALNESSMAP+ vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );+ metalnessFactor *= texelMetalness.b;+#endif`,am=`#ifdef USE_METALNESSMAP+ uniform sampler2D metalnessMap;+#endif`,lm=`#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`,cm=`#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`,hm=`#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`,um=`#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`,dm=`#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`,fm=`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+ #ifdef DOUBLE_SIDED+ 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+ #ifdef DOUBLE_SIDED+ tbn2[0] *= faceDirection;+ tbn2[1] *= faceDirection;+ #endif+#endif+vec3 nonPerturbedNormal = normal;`,pm=`#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;+ #if defined( USE_PACKED_NORMALMAP )+ mapN = vec3( mapN.xy, sqrt( saturate( 1.0 - dot( mapN.xy, mapN.xy ) ) ) );+ #endif+ mapN.xy *= normalScale;+ normal = normalize( tbn * mapN );+#elif defined( USE_BUMPMAP )+ normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );+#endif`,mm=`#ifndef FLAT_SHADED+ varying vec3 vNormal;+ #ifdef USE_TANGENT+ varying vec3 vTangent;+ varying vec3 vBitangent;+ #endif+#endif`,gm=`#ifndef FLAT_SHADED+ varying vec3 vNormal;+ #ifdef USE_TANGENT+ varying vec3 vTangent;+ varying vec3 vBitangent;+ #endif+#endif`,_m=`#ifndef FLAT_SHADED+ vNormal = normalize( transformedNormal );+ #ifdef USE_TANGENT+ vTangent = normalize( transformedTangent );+ vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );+ #ifdef FLIP_SIDED+ vBitangent = - vBitangent;+ #endif+ #endif+#endif`,xm=`#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`,ym=`#ifdef USE_CLEARCOAT+ vec3 clearcoatNormal = nonPerturbedNormal;+#endif`,vm=`#ifdef USE_CLEARCOAT_NORMALMAP+ vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;+ clearcoatMapN.xy *= clearcoatNormalScale;+ clearcoatNormal = normalize( tbn2 * clearcoatMapN );+#endif`,Mm=`#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`,Sm=`#ifdef USE_IRIDESCENCEMAP+ uniform sampler2D iridescenceMap;+#endif+#ifdef USE_IRIDESCENCE_THICKNESSMAP+ uniform sampler2D iridescenceThicknessMap;+#endif`,bm=`#ifdef OPAQUE+diffuseColor.a = 1.0;+#endif+#ifdef USE_TRANSMISSION+diffuseColor.a *= material.transmissionAlpha;+#endif+gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,wm=`vec3 packNormalToRGB( const in vec3 normal ) {+ return normalize( normal ) * 0.5 + 0.5;}-.world-toolbar button,-.build-actions button,-.world-time button,-.world-pad button {- background: #17352eaa;- backdrop-filter: blur(8px);- font-size: 11px;+vec3 unpackRGBToNormal( const in vec3 rgb ) {+ return 2.0 * rgb.xyz - 1.0;}-.build-actions .primary {- background: #d3e4a5;- color: #203b37;+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 );}-.world-crosshair {- position: absolute;- top: 50%;- left: 50%;- transform: translate(-50%, -50%);- font-size: 25px;- color: #fff9;- pointer-events: none;+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 );}-.world-coordinates {- position: absolute;- left: 25px;- bottom: 184px;- display: grid;- gap: 3px;- font:- 9px/1.6 ui-monospace,- monospace;- text-shadow: 0 1px 3px #000;+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 );}-.world-bottom {- position: absolute;- bottom: 24px;- left: 50%;- transform: translateX(-50%);- display: flex;- flex-direction: column;- align-items: center;- gap: 10px;- width: 90%;- pointer-events: none;+float unpackRGBAToDepth( const in vec4 v ) {+ return dot( v, UnpackFactors4 );}-.world-bottom > p {- font:- 10px ui-monospace,- monospace;- text-align: center;- text-shadow: 0 1px 4px #000;- background: #153e3466;- padding: 6px 12px;- border-radius: 4px;+float unpackRGBToDepth( const in vec3 v ) {+ return dot( v, UnpackFactors3 );}-.hotbar {- display: flex;- gap: 6px;- pointer-events: auto;+float unpackRGToDepth( const in vec2 v ) {+ return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g;}-.hotbar button {- width: 55px;- height: 54px;- background: #18382fd9;- border: 1px solid #ffffff33;- border-radius: 5px;- padding: 5px;- display: flex;- align-items: center;- justify-content: center;- flex-direction: column;- gap: 4px;- font:- 8px ui-monospace,- monospace;+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 );}-.hotbar button[aria-pressed="true"] {- border: 2px solid #edebb7;- box-shadow: 0 0 20px #b9d98e44;+vec2 unpackRGBATo2Half( const in vec4 v ) {+ return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );}-.hotbar i {- width: 21px;- height: 21px;- box-shadow: inset -5px -5px #0002;- display: block;+float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {+ return ( viewZ + near ) / ( near - far );}-.build-actions {- display: flex;- gap: 8px;- pointer-events: auto;+float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {+ #ifdef USE_REVERSED_DEPTH_BUFFER++ return depth * ( far - near ) - far;+ #else+ return depth * ( near - far ) - near;+ #endif}-.world-time {- position: absolute;- right: 22px;- bottom: 184px;- display: grid;- gap: 7px;- width: 125px;- font:- 9px ui-monospace,- monospace;+float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {+ return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );}-.world-time input {- width: 100%;+float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {++ #ifdef USE_REVERSED_DEPTH_BUFFER+ return ( near * far ) / ( ( near - far ) * depth - near );+ #else+ return ( near * far ) / ( ( far - near ) * depth - far );+ #endif+}`,Em=`#ifdef PREMULTIPLIED_ALPHA+ gl_FragColor.rgb *= gl_FragColor.a;+#endif`,Tm=`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;`,Am=`#ifdef DITHERING+ gl_FragColor.rgb = dithering( gl_FragColor.rgb );+#endif`,Cm=`#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`,Rm=`float roughnessFactor = roughness;+#ifdef USE_ROUGHNESSMAP+ vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );+ roughnessFactor *= texelRoughness.g;+#endif`,Pm=`#ifdef USE_ROUGHNESSMAP+ uniform sampler2D roughnessMap;+#endif`,Im=`#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_SUN_LIGHT_SHADOWS > 0+ #define SUN_LIGHT_CASCADES 2+ #if defined( SHADOWMAP_TYPE_PCF )+ uniform sampler2DShadow sunShadowMap[ NUM_SUN_LIGHT_SHADOWS ];+ #else+ uniform sampler2D sunShadowMap[ NUM_SUN_LIGHT_SHADOWS ];+ #endif+ uniform mat4 sunShadowMatrix[ NUM_SUN_LIGHT_SHADOWS * SUN_LIGHT_CASCADES ];+ uniform vec4 sunShadowCascade[ NUM_SUN_LIGHT_SHADOWS * SUN_LIGHT_CASCADES ];+ varying vec4 vSunShadowWorldPosition;+ varying vec3 vSunShadowWorldNormal;+ struct SunLightShadow {+ float shadowIntensity;+ float shadowBias;+ float shadowNormalBias;+ float shadowRadius;+ vec2 shadowMapSize;+ };+ uniform SunLightShadow sunLightShadows[ NUM_SUN_LIGHT_SHADOWS ];+ #endif+ #if NUM_DIR_LIGHT_SHADOWS > 0+ #if defined( SHADOWMAP_TYPE_PCF )+ uniform sampler2DShadow directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];+ #else+ uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];+ #endif+ 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+ #if defined( SHADOWMAP_TYPE_PCF )+ uniform sampler2DShadow spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];+ #else+ uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];+ #endif+ 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+ #if defined( SHADOWMAP_TYPE_PCF )+ uniform samplerCubeShadow pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];+ #elif defined( SHADOWMAP_TYPE_BASIC )+ uniform samplerCube pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];+ #endif+ 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+ #if defined( SHADOWMAP_TYPE_PCF )+ float interleavedGradientNoise( vec2 position ) {+ return fract( 52.9829189 * fract( dot( position, vec2( 0.06711056, 0.00583715 ) ) ) );+ }+ vec2 vogelDiskSample( int sampleIndex, int samplesCount, float phi ) {+ const float goldenAngle = 2.399963229728653;+ float r = sqrt( ( float( sampleIndex ) + 0.5 ) / float( samplesCount ) );+ float theta = float( sampleIndex ) * goldenAngle + phi;+ return vec2( cos( theta ), sin( theta ) ) * r;+ }+ #endif+ #if defined( SHADOWMAP_TYPE_PCF )+ float getShadow( sampler2DShadow 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 ) {+ vec2 texelSize = vec2( 1.0 ) / shadowMapSize;+ float radius = shadowRadius * texelSize.x;+ float phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2;+ shadow = (+ texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 0, 5, phi ) * radius, shadowCoord.z ) ) ++ texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 1, 5, phi ) * radius, shadowCoord.z ) ) ++ texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 2, 5, phi ) * radius, shadowCoord.z ) ) ++ texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 3, 5, phi ) * radius, shadowCoord.z ) ) ++ texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 4, 5, phi ) * radius, shadowCoord.z ) )+ ) * 0.2;+ }+ return mix( 1.0, shadow, shadowIntensity );+ }+ #elif defined( SHADOWMAP_TYPE_VSM )+ float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {+ float shadow = 1.0;+ shadowCoord.xyz /= shadowCoord.w;+ #ifdef USE_REVERSED_DEPTH_BUFFER+ shadowCoord.z -= shadowBias;+ #else+ shadowCoord.z += shadowBias;+ #endif+ 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 ) {+ vec2 distribution = texture2D( shadowMap, shadowCoord.xy ).rg;+ float mean = distribution.x;+ float variance = distribution.y * distribution.y;+ #ifdef USE_REVERSED_DEPTH_BUFFER+ float hard_shadow = step( mean, shadowCoord.z );+ #else+ float hard_shadow = step( shadowCoord.z, mean );+ #endif++ if ( hard_shadow == 1.0 ) {+ shadow = 1.0;+ } else {+ variance = max( variance, 0.0000001 );+ float d = shadowCoord.z - mean;+ float p_max = variance / ( variance + d * d );+ p_max = clamp( ( p_max - 0.3 ) / 0.65, 0.0, 1.0 );+ shadow = max( hard_shadow, p_max );+ }+ }+ return mix( 1.0, shadow, shadowIntensity );+ }+ #else+ float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {+ float shadow = 1.0;+ shadowCoord.xyz /= shadowCoord.w;+ #ifdef USE_REVERSED_DEPTH_BUFFER+ shadowCoord.z -= shadowBias;+ #else+ shadowCoord.z += shadowBias;+ #endif+ 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 ) {+ float depth = texture2D( shadowMap, shadowCoord.xy ).r;+ #ifdef USE_REVERSED_DEPTH_BUFFER+ shadow = step( depth, shadowCoord.z );+ #else+ shadow = step( shadowCoord.z, depth );+ #endif+ }+ return mix( 1.0, shadow, shadowIntensity );+ }+ #endif+ #if NUM_SUN_LIGHT_SHADOWS > 0+ float getSunShadow(+ #if defined( SHADOWMAP_TYPE_PCF )+ sampler2DShadow shadowMap,+ #else+ sampler2D shadowMap,+ #endif+ SunLightShadow sunLightShadow,+ int shadowIndex+ ) {+ vec4 shadowWorldPosition = vec4( vSunShadowWorldPosition.xyz + vSunShadowWorldNormal * sunLightShadow.shadowNormalBias, 1.0 );+ float viewDepth = vSunShadowWorldPosition.w;+ int cascadeOffset = shadowIndex * SUN_LIGHT_CASCADES;+ float shadow = 1.0;+ for ( int i = SUN_LIGHT_CASCADES - 1; i >= 0; i -- ) {+ vec4 cascade = sunShadowCascade[ cascadeOffset + i ];+ if ( viewDepth >= cascade.x && viewDepth < cascade.y ) {+ float cascadeShadow = getShadow(+ shadowMap,+ sunLightShadow.shadowMapSize,+ sunLightShadow.shadowIntensity,+ sunLightShadow.shadowBias,+ sunLightShadow.shadowRadius,+ sunShadowMatrix[ cascadeOffset + i ] * shadowWorldPosition+ );+ shadow = mix( cascadeShadow, shadow, smoothstep( cascade.z, cascade.y, viewDepth ) );+ }+ }+ return shadow;+ }+ #endif+ #if NUM_POINT_LIGHT_SHADOWS > 0+ #if defined( SHADOWMAP_TYPE_PCF )+ float getPointShadow( samplerCubeShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {+ float shadow = 1.0;+ vec3 lightToPosition = shadowCoord.xyz;+ vec3 bd3D = normalize( lightToPosition );+ vec3 absVec = abs( lightToPosition );+ float viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z );+ if ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) {+ #ifdef USE_REVERSED_DEPTH_BUFFER+ float dp = ( shadowCameraNear * ( shadowCameraFar - viewSpaceZ ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );+ dp -= shadowBias;+ #else+ float dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );+ dp += shadowBias;+ #endif+ float texelSize = shadowRadius / shadowMapSize.x;+ vec3 absDir = abs( bd3D );+ vec3 tangent = absDir.x > absDir.z ? vec3( 0.0, 1.0, 0.0 ) : vec3( 1.0, 0.0, 0.0 );+ tangent = normalize( cross( bd3D, tangent ) );+ vec3 bitangent = cross( bd3D, tangent );+ float phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2;+ vec2 sample0 = vogelDiskSample( 0, 5, phi );+ vec2 sample1 = vogelDiskSample( 1, 5, phi );+ vec2 sample2 = vogelDiskSample( 2, 5, phi );+ vec2 sample3 = vogelDiskSample( 3, 5, phi );+ vec2 sample4 = vogelDiskSample( 4, 5, phi );+ shadow = (+ texture( shadowMap, vec4( bd3D + ( tangent * sample0.x + bitangent * sample0.y ) * texelSize, dp ) ) ++ texture( shadowMap, vec4( bd3D + ( tangent * sample1.x + bitangent * sample1.y ) * texelSize, dp ) ) ++ texture( shadowMap, vec4( bd3D + ( tangent * sample2.x + bitangent * sample2.y ) * texelSize, dp ) ) ++ texture( shadowMap, vec4( bd3D + ( tangent * sample3.x + bitangent * sample3.y ) * texelSize, dp ) ) ++ texture( shadowMap, vec4( bd3D + ( tangent * sample4.x + bitangent * sample4.y ) * texelSize, dp ) )+ ) * 0.2;+ }+ return mix( 1.0, shadow, shadowIntensity );+ }+ #elif defined( SHADOWMAP_TYPE_BASIC )+ float getPointShadow( samplerCube shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {+ float shadow = 1.0;+ vec3 lightToPosition = shadowCoord.xyz;+ vec3 absVec = abs( lightToPosition );+ float viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z );+ if ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) {+ float dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );+ dp += shadowBias;+ vec3 bd3D = normalize( lightToPosition );+ float depth = textureCube( shadowMap, bd3D ).r;+ #ifdef USE_REVERSED_DEPTH_BUFFER+ depth = 1.0 - depth;+ #endif+ shadow = step( dp, depth );+ }+ return mix( 1.0, shadow, shadowIntensity );+ }+ #endif+ #endif+#endif`,Lm=`#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_SUN_LIGHT_SHADOWS > 0+ varying vec4 vSunShadowWorldPosition;+ varying vec3 vSunShadowWorldNormal;+ #endif+ #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`,Dm=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SUN_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )+ #ifdef HAS_NORMAL+ vec3 shadowWorldNormal = transformNormalByInverseViewMatrix( transformedNormal, viewMatrix );+ #else+ vec3 shadowWorldNormal = vec3( 0.0 );+ #endif+ vec4 shadowWorldPosition;+#endif+#if defined( USE_SHADOWMAP )+ #if NUM_SUN_LIGHT_SHADOWS > 0+ vSunShadowWorldPosition = vec4( worldPosition.xyz, - mvPosition.z );+ vSunShadowWorldNormal = shadowWorldNormal;+ #endif+ #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`,Nm=`float getShadowMask() {+ float shadow = 1.0;+ #ifdef USE_SHADOWMAP+ #if NUM_SUN_LIGHT_SHADOWS > 0+ SunLightShadow sunLight;+ #pragma unroll_loop_start+ for ( int i = 0; i < NUM_SUN_LIGHT_SHADOWS; i ++ ) {+ sunLight = sunLightShadows[ i ];+ shadow *= receiveShadow ? getSunShadow( sunShadowMap[ i ], sunLight, UNROLLED_LOOP_INDEX ) : 1.0;+ }+ #pragma unroll_loop_end+ #endif+ #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 && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) )+ 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;+}`,Um=`#ifdef USE_SKINNING+ mat4 boneMatX = getBoneMatrix( skinIndex.x );+ mat4 boneMatY = getBoneMatrix( skinIndex.y );+ mat4 boneMatZ = getBoneMatrix( skinIndex.z );+ mat4 boneMatW = getBoneMatrix( skinIndex.w );+#endif`,Fm=`#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`,Om=`#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`,Bm=`#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`,km=`#ifdef USE_SPECULARMAP+ uniform sampler2D specularMap;+#endif`,Vm=`#if defined( TONE_MAPPING )+ gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );+#endif`,Hm=`#ifndef saturate+#define saturate( a ) clamp( a, 0.0, 1.0 )+#endif+uniform float toneMappingExposure;+vec3 LinearToneMapping( vec3 color ) {+ return saturate( toneMappingExposure * color );}-.world-pad {- display: none;+vec3 ReinhardToneMapping( vec3 color ) {+ color *= toneMappingExposure;+ return saturate( color / ( vec3( 1.0 ) + color ) );}-.world-error {- position: absolute;- inset: 25% 10%;- background: #173d36ee;- padding: 30px;- border-radius: 8px;- z-index: 20;+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 ) );}-.overview .world-crosshair {- display: none;+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;}-@media (max-width: 750px) {- .world-heading {- left: 20px;- top: 100px;- }- .world-heading h1 {- font-size: 56px;- }- .world-heading > p:last-child {- display: none;- }- .world-toolbar {- top: 90px;- right: 14px;- }- .world-toolbar button {- padding: 7px;- font-size: 10px;- }- .world-coordinates {- left: 17px;- bottom: 190px;- }- .world-time {- right: 14px;- bottom: 185px;- width: 100px;- }- .world-pad {- position: absolute;- display: grid;- grid-template-columns: repeat(3, 32px);- gap: 4px;- left: 16px;- bottom: 250px;- }- .world-pad button {- touch-action: none;- padding: 6px;- }- .world-pad button:first-child {- grid-column: 2;- }- .world-pad button:nth-child(2) {- grid-column: 1;- }- .world-pad button:last-child {- grid-column: 2;- }- .world-heading .eyebrow {- max-width: 120px;- }- .hotbar button {- width: 47px;- }- .world-bottom > p {- font-size: 9px;- max-width: 300px;- }- .world-bottom {- bottom: 16px;- }+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 );}-</style></head><body>-<header class="masthead"><div class="identity"><span class="mark" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 96 96">- <title>Voxel Worlds — stepped island</title>- <rect x="4" y="4" width="88" height="88" rx="23" fill="#183e36"/>- <path d="M20 58 48 74 76 58v10L48 84 20 68Z" fill="#619e9d"/>- <path d="m20 42 14-8 14 8-14 8Z" fill="#d8e9a6"/>- <path d="m20 42 14 8v20l-14-8Z" fill="#71936a"/>- <path d="m34 50 14-8v20l-14 8Z" fill="#aac785"/>- <path d="m48 42 14-8 14 8-14 8Z" fill="#d8e9a6"/>- <path d="m48 42 14 8v20l-14-8Z" fill="#71936a"/>- <path d="m62 50 14-8v20l-14 8Z" fill="#aac785"/>- <path d="m34 24 14-8 14 8-14 8Z" fill="#f4efce"/>- <path d="m34 24 14 8v30l-14-8Z" fill="#99b878"/>- <path d="m48 32 14-8v30l-14 8Z" fill="#d8e9a6"/>-</svg></span>TIDELANDS</div>-<form class="seed-form" id="seed-form"><label for="seed">Seed</label><input id="seed" aria-label="Seed" maxlength="128" autocomplete="off" spellcheck="false"><button type="submit">Apply</button><button id="next-seed" type="button" title="Next seed">↗ Next</button></form></header>-<main class="world-stage">- <canvas- id="world"- tabindex="0"- aria-label="Walkable voxel island. Click to look around, use WASD to walk, Space to jump. Use the buttons to place or break blocks."- ></canvas>- <div class="world-heading">- <p class="eyebrow">A place worth getting lost in</p>- <h1>A little<br />wild.</h1>- <p>Walk the shoreline. Find the cabin.<br />Leave something of your own.</p>- </div>- <div class="world-toolbar">- <button id="overview">Island overview</button- ><button id="export-world">Save world ↗</button- ><button id="import-world">Open saved world</button- ><input- id="world-file"- type="file"- accept=".json,application/json"- hidden- /><button id="home">Return home</button>- </div>- <div class="world-crosshair" aria-hidden="true">+</div>- <div class="world-coordinates">- <span id="coordinates"></span><span id="world-clock"></span>- </div>- <div class="world-bottom">- <p id="target" role="status">- Click the world to look around · WASD to walk · Space to jump- </p>- <div- class="hotbar"- id="hotbar"- role="group"- aria-label="Building materials"- ></div>- <div class="build-actions">- <button id="break">Break block</button- ><button id="place" class="primary">Place block</button>- </div>- </div>- <div class="world-pad">- <button data-key="w" aria-label="Walk forward">↑</button- ><button data-key="a" aria-label="Walk left">←</button- ><button data-key="s" aria-label="Walk backward">↓</button- ><button data-key="d" aria-label="Walk right">→</button- ><button data-key=" " aria-label="Jump">↟</button>- </div>- <div class="world-time">- <label for="daylight">Time of day</label- ><input id="daylight" type="range" min="0" max="100" value="32" /><button- id="cycle"- aria-pressed="false"- >- Day cycle- </button>- </div>- <div class="world-error" id="world-error" hidden></div>-</main>-<div class="toast" id="toast" role="status"></div>-<script id="harness-model">-'use strict';-// Shared deterministic primitives. Domain models use named streams so unrelated edits stay stable.-function hash(value) {- let h = 2166136261;- for (const c of String(value)) h = Math.imul(h ^ c.charCodeAt(0), 16777619);- return h >>> 0;+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;}-function random(seed, stream = "main") {- let a = hash(`${seed}:${stream}`);- return () => {- a = (a + 0x6d2b79f5) | 0;- let t = Math.imul(a ^ (a >>> 15), 1 | a);- t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;- return ((t ^ (t >>> 14)) >>> 0) / 4294967296;- };+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;}-const clamp = (n, lo, hi) => Math.max(lo, Math.min(hi, n));-const lerp = (a, b, t) => a + (b - a) * t;-const pick = (items, rng) => items[Math.floor(rng() * items.length)];-function normal(rng) {- return (- Math.sqrt(-2 * Math.log(Math.max(1e-9, rng()))) *- Math.cos(2 * Math.PI * rng())- );+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; }`,Gm=`#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 = transformNormalByInverseViewMatrix( normal, viewMatrix );+ vec4 transmitted = getIBLVolumeRefraction(+ n, v, material.roughness, material.diffuseContribution, material.specularColorBlended, 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`,Wm=`#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`,Xm=`#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`,Ym=`#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`,qm=`#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`,Zm=`#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`,jm=`varying vec2 vUv;+uniform mat3 uvTransform;+void main() {+ vUv = ( uvTransform * vec3( uv, 1 ) ).xy;+ gl_Position = vec4( position.xy, 1.0, 1.0 );+}`,Jm=`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 <tonemapping_fragment>+ #include <colorspace_fragment>+}`,$m=`varying vec3 vWorldDirection;+#include <common>+void main() {+ vWorldDirection = transformDirection( position, modelMatrix );+ #include <begin_vertex>+ #include <project_vertex>+ gl_Position.z = gl_Position.w;+}`,Km=`#ifdef ENVMAP_TYPE_CUBE+ uniform samplerCube envMap;+#elif defined( ENVMAP_TYPE_CUBE_UV )+ uniform sampler2D envMap;+#endif+uniform float backgroundBlurriness;+uniform float backgroundIntensity;+uniform mat3 backgroundRotation;+varying vec3 vWorldDirection;+#include <cube_uv_reflection_fragment>+void main() {+ #ifdef ENVMAP_TYPE_CUBE+ vec4 texColor = textureCube( envMap, backgroundRotation * vWorldDirection );+ #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 <tonemapping_fragment>+ #include <colorspace_fragment>+}`,Qm=`varying vec3 vWorldDirection;+#include <common>+void main() {+ vWorldDirection = transformDirection( position, modelMatrix );+ #include <begin_vertex>+ #include <project_vertex>+ gl_Position.z = gl_Position.w;+}`,tg=`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 <tonemapping_fragment>+ #include <colorspace_fragment>+}`,eg=`#include <common>+#include <batching_pars_vertex>+#include <uv_pars_vertex>+#include <displacementmap_pars_vertex>+#include <morphtarget_pars_vertex>+#include <skinning_pars_vertex>+#include <logdepthbuf_pars_vertex>+#include <clipping_planes_pars_vertex>+varying vec2 vHighPrecisionZW;+void main() {+ #include <uv_vertex>+ #include <batching_vertex>+ #include <skinbase_vertex>+ #include <morphinstance_vertex>+ #ifdef USE_DISPLACEMENTMAP+ #include <beginnormal_vertex>+ #include <morphnormal_vertex>+ #include <skinnormal_vertex>+ #endif+ #include <begin_vertex>+ #include <morphtarget_vertex>+ #include <skinning_vertex>+ #include <displacementmap_vertex>+ #include <project_vertex>+ #include <logdepthbuf_vertex>+ #include <clipping_planes_vertex>+ vHighPrecisionZW = gl_Position.zw;+}`,ng=`#if DEPTH_PACKING == 3200+ uniform float opacity;+#endif+#include <common>+#include <packing>+#include <uv_pars_fragment>+#include <map_pars_fragment>+#include <alphamap_pars_fragment>+#include <alphatest_pars_fragment>+#include <alphahash_pars_fragment>+#include <logdepthbuf_pars_fragment>+#include <clipping_planes_pars_fragment>+varying vec2 vHighPrecisionZW;+void main() {+ vec4 diffuseColor = vec4( 1.0 );+ #include <clipping_planes_fragment>+ #if DEPTH_PACKING == 3200+ diffuseColor.a = opacity;+ #endif+ #include <map_fragment>+ #include <alphamap_fragment>+ #include <alphatest_fragment>+ #include <alphahash_fragment>+ #include <logdepthbuf_fragment>+ #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+}`,ig=`#define DISTANCE+varying vec3 vWorldPosition;+#include <common>+#include <batching_pars_vertex>+#include <uv_pars_vertex>+#include <displacementmap_pars_vertex>+#include <morphtarget_pars_vertex>+#include <skinning_pars_vertex>+#include <clipping_planes_pars_vertex>+void main() {+ #include <uv_vertex>+ #include <batching_vertex>+ #include <skinbase_vertex>+ #include <morphinstance_vertex>+ #ifdef USE_DISPLACEMENTMAP+ #include <beginnormal_vertex>+ #include <morphnormal_vertex>+ #include <skinnormal_vertex>+ #endif+ #include <begin_vertex>+ #include <morphtarget_vertex>+ #include <skinning_vertex>+ #include <displacementmap_vertex>+ #include <project_vertex>+ #include <worldpos_vertex>+ #include <clipping_planes_vertex>+ vWorldPosition = worldPosition.xyz;+}`,sg=`#define DISTANCE+uniform vec3 referencePosition;+uniform float nearDistance;+uniform float farDistance;+varying vec3 vWorldPosition;+#include <common>+#include <uv_pars_fragment>+#include <map_pars_fragment>+#include <alphamap_pars_fragment>+#include <alphatest_pars_fragment>+#include <alphahash_pars_fragment>+#include <clipping_planes_pars_fragment>+void main() {+ vec4 diffuseColor = vec4( 1.0 );+ #include <clipping_planes_fragment>+ #include <map_fragment>+ #include <alphamap_fragment>+ #include <alphatest_fragment>+ #include <alphahash_fragment>+ float dist = length( vWorldPosition - referencePosition );+ dist = ( dist - nearDistance ) / ( farDistance - nearDistance );+ dist = saturate( dist );+ gl_FragColor = vec4( dist, 0.0, 0.0, 1.0 );+}`,rg=`varying vec3 vWorldDirection;+#include <common>+void main() {+ vWorldDirection = transformDirection( position, modelMatrix );+ #include <begin_vertex>+ #include <project_vertex>+}`,og=`uniform sampler2D tEquirect;+varying vec3 vWorldDirection;+#include <common>+void main() {+ vec3 direction = normalize( vWorldDirection );+ vec2 sampleUV = equirectUv( direction );+ gl_FragColor = texture2D( tEquirect, sampleUV );+ #include <tonemapping_fragment>+ #include <colorspace_fragment>+}`,ag=`uniform float scale;+attribute float lineDistance;+varying float vLineDistance;+#include <common>+#include <uv_pars_vertex>+#include <color_pars_vertex>+#include <fog_pars_vertex>+#include <morphtarget_pars_vertex>+#include <logdepthbuf_pars_vertex>+#include <clipping_planes_pars_vertex>+void main() {+ vLineDistance = scale * lineDistance;+ #include <uv_vertex>+ #include <color_vertex>+ #include <morphinstance_vertex>+ #include <morphcolor_vertex>+ #include <begin_vertex>+ #include <morphtarget_vertex>+ #include <project_vertex>+ #include <logdepthbuf_vertex>+ #include <clipping_planes_vertex>+ #include <fog_vertex>+}`,lg=`uniform vec3 diffuse;+uniform float opacity;+uniform float dashSize;+uniform float totalSize;+varying float vLineDistance;+#include <common>+#include <color_pars_fragment>+#include <uv_pars_fragment>+#include <map_pars_fragment>+#include <fog_pars_fragment>+#include <logdepthbuf_pars_fragment>+#include <clipping_planes_pars_fragment>+void main() {+ vec4 diffuseColor = vec4( diffuse, opacity );+ #include <clipping_planes_fragment>+ if ( mod( vLineDistance, totalSize ) > dashSize ) {+ discard;+ }+ vec3 outgoingLight = vec3( 0.0 );+ #include <logdepthbuf_fragment>+ #include <map_fragment>+ #include <color_fragment>+ outgoingLight = diffuseColor.rgb;+ #include <opaque_fragment>+ #include <tonemapping_fragment>+ #include <colorspace_fragment>+ #include <fog_fragment>+ #include <premultiplied_alpha_fragment>+}`,cg=`#include <common>+#include <batching_pars_vertex>+#include <uv_pars_vertex>+#include <envmap_pars_vertex>+#include <color_pars_vertex>+#include <fog_pars_vertex>+#include <morphtarget_pars_vertex>+#include <skinning_pars_vertex>+#include <logdepthbuf_pars_vertex>+#include <clipping_planes_pars_vertex>+void main() {+ #include <uv_vertex>+ #include <color_vertex>+ #include <morphinstance_vertex>+ #include <morphcolor_vertex>+ #include <batching_vertex>+ #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )+ #include <beginnormal_vertex>+ #include <morphnormal_vertex>+ #include <skinbase_vertex>+ #include <skinnormal_vertex>+ #include <defaultnormal_vertex>+ #endif+ #include <begin_vertex>+ #include <morphtarget_vertex>+ #include <skinning_vertex>+ #include <project_vertex>+ #include <logdepthbuf_vertex>+ #include <clipping_planes_vertex>+ #include <worldpos_vertex>+ #include <envmap_vertex>+ #include <fog_vertex>+}`,hg=`uniform vec3 diffuse;+uniform float opacity;+#ifndef FLAT_SHADED+ varying vec3 vNormal;+#endif+#include <common>+#include <dithering_pars_fragment>+#include <color_pars_fragment>+#include <uv_pars_fragment>+#include <map_pars_fragment>+#include <alphamap_pars_fragment>+#include <alphatest_pars_fragment>+#include <alphahash_pars_fragment>+#include <aomap_pars_fragment>+#include <lightmap_pars_fragment>+#include <envmap_common_pars_fragment>+#include <envmap_pars_fragment>+#include <fog_pars_fragment>+#include <specularmap_pars_fragment>+#include <logdepthbuf_pars_fragment>+#include <clipping_planes_pars_fragment>+void main() {+ vec4 diffuseColor = vec4( diffuse, opacity );+ #include <clipping_planes_fragment>+ #include <logdepthbuf_fragment>+ #include <map_fragment>+ #include <color_fragment>+ #include <alphamap_fragment>+ #include <alphatest_fragment>+ #include <alphahash_fragment>+ #include <specularmap_fragment>+ 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 <aomap_fragment>+ reflectedLight.indirectDiffuse *= diffuseColor.rgb;+ vec3 outgoingLight = reflectedLight.indirectDiffuse;+ #include <envmap_fragment>+ #include <opaque_fragment>+ #include <tonemapping_fragment>+ #include <colorspace_fragment>+ #include <fog_fragment>+ #include <premultiplied_alpha_fragment>+ #include <dithering_fragment>+}`,ug=`#define LAMBERT+varying vec3 vViewPosition;+#include <common>+#include <batching_pars_vertex>+#include <uv_pars_vertex>+#include <displacementmap_pars_vertex>+#include <envmap_pars_vertex>+#include <color_pars_vertex>+#include <fog_pars_vertex>+#include <normal_pars_vertex>+#include <morphtarget_pars_vertex>+#include <skinning_pars_vertex>+#include <shadowmap_pars_vertex>+#include <logdepthbuf_pars_vertex>+#include <clipping_planes_pars_vertex>+void main() {+ #include <uv_vertex>+ #include <color_vertex>+ #include <morphinstance_vertex>+ #include <morphcolor_vertex>+ #include <batching_vertex>+ #include <beginnormal_vertex>+ #include <morphnormal_vertex>+ #include <skinbase_vertex>+ #include <skinnormal_vertex>+ #include <defaultnormal_vertex>+ #include <normal_vertex>+ #include <begin_vertex>+ #include <morphtarget_vertex>+ #include <skinning_vertex>+ #include <displacementmap_vertex>+ #include <project_vertex>+ #include <logdepthbuf_vertex>+ #include <clipping_planes_vertex>+ vViewPosition = - mvPosition.xyz;+ #include <worldpos_vertex>+ #include <envmap_vertex>+ #include <shadowmap_vertex>+ #include <fog_vertex>+}`,dg=`#define LAMBERT+uniform vec3 diffuse;+uniform vec3 emissive;+uniform float opacity;+#include <common>+#include <dithering_pars_fragment>+#include <color_pars_fragment>+#include <uv_pars_fragment>+#include <map_pars_fragment>+#include <alphamap_pars_fragment>+#include <alphatest_pars_fragment>+#include <alphahash_pars_fragment>+#include <aomap_pars_fragment>+#include <lightmap_pars_fragment>+#include <emissivemap_pars_fragment>+#include <cube_uv_reflection_fragment>+#include <envmap_common_pars_fragment>+#include <envmap_pars_fragment>+#include <envmap_physical_pars_fragment>+#include <fog_pars_fragment>+#include <bsdfs>+#include <lights_pars_begin>+#include <normal_pars_fragment>+#include <lights_lambert_pars_fragment>+#include <shadowmap_pars_fragment>+#include <bumpmap_pars_fragment>+#include <normalmap_pars_fragment>+#include <specularmap_pars_fragment>+#include <logdepthbuf_pars_fragment>+#include <clipping_planes_pars_fragment>+void main() {+ vec4 diffuseColor = vec4( diffuse, opacity );+ #include <clipping_planes_fragment>+ ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );+ vec3 totalEmissiveRadiance = emissive;+ #include <logdepthbuf_fragment>+ #include <map_fragment>+ #include <color_fragment>+ #include <alphamap_fragment>+ #include <alphatest_fragment>+ #include <alphahash_fragment>+ #include <specularmap_fragment>+ #include <normal_fragment_begin>+ #include <normal_fragment_maps>+ #include <emissivemap_fragment>+ #include <lights_lambert_fragment>+ #include <lights_fragment_begin>+ #include <lights_fragment_maps>+ #include <lights_fragment_end>+ #include <aomap_fragment>+ vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;+ #include <envmap_fragment>+ #include <opaque_fragment>+ #include <tonemapping_fragment>+ #include <colorspace_fragment>+ #include <fog_fragment>+ #include <premultiplied_alpha_fragment>+ #include <dithering_fragment>+}`,fg=`#define MATCAP+varying vec3 vViewPosition;+#include <common>+#include <batching_pars_vertex>+#include <uv_pars_vertex>+#include <color_pars_vertex>+#include <displacementmap_pars_vertex>+#include <fog_pars_vertex>+#include <normal_pars_vertex>+#include <morphtarget_pars_vertex>+#include <skinning_pars_vertex>+#include <logdepthbuf_pars_vertex>+#include <clipping_planes_pars_vertex>+void main() {+ #include <uv_vertex>+ #include <color_vertex>+ #include <morphinstance_vertex>+ #include <morphcolor_vertex>+ #include <batching_vertex>+ #include <beginnormal_vertex>+ #include <morphnormal_vertex>+ #include <skinbase_vertex>+ #include <skinnormal_vertex>+ #include <defaultnormal_vertex>+ #include <normal_vertex>+ #include <begin_vertex>+ #include <morphtarget_vertex>+ #include <skinning_vertex>+ #include <displacementmap_vertex>+ #include <project_vertex>+ #include <logdepthbuf_vertex>+ #include <clipping_planes_vertex>+ #include <fog_vertex>+ vViewPosition = - mvPosition.xyz;+}`,pg=`#define MATCAP+uniform vec3 diffuse;+uniform float opacity;+uniform sampler2D matcap;+varying vec3 vViewPosition;+#include <common>+#include <dithering_pars_fragment>+#include <color_pars_fragment>+#include <uv_pars_fragment>+#include <map_pars_fragment>+#include <alphamap_pars_fragment>+#include <alphatest_pars_fragment>+#include <alphahash_pars_fragment>+#include <fog_pars_fragment>+#include <normal_pars_fragment>+#include <bumpmap_pars_fragment>+#include <normalmap_pars_fragment>+#include <logdepthbuf_pars_fragment>+#include <clipping_planes_pars_fragment>+void main() {+ vec4 diffuseColor = vec4( diffuse, opacity );+ #include <clipping_planes_fragment>+ #include <logdepthbuf_fragment>+ #include <map_fragment>+ #include <color_fragment>+ #include <alphamap_fragment>+ #include <alphatest_fragment>+ #include <alphahash_fragment>+ #include <normal_fragment_begin>+ #include <normal_fragment_maps>+ 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 <opaque_fragment>+ #include <tonemapping_fragment>+ #include <colorspace_fragment>+ #include <fog_fragment>+ #include <premultiplied_alpha_fragment>+ #include <dithering_fragment>+}`,mg=`#define NORMAL+#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )+ varying vec3 vViewPosition;+#endif+#include <common>+#include <batching_pars_vertex>+#include <uv_pars_vertex>+#include <displacementmap_pars_vertex>+#include <normal_pars_vertex>+#include <morphtarget_pars_vertex>+#include <skinning_pars_vertex>+#include <logdepthbuf_pars_vertex>+#include <clipping_planes_pars_vertex>+void main() {+ #include <uv_vertex>+ #include <batching_vertex>+ #include <beginnormal_vertex>+ #include <morphinstance_vertex>+ #include <morphnormal_vertex>+ #include <skinbase_vertex>+ #include <skinnormal_vertex>+ #include <defaultnormal_vertex>+ #include <normal_vertex>+ #include <begin_vertex>+ #include <morphtarget_vertex>+ #include <skinning_vertex>+ #include <displacementmap_vertex>+ #include <project_vertex>+ #include <logdepthbuf_vertex>+ #include <clipping_planes_vertex>+#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )+ vViewPosition = - mvPosition.xyz;+#endif+}`,gg=`#define NORMAL+uniform float opacity;+#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )+ varying vec3 vViewPosition;+#endif+#include <uv_pars_fragment>+#include <normal_pars_fragment>+#include <bumpmap_pars_fragment>+#include <normalmap_pars_fragment>+#include <logdepthbuf_pars_fragment>+#include <clipping_planes_pars_fragment>+void main() {+ vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );+ #include <clipping_planes_fragment>+ #include <logdepthbuf_fragment>+ #include <normal_fragment_begin>+ #include <normal_fragment_maps>+ gl_FragColor = vec4( normalize( normal ) * 0.5 + 0.5, diffuseColor.a );+ #ifdef OPAQUE+ gl_FragColor.a = 1.0;+ #endif+}`,_g=`#define PHONG+varying vec3 vViewPosition;+#include <common>+#include <batching_pars_vertex>+#include <uv_pars_vertex>+#include <displacementmap_pars_vertex>+#include <envmap_pars_vertex>+#include <color_pars_vertex>+#include <fog_pars_vertex>+#include <normal_pars_vertex>+#include <morphtarget_pars_vertex>+#include <skinning_pars_vertex>+#include <shadowmap_pars_vertex>+#include <logdepthbuf_pars_vertex>+#include <clipping_planes_pars_vertex>+void main() {+ #include <uv_vertex>+ #include <color_vertex>+ #include <morphcolor_vertex>+ #include <batching_vertex>+ #include <beginnormal_vertex>+ #include <morphinstance_vertex>+ #include <morphnormal_vertex>+ #include <skinbase_vertex>+ #include <skinnormal_vertex>+ #include <defaultnormal_vertex>+ #include <normal_vertex>+ #include <begin_vertex>+ #include <morphtarget_vertex>+ #include <skinning_vertex>+ #include <displacementmap_vertex>+ #include <project_vertex>+ #include <logdepthbuf_vertex>+ #include <clipping_planes_vertex>+ vViewPosition = - mvPosition.xyz;+ #include <worldpos_vertex>+ #include <envmap_vertex>+ #include <shadowmap_vertex>+ #include <fog_vertex>+}`,xg=`#define PHONG+uniform vec3 diffuse;+uniform vec3 emissive;+uniform vec3 specular;+uniform float shininess;+uniform float opacity;+#include <common>+#include <dithering_pars_fragment>+#include <color_pars_fragment>+#include <uv_pars_fragment>+#include <map_pars_fragment>+#include <alphamap_pars_fragment>+#include <alphatest_pars_fragment>+#include <alphahash_pars_fragment>+#include <aomap_pars_fragment>+#include <lightmap_pars_fragment>+#include <emissivemap_pars_fragment>+#include <cube_uv_reflection_fragment>+#include <envmap_common_pars_fragment>+#include <envmap_pars_fragment>+#include <envmap_physical_pars_fragment>+#include <fog_pars_fragment>+#include <bsdfs>+#include <lights_pars_begin>+#include <normal_pars_fragment>+#include <lights_phong_pars_fragment>+#include <shadowmap_pars_fragment>+#include <bumpmap_pars_fragment>+#include <normalmap_pars_fragment>+#include <specularmap_pars_fragment>+#include <logdepthbuf_pars_fragment>+#include <clipping_planes_pars_fragment>+void main() {+ vec4 diffuseColor = vec4( diffuse, opacity );+ #include <clipping_planes_fragment>+ ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );+ vec3 totalEmissiveRadiance = emissive;+ #include <logdepthbuf_fragment>+ #include <map_fragment>+ #include <color_fragment>+ #include <alphamap_fragment>+ #include <alphatest_fragment>+ #include <alphahash_fragment>+ #include <specularmap_fragment>+ #include <normal_fragment_begin>+ #include <normal_fragment_maps>+ #include <emissivemap_fragment>+ #include <lights_phong_fragment>+ #include <lights_fragment_begin>+ #include <lights_fragment_maps>+ #include <lights_fragment_end>+ #include <aomap_fragment>+ vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;+ #include <envmap_fragment>+ #include <opaque_fragment>+ #include <tonemapping_fragment>+ #include <colorspace_fragment>+ #include <fog_fragment>+ #include <premultiplied_alpha_fragment>+ #include <dithering_fragment>+}`,yg=`#define STANDARD+varying vec3 vViewPosition;+#ifdef USE_TRANSMISSION+ varying vec3 vWorldPosition;+#endif+#include <common>+#include <batching_pars_vertex>+#include <uv_pars_vertex>+#include <displacementmap_pars_vertex>+#include <color_pars_vertex>+#include <fog_pars_vertex>+#include <normal_pars_vertex>+#include <morphtarget_pars_vertex>+#include <skinning_pars_vertex>+#include <shadowmap_pars_vertex>+#include <logdepthbuf_pars_vertex>+#include <clipping_planes_pars_vertex>+void main() {+ #include <uv_vertex>+ #include <color_vertex>+ #include <morphinstance_vertex>+ #include <morphcolor_vertex>+ #include <batching_vertex>+ #include <beginnormal_vertex>+ #include <morphnormal_vertex>+ #include <skinbase_vertex>+ #include <skinnormal_vertex>+ #include <defaultnormal_vertex>+ #include <normal_vertex>+ #include <begin_vertex>+ #include <morphtarget_vertex>+ #include <skinning_vertex>+ #include <displacementmap_vertex>+ #include <project_vertex>+ #include <logdepthbuf_vertex>+ #include <clipping_planes_vertex>+ vViewPosition = - mvPosition.xyz;+ #include <worldpos_vertex>+ #include <shadowmap_vertex>+ #include <fog_vertex>+#ifdef USE_TRANSMISSION+ vWorldPosition = worldPosition.xyz;+#endif+}`,vg=`#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_RETROREFLECTION+ uniform float retroreflectivity;+#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 <common>+#include <dithering_pars_fragment>+#include <color_pars_fragment>+#include <uv_pars_fragment>+#include <map_pars_fragment>+#include <alphamap_pars_fragment>+#include <alphatest_pars_fragment>+#include <alphahash_pars_fragment>+#include <aomap_pars_fragment>+#include <lightmap_pars_fragment>+#include <emissivemap_pars_fragment>+#include <iridescence_fragment>+#include <cube_uv_reflection_fragment>+#include <envmap_common_pars_fragment>+#include <envmap_physical_pars_fragment>+#include <fog_pars_fragment>+#include <lights_pars_begin>+#include <normal_pars_fragment>+#include <lights_physical_pars_fragment>+#include <transmission_pars_fragment>+#include <shadowmap_pars_fragment>+#include <bumpmap_pars_fragment>+#include <normalmap_pars_fragment>+#include <clearcoat_pars_fragment>+#include <iridescence_pars_fragment>+#include <roughnessmap_pars_fragment>+#include <metalnessmap_pars_fragment>+#include <logdepthbuf_pars_fragment>+#include <clipping_planes_pars_fragment>+void main() {+ vec4 diffuseColor = vec4( diffuse, opacity );+ #include <clipping_planes_fragment>+ ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );+ vec3 totalEmissiveRadiance = emissive;+ #include <logdepthbuf_fragment>+ #include <map_fragment>+ #include <color_fragment>+ #include <alphamap_fragment>+ #include <alphatest_fragment>+ #include <alphahash_fragment>+ #include <roughnessmap_fragment>+ #include <metalnessmap_fragment>+ #include <normal_fragment_begin>+ #include <normal_fragment_maps>+ #include <clearcoat_normal_fragment_begin>+ #include <clearcoat_normal_fragment_maps>+ #include <emissivemap_fragment>+ #include <lights_physical_fragment>+ #include <lights_fragment_begin>+ #include <lights_fragment_maps>+ #include <lights_fragment_end>+ #include <aomap_fragment>+ vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;+ vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;+ #include <transmission_fragment>+ vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;+ #ifdef USE_SHEEN++ outgoingLight = outgoingLight + 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 <opaque_fragment>+ #include <tonemapping_fragment>+ #include <colorspace_fragment>+ #include <fog_fragment>+ #include <premultiplied_alpha_fragment>+ #include <dithering_fragment>+}`,Mg=`#define TOON+varying vec3 vViewPosition;+#include <common>+#include <batching_pars_vertex>+#include <uv_pars_vertex>+#include <displacementmap_pars_vertex>+#include <color_pars_vertex>+#include <fog_pars_vertex>+#include <normal_pars_vertex>+#include <morphtarget_pars_vertex>+#include <skinning_pars_vertex>+#include <shadowmap_pars_vertex>+#include <logdepthbuf_pars_vertex>+#include <clipping_planes_pars_vertex>+void main() {+ #include <uv_vertex>+ #include <color_vertex>+ #include <morphinstance_vertex>+ #include <morphcolor_vertex>+ #include <batching_vertex>+ #include <beginnormal_vertex>+ #include <morphnormal_vertex>+ #include <skinbase_vertex>+ #include <skinnormal_vertex>+ #include <defaultnormal_vertex>+ #include <normal_vertex>+ #include <begin_vertex>+ #include <morphtarget_vertex>+ #include <skinning_vertex>+ #include <displacementmap_vertex>+ #include <project_vertex>+ #include <logdepthbuf_vertex>+ #include <clipping_planes_vertex>+ vViewPosition = - mvPosition.xyz;+ #include <worldpos_vertex>+ #include <shadowmap_vertex>+ #include <fog_vertex>+}`,Sg=`#define TOON+uniform vec3 diffuse;+uniform vec3 emissive;+uniform float opacity;+#include <common>+#include <dithering_pars_fragment>+#include <color_pars_fragment>+#include <uv_pars_fragment>+#include <map_pars_fragment>+#include <alphamap_pars_fragment>+#include <alphatest_pars_fragment>+#include <alphahash_pars_fragment>+#include <aomap_pars_fragment>+#include <lightmap_pars_fragment>+#include <emissivemap_pars_fragment>+#include <gradientmap_pars_fragment>+#include <fog_pars_fragment>+#include <bsdfs>+#include <lights_pars_begin>+#include <normal_pars_fragment>+#include <lights_toon_pars_fragment>+#include <shadowmap_pars_fragment>+#include <bumpmap_pars_fragment>+#include <normalmap_pars_fragment>+#include <logdepthbuf_pars_fragment>+#include <clipping_planes_pars_fragment>+void main() {+ vec4 diffuseColor = vec4( diffuse, opacity );+ #include <clipping_planes_fragment>+ ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );+ vec3 totalEmissiveRadiance = emissive;+ #include <logdepthbuf_fragment>+ #include <map_fragment>+ #include <color_fragment>+ #include <alphamap_fragment>+ #include <alphatest_fragment>+ #include <alphahash_fragment>+ #include <normal_fragment_begin>+ #include <normal_fragment_maps>+ #include <emissivemap_fragment>+ #include <lights_toon_fragment>+ #include <lights_fragment_begin>+ #include <lights_fragment_maps>+ #include <lights_fragment_end>+ #include <aomap_fragment>+ vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;+ #include <opaque_fragment>+ #include <tonemapping_fragment>+ #include <colorspace_fragment>+ #include <fog_fragment>+ #include <premultiplied_alpha_fragment>+ #include <dithering_fragment>+}`,bg=`uniform float size;+uniform float scale;+#include <common>+#include <color_pars_vertex>+#include <fog_pars_vertex>+#include <morphtarget_pars_vertex>+#include <logdepthbuf_pars_vertex>+#include <clipping_planes_pars_vertex>+#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 <color_vertex>+ #include <morphinstance_vertex>+ #include <morphcolor_vertex>+ #include <begin_vertex>+ #include <morphtarget_vertex>+ #include <project_vertex>+ gl_PointSize = size;+ #ifdef USE_SIZEATTENUATION+ bool isPerspective = isPerspectiveMatrix( projectionMatrix );+ if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );+ #endif+ #include <logdepthbuf_vertex>+ #include <clipping_planes_vertex>+ #include <worldpos_vertex>+ #include <fog_vertex>+}`,wg=`uniform vec3 diffuse;+uniform float opacity;+#include <common>+#include <color_pars_fragment>+#include <map_particle_pars_fragment>+#include <alphatest_pars_fragment>+#include <alphahash_pars_fragment>+#include <fog_pars_fragment>+#include <logdepthbuf_pars_fragment>+#include <clipping_planes_pars_fragment>+void main() {+ vec4 diffuseColor = vec4( diffuse, opacity );+ #include <clipping_planes_fragment>+ vec3 outgoingLight = vec3( 0.0 );+ #include <logdepthbuf_fragment>+ #include <map_particle_fragment>+ #include <color_fragment>+ #include <alphatest_fragment>+ #include <alphahash_fragment>+ outgoingLight = diffuseColor.rgb;+ #include <opaque_fragment>+ #include <tonemapping_fragment>+ #include <colorspace_fragment>+ #include <fog_fragment>+ #include <premultiplied_alpha_fragment>+}`,Eg=`#include <common>+#include <batching_pars_vertex>+#include <fog_pars_vertex>+#include <morphtarget_pars_vertex>+#include <skinning_pars_vertex>+#include <logdepthbuf_pars_vertex>+#include <shadowmap_pars_vertex>+void main() {+ #include <batching_vertex>+ #include <beginnormal_vertex>+ #include <morphinstance_vertex>+ #include <morphnormal_vertex>+ #include <skinbase_vertex>+ #include <skinnormal_vertex>+ #include <defaultnormal_vertex>+ #include <begin_vertex>+ #include <morphtarget_vertex>+ #include <skinning_vertex>+ #include <project_vertex>+ #include <logdepthbuf_vertex>+ #include <worldpos_vertex>+ #include <shadowmap_vertex>+ #include <fog_vertex>+}`,Tg=`uniform vec3 color;+uniform float opacity;+#include <common>+#include <fog_pars_fragment>+#include <bsdfs>+#include <lights_pars_begin>+#include <logdepthbuf_pars_fragment>+#include <shadowmap_pars_fragment>+#include <shadowmask_pars_fragment>+void main() {+ #include <logdepthbuf_fragment>+ gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );+ #include <tonemapping_fragment>+ #include <colorspace_fragment>+ #include <fog_fragment>+ #include <premultiplied_alpha_fragment>+}`,Ag=`uniform float rotation;+uniform vec2 center;+#include <common>+#include <uv_pars_vertex>+#include <fog_pars_vertex>+#include <logdepthbuf_pars_vertex>+#include <clipping_planes_pars_vertex>+void main() {+ #include <uv_vertex>+ 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 <logdepthbuf_vertex>+ #include <clipping_planes_vertex>+ #include <fog_vertex>+}`,Cg=`uniform vec3 diffuse;+uniform float opacity;+#include <common>+#include <uv_pars_fragment>+#include <map_pars_fragment>+#include <alphamap_pars_fragment>+#include <alphatest_pars_fragment>+#include <alphahash_pars_fragment>+#include <fog_pars_fragment>+#include <logdepthbuf_pars_fragment>+#include <clipping_planes_pars_fragment>+void main() {+ vec4 diffuseColor = vec4( diffuse, opacity );+ #include <clipping_planes_fragment>+ vec3 outgoingLight = vec3( 0.0 );+ #include <logdepthbuf_fragment>+ #include <map_fragment>+ #include <alphamap_fragment>+ #include <alphatest_fragment>+ #include <alphahash_fragment>+ outgoingLight = diffuseColor.rgb;+ #include <opaque_fragment>+ #include <tonemapping_fragment>+ #include <colorspace_fragment>+ #include <fog_fragment>+}`,zt={alphahash_fragment:jf,alphahash_pars_fragment:Jf,alphamap_fragment:$f,alphamap_pars_fragment:Kf,alphatest_fragment:Qf,alphatest_pars_fragment:tp,aomap_fragment:ep,aomap_pars_fragment:np,batching_pars_vertex:ip,batching_vertex:sp,begin_vertex:rp,beginnormal_vertex:op,bsdfs:ap,iridescence_fragment:lp,bumpmap_pars_fragment:cp,clipping_planes_fragment:hp,clipping_planes_pars_fragment:up,clipping_planes_pars_vertex:dp,clipping_planes_vertex:fp,color_fragment:pp,color_pars_fragment:mp,color_pars_vertex:gp,color_vertex:_p,common:xp,cube_uv_reflection_fragment:yp,defaultnormal_vertex:vp,displacementmap_pars_vertex:Mp,displacementmap_vertex:Sp,emissivemap_fragment:bp,emissivemap_pars_fragment:wp,colorspace_fragment:Ep,colorspace_pars_fragment:Tp,envmap_fragment:Ap,envmap_common_pars_fragment:Cp,envmap_pars_fragment:Rp,envmap_pars_vertex:Pp,envmap_physical_pars_fragment:Vp,envmap_vertex:Ip,fog_vertex:Lp,fog_pars_vertex:Dp,fog_fragment:Np,fog_pars_fragment:Up,gradientmap_pars_fragment:Fp,lightmap_pars_fragment:Op,lights_lambert_fragment:Bp,lights_lambert_pars_fragment:zp,lights_pars_begin:kp,lights_toon_fragment:Hp,lights_toon_pars_fragment:Gp,lights_phong_fragment:Wp,lights_phong_pars_fragment:Xp,lights_physical_fragment:Yp,lights_physical_pars_fragment:qp,lights_fragment_begin:Zp,lights_fragment_maps:jp,lights_fragment_end:Jp,lightprobes_pars_fragment:$p,logdepthbuf_fragment:Kp,logdepthbuf_pars_fragment:Qp,logdepthbuf_pars_vertex:tm,logdepthbuf_vertex:em,map_fragment:nm,map_pars_fragment:im,map_particle_fragment:sm,map_particle_pars_fragment:rm,metalnessmap_fragment:om,metalnessmap_pars_fragment:am,morphinstance_vertex:lm,morphcolor_vertex:cm,morphnormal_vertex:hm,morphtarget_pars_vertex:um,morphtarget_vertex:dm,normal_fragment_begin:fm,normal_fragment_maps:pm,normal_pars_fragment:mm,normal_pars_vertex:gm,normal_vertex:_m,normalmap_pars_fragment:xm,clearcoat_normal_fragment_begin:ym,clearcoat_normal_fragment_maps:vm,clearcoat_pars_fragment:Mm,iridescence_pars_fragment:Sm,opaque_fragment:bm,packing:wm,premultiplied_alpha_fragment:Em,project_vertex:Tm,dithering_fragment:Am,dithering_pars_fragment:Cm,roughnessmap_fragment:Rm,roughnessmap_pars_fragment:Pm,shadowmap_pars_fragment:Im,shadowmap_pars_vertex:Lm,shadowmap_vertex:Dm,shadowmask_pars_fragment:Nm,skinbase_vertex:Um,skinning_pars_vertex:Fm,skinning_vertex:Om,skinnormal_vertex:Bm,specularmap_fragment:zm,specularmap_pars_fragment:km,tonemapping_fragment:Vm,tonemapping_pars_fragment:Hm,transmission_fragment:Gm,transmission_pars_fragment:Wm,uv_pars_fragment:Xm,uv_pars_vertex:Ym,uv_vertex:qm,worldpos_vertex:Zm,background_vert:jm,background_frag:Jm,backgroundCube_vert:$m,backgroundCube_frag:Km,cube_vert:Qm,cube_frag:tg,depth_vert:eg,depth_frag:ng,distance_vert:ig,distance_frag:sg,equirect_vert:rg,equirect_frag:og,linedashed_vert:ag,linedashed_frag:lg,meshbasic_vert:cg,meshbasic_frag:hg,meshlambert_vert:ug,meshlambert_frag:dg,meshmatcap_vert:fg,meshmatcap_frag:pg,meshnormal_vert:mg,meshnormal_frag:gg,meshphong_vert:_g,meshphong_frag:xg,meshphysical_vert:yg,meshphysical_frag:vg,meshtoon_vert:Mg,meshtoon_frag:Sg,points_vert:bg,points_frag:wg,shadow_vert:Eg,shadow_frag:Tg,sprite_vert:Ag,sprite_frag:Cg},ft={common:{diffuse:{value:new Nt(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new Ut},alphaMap:{value:null},alphaMapTransform:{value:new Ut},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new Ut}},envmap:{envMap:{value:null},envMapRotation:{value:new Ut},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new Ut}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new Ut}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new Ut},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new Ut},normalScale:{value:new Pt(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new Ut},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new Ut}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new Ut}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new Ut}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new Nt(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},sunLights:{value:[],properties:{direction:{},color:{}}},sunLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},sunShadowMatrix:{value:[]},sunShadowCascade:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null},probesSH:{value:null},probesMin:{value:new P},probesMax:{value:new P},probesResolution:{value:new P}},points:{diffuse:{value:new Nt(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new Ut},alphaTest:{value:0},uvTransform:{value:new Ut}},sprite:{diffuse:{value:new Nt(16777215)},opacity:{value:1},center:{value:new Pt(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new Ut},alphaMap:{value:null},alphaMapTransform:{value:new Ut},alphaTest:{value:0}}},Wn={basic:{uniforms:He([ft.common,ft.specularmap,ft.envmap,ft.aomap,ft.lightmap,ft.fog]),vertexShader:zt.meshbasic_vert,fragmentShader:zt.meshbasic_frag},lambert:{uniforms:He([ft.common,ft.specularmap,ft.envmap,ft.aomap,ft.lightmap,ft.emissivemap,ft.bumpmap,ft.normalmap,ft.displacementmap,ft.fog,ft.lights,{emissive:{value:new Nt(0)},envMapIntensity:{value:1}}]),vertexShader:zt.meshlambert_vert,fragmentShader:zt.meshlambert_frag},phong:{uniforms:He([ft.common,ft.specularmap,ft.envmap,ft.aomap,ft.lightmap,ft.emissivemap,ft.bumpmap,ft.normalmap,ft.displacementmap,ft.fog,ft.lights,{emissive:{value:new Nt(0)},specular:{value:new Nt(1118481)},shininess:{value:30},envMapIntensity:{value:1}}]),vertexShader:zt.meshphong_vert,fragmentShader:zt.meshphong_frag},standard:{uniforms:He([ft.common,ft.envmap,ft.aomap,ft.lightmap,ft.emissivemap,ft.bumpmap,ft.normalmap,ft.displacementmap,ft.roughnessmap,ft.metalnessmap,ft.fog,ft.lights,{emissive:{value:new Nt(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:zt.meshphysical_vert,fragmentShader:zt.meshphysical_frag},toon:{uniforms:He([ft.common,ft.aomap,ft.lightmap,ft.emissivemap,ft.bumpmap,ft.normalmap,ft.displacementmap,ft.gradientmap,ft.fog,ft.lights,{emissive:{value:new Nt(0)}}]),vertexShader:zt.meshtoon_vert,fragmentShader:zt.meshtoon_frag},matcap:{uniforms:He([ft.common,ft.bumpmap,ft.normalmap,ft.displacementmap,ft.fog,{matcap:{value:null}}]),vertexShader:zt.meshmatcap_vert,fragmentShader:zt.meshmatcap_frag},points:{uniforms:He([ft.points,ft.fog]),vertexShader:zt.points_vert,fragmentShader:zt.points_frag},dashed:{uniforms:He([ft.common,ft.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:zt.linedashed_vert,fragmentShader:zt.linedashed_frag},depth:{uniforms:He([ft.common,ft.displacementmap]),vertexShader:zt.depth_vert,fragmentShader:zt.depth_frag},normal:{uniforms:He([ft.common,ft.bumpmap,ft.normalmap,ft.displacementmap,{opacity:{value:1}}]),vertexShader:zt.meshnormal_vert,fragmentShader:zt.meshnormal_frag},sprite:{uniforms:He([ft.sprite,ft.fog]),vertexShader:zt.sprite_vert,fragmentShader:zt.sprite_frag},background:{uniforms:{uvTransform:{value:new Ut},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:zt.background_vert,fragmentShader:zt.background_frag},backgroundCube:{uniforms:{envMap:{value:null},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new Ut}},vertexShader:zt.backgroundCube_vert,fragmentShader:zt.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:zt.cube_vert,fragmentShader:zt.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:zt.equirect_vert,fragmentShader:zt.equirect_frag},distance:{uniforms:He([ft.common,ft.displacementmap,{referencePosition:{value:new P},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:zt.distance_vert,fragmentShader:zt.distance_frag},shadow:{uniforms:He([ft.lights,ft.fog,{color:{value:new Nt(0)},opacity:{value:1}}]),vertexShader:zt.shadow_vert,fragmentShader:zt.shadow_frag}};Wn.physical={uniforms:He([Wn.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new Ut},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new Ut},clearcoatNormalScale:{value:new Pt(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new Ut},dispersion:{value:0},retroreflectivity:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new Ut},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new Ut},sheen:{value:0},sheenColor:{value:new Nt(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new Ut},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new Ut},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new Ut},transmissionSamplerSize:{value:new Pt},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new Ut},attenuationDistance:{value:0},attenuationColor:{value:new Nt(0)},specularColor:{value:new Nt(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new Ut},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new Ut},anisotropyVector:{value:new Pt},anisotropyMap:{value:null},anisotropyMapTransform:{value:new Ut}}]),vertexShader:zt.meshphysical_vert,fragmentShader:zt.meshphysical_frag};var $a={r:0,b:0,g:0},Rg=new se,sd=new Ut;sd.set(-1,0,0,0,1,0,0,0,1);function Pg(i,t,e,n,s,r){let o=new Nt(0),a=s===!0?0:1,c,l,u=null,f=0,h=null;function p(S){let T=S.isScene===!0?S.background:null;if(T&&T.isTexture){let y=S.backgroundBlurriness>0;T=t.get(T,y)}return T}function g(S){let T=!1,y=p(S);y===null?m(o,a):y&&y.isColor&&(m(y,1),T=!0);let b=i.xr.getEnvironmentBlendMode();b==="additive"?e.buffers.color.setClear(0,0,0,1,r):b==="alpha-blend"&&e.buffers.color.setClear(0,0,0,0,r),(i.autoClear||T)&&(e.buffers.depth.setTest(!0),e.buffers.depth.setMask(!0),e.buffers.color.setMask(!0),i.clear(i.autoClearColor,i.autoClearDepth,i.autoClearStencil))}function v(S,T){let y=p(T);y&&(y.isCubeTexture||y.mapping===Ir)?(l===void 0&&(l=new ut(new ge(1,1,1),new un({name:"BackgroundCubeMaterial",uniforms:Zi(Wn.backgroundCube.uniforms),vertexShader:Wn.backgroundCube.vertexShader,fragmentShader:Wn.backgroundCube.fragmentShader,side:Ze,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute("normal"),l.geometry.deleteAttribute("uv"),l.onBeforeRender=function(b,w,C){this.matrixWorld.copyPosition(C.matrixWorld)},Object.defineProperty(l.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),n.update(l)),l.material.uniforms.envMap.value=y,l.material.uniforms.backgroundBlurriness.value=T.backgroundBlurriness,l.material.uniforms.backgroundIntensity.value=T.backgroundIntensity,l.material.uniforms.backgroundRotation.value.setFromMatrix4(Rg.makeRotationFromEuler(T.backgroundRotation)).transpose(),y.isCubeTexture&&y.isRenderTargetTexture===!1&&l.material.uniforms.backgroundRotation.value.premultiply(sd),l.material.toneMapped=Xt.getTransfer(y.colorSpace)!==Qt,(u!==y||f!==y.version||h!==i.toneMapping)&&(l.material.needsUpdate=!0,u=y,f=y.version,h=i.toneMapping),l.layers.enableAll(),S.unshift(l,l.geometry,l.material,0,0,null)):y&&y.isTexture&&(c===void 0&&(c=new ut(new ni(2,2),new un({name:"BackgroundMaterial",uniforms:Zi(Wn.background.uniforms),vertexShader:Wn.background.vertexShader,fragmentShader:Wn.background.fragmentShader,side:Ti,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),c.geometry.deleteAttribute("normal"),Object.defineProperty(c.material,"map",{get:function(){return this.uniforms.t2D.value}}),n.update(c)),c.material.uniforms.t2D.value=y,c.material.uniforms.backgroundIntensity.value=T.backgroundIntensity,c.material.toneMapped=Xt.getTransfer(y.colorSpace)!==Qt,y.matrixAutoUpdate===!0&&y.updateMatrix(),c.material.uniforms.uvTransform.value.copy(y.matrix),(u!==y||f!==y.version||h!==i.toneMapping)&&(c.material.needsUpdate=!0,u=y,f=y.version,h=i.toneMapping),c.layers.enableAll(),S.unshift(c,c.geometry,c.material,0,0,null))}function m(S,T){S.getRGB($a,Sc(i)),e.buffers.color.setClear($a.r,$a.g,$a.b,T,r)}function d(){l!==void 0&&(l.geometry.dispose(),l.material.dispose(),l=void 0),c!==void 0&&(c.geometry.dispose(),c.material.dispose(),c=void 0)}return{getClearColor:function(){return o},setClearColor:function(S,T=1){o.set(S),a=T,m(o,a)},getClearAlpha:function(){return a},setClearAlpha:function(S){a=S,m(o,a)},render:g,addToRenderList:v,dispose:d}}function Ig(i,t){let e=i.getParameter(i.MAX_VERTEX_ATTRIBS),n={},s=h(null),r=s,o=!1;function a(L,F,z,I,O){let G=!1,X=f(L,I,z,F);r!==X&&(r=X,l(r.object)),G=p(L,I,z,O),G&&g(L,I,z,O),O!==null&&t.update(O,i.ELEMENT_ARRAY_BUFFER),(G||o)&&(o=!1,y(L,F,z,I),O!==null&&i.bindBuffer(i.ELEMENT_ARRAY_BUFFER,t.get(O).buffer))}function c(){return i.createVertexArray()}function l(L){return i.bindVertexArray(L)}function u(L){return i.deleteVertexArray(L)}function f(L,F,z,I){let O=I.wireframe===!0,G=n[F.id];G===void 0&&(G={},n[F.id]=G);let X=L.isInstancedMesh===!0?L.id:0,et=G[X];et===void 0&&(et={},G[X]=et);let Y=et[z.id];Y===void 0&&(Y={},et[z.id]=Y);let K=Y[O];return K===void 0&&(K=h(c()),Y[O]=K),K}function h(L){let F=[],z=[],I=[];for(let O=0;O<e;O++)F[O]=0,z[O]=0,I[O]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:F,enabledAttributes:z,attributeDivisors:I,object:L,attributes:{},index:null}}function p(L,F,z,I){let O=r.attributes,G=F.attributes,X=0,et=z.getAttributes();for(let Y in et)if(et[Y].location>=0){let nt=O[Y],Et=G[Y];if(Et===void 0&&(Y==="instanceMatrix"&&L.instanceMatrix&&(Et=L.instanceMatrix),Y==="instanceColor"&&L.instanceColor&&(Et=L.instanceColor)),nt===void 0||nt.attribute!==Et||Et&&nt.data!==Et.data)return!0;X++}return r.attributesNum!==X||r.index!==I}function g(L,F,z,I){let O={},G=F.attributes,X=0,et=z.getAttributes();for(let Y in et)if(et[Y].location>=0){let nt=G[Y];nt===void 0&&(Y==="instanceMatrix"&&L.instanceMatrix&&(nt=L.instanceMatrix),Y==="instanceColor"&&L.instanceColor&&(nt=L.instanceColor));let Et={};Et.attribute=nt,nt&&nt.data&&(Et.data=nt.data),O[Y]=Et,X++}r.attributes=O,r.attributesNum=X,r.index=I}function v(){let L=r.newAttributes;for(let F=0,z=L.length;F<z;F++)L[F]=0}function m(L){d(L,0)}function d(L,F){let z=r.newAttributes,I=r.enabledAttributes,O=r.attributeDivisors;z[L]=1,I[L]===0&&(i.enableVertexAttribArray(L),I[L]=1),O[L]!==F&&(i.vertexAttribDivisor(L,F),O[L]=F)}function S(){let L=r.newAttributes,F=r.enabledAttributes;for(let z=0,I=F.length;z<I;z++)F[z]!==L[z]&&(i.disableVertexAttribArray(z),F[z]=0)}function T(L,F,z,I,O,G,X){X===!0?i.vertexAttribIPointer(L,F,z,O,G):i.vertexAttribPointer(L,F,z,I,O,G)}function y(L,F,z,I){v();let O=I.attributes,G=z.getAttributes(),X=F.defaultAttributeValues;for(let et in G){let Y=G[et];if(Y.location>=0){let K=O[et];if(K===void 0&&(et==="instanceMatrix"&&L.instanceMatrix&&(K=L.instanceMatrix),et==="instanceColor"&&L.instanceColor&&(K=L.instanceColor)),K!==void 0){let nt=K.normalized,Et=K.itemSize,Tt=t.get(K);if(Tt===void 0)continue;let te=Tt.buffer,qt=Tt.type,Jt=Tt.bytesPerElement,Z=qt===i.INT||qt===i.UNSIGNED_INT||K.gpuType===da;if(K.isInterleavedBufferAttribute){let Q=K.data,vt=Q.stride,Ft=K.offset;if(Q.isInstancedInterleavedBuffer){for(let xt=0;xt<Y.locationSize;xt++)d(Y.location+xt,Q.meshPerAttribute);L.isInstancedMesh!==!0&&I._maxInstanceCount===void 0&&(I._maxInstanceCount=Q.meshPerAttribute*Q.count)}else for(let xt=0;xt<Y.locationSize;xt++)m(Y.location+xt);i.bindBuffer(i.ARRAY_BUFFER,te);for(let xt=0;xt<Y.locationSize;xt++)T(Y.location+xt,Et/Y.locationSize,qt,nt,vt*Jt,(Ft+Et/Y.locationSize*xt)*Jt,Z)}else{if(K.isInstancedBufferAttribute){for(let Q=0;Q<Y.locationSize;Q++)d(Y.location+Q,K.meshPerAttribute);L.isInstancedMesh!==!0&&I._maxInstanceCount===void 0&&(I._maxInstanceCount=K.meshPerAttribute*K.count)}else for(let Q=0;Q<Y.locationSize;Q++)m(Y.location+Q);i.bindBuffer(i.ARRAY_BUFFER,te);for(let Q=0;Q<Y.locationSize;Q++)T(Y.location+Q,Et/Y.locationSize,qt,nt,Et*Jt,Et/Y.locationSize*Q*Jt,Z)}}else if(X!==void 0){let nt=X[et];if(nt!==void 0)switch(nt.length){case 2:i.vertexAttrib2fv(Y.location,nt);break;case 3:i.vertexAttrib3fv(Y.location,nt);break;case 4:i.vertexAttrib4fv(Y.location,nt);break;default:i.vertexAttrib1fv(Y.location,nt)}}}}S()}function b(){E();for(let L in n){let F=n[L];for(let z in F){let I=F[z];for(let O in I){let G=I[O];for(let X in G)u(G[X].object),delete G[X];delete I[O]}}delete n[L]}}function w(L){if(n[L.id]===void 0)return;let F=n[L.id];for(let z in F){let I=F[z];for(let O in I){let G=I[O];for(let X in G)u(G[X].object),delete G[X];delete I[O]}}delete n[L.id]}function C(L){for(let F in n){let z=n[F];for(let I in z){let O=z[I];if(O[L.id]===void 0)continue;let G=O[L.id];for(let X in G)u(G[X].object),delete G[X];delete O[L.id]}}}function _(L){for(let F in n){let z=n[F],I=L.isInstancedMesh===!0?L.id:0,O=z[I];if(O!==void 0){for(let G in O){let X=O[G];for(let et in X)u(X[et].object),delete X[et];delete O[G]}delete z[I],Object.keys(z).length===0&&delete n[F]}}}function E(){R(),o=!0,r!==s&&(r=s,l(r.object))}function R(){s.geometry=null,s.program=null,s.wireframe=!1}return{setup:a,reset:E,resetDefaultState:R,dispose:b,releaseStatesOfGeometry:w,releaseStatesOfObject:_,releaseStatesOfProgram:C,initAttributes:v,enableAttribute:m,disableUnusedAttributes:S}}function Lg(i,t,e){let n;function s(c){n=c}function r(c,l){i.drawArrays(n,c,l),e.update(l,n,1)}function o(c,l,u){u!==0&&(i.drawArraysInstanced(n,c,l,u),e.update(l,n,u))}function a(c,l,u){if(u===0)return;t.get("WEBGL_multi_draw").multiDrawArraysWEBGL(n,c,0,l,0,u);let h=0;for(let p=0;p<u;p++)h+=l[p];e.update(h,n,1)}this.setMode=s,this.render=r,this.renderInstances=o,this.renderMultiDraw=a}function Dg(i,t,e,n){let s;function r(){if(s!==void 0)return s;if(t.has("EXT_texture_filter_anisotropic")===!0){let C=t.get("EXT_texture_filter_anisotropic");s=i.getParameter(C.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else s=0;return s}function o(C){return!(C!==xn&&n.convert(C)!==i.getParameter(i.IMPLEMENTATION_COLOR_READ_FORMAT))}function a(C){let _=C===Ln&&(t.has("EXT_color_buffer_half_float")||t.has("EXT_color_buffer_float"));return!(C!==Qe&&C!==In&&!_&&n.convert(C)!==i.getParameter(i.IMPLEMENTATION_COLOR_READ_TYPE))}function c(C){if(C==="highp"){if(i.getShaderPrecisionFormat(i.VERTEX_SHADER,i.HIGH_FLOAT).precision>0&&i.getShaderPrecisionFormat(i.FRAGMENT_SHADER,i.HIGH_FLOAT).precision>0)return"highp";C="mediump"}return C==="mediump"&&i.getShaderPrecisionFormat(i.VERTEX_SHADER,i.MEDIUM_FLOAT).precision>0&&i.getShaderPrecisionFormat(i.FRAGMENT_SHADER,i.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let l=e.precision!==void 0?e.precision:"highp",u=c(l);u!==l&&(It("WebGLRenderer:",l,"not supported, using",u,"instead."),l=u);let f=e.logarithmicDepthBuffer===!0,h=e.reversedDepthBuffer===!0&&t.has("EXT_clip_control");e.reversedDepthBuffer===!0&&h===!1&&It("WebGLRenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer.");let p=i.getParameter(i.MAX_TEXTURE_IMAGE_UNITS),g=i.getParameter(i.MAX_VERTEX_TEXTURE_IMAGE_UNITS),v=i.getParameter(i.MAX_TEXTURE_SIZE),m=i.getParameter(i.MAX_CUBE_MAP_TEXTURE_SIZE),d=i.getParameter(i.MAX_VERTEX_ATTRIBS),S=i.getParameter(i.MAX_VERTEX_UNIFORM_VECTORS),T=i.getParameter(i.MAX_VARYING_VECTORS),y=i.getParameter(i.MAX_FRAGMENT_UNIFORM_VECTORS),b=i.getParameter(i.MAX_SAMPLES),w=i.getParameter(i.SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:r,getMaxPrecision:c,textureFormatReadable:o,textureTypeReadable:a,precision:l,logarithmicDepthBuffer:f,reversedDepthBuffer:h,maxTextures:p,maxVertexTextures:g,maxTextureSize:v,maxCubemapSize:m,maxAttributes:d,maxVertexUniforms:S,maxVaryings:T,maxFragmentUniforms:y,maxSamples:b,samples:w}}function Ng(i){let t=this,e=null,n=0,s=!1,r=!1,o=new ln,a=new Ut,c={value:null,needsUpdate:!1};this.uniform=c,this.numPlanes=0,this.numIntersection=0,this.init=function(f,h){let p=f.length!==0||h||n!==0||s;return s=h,n=f.length,p},this.beginShadows=function(){r=!0,u(null)},this.endShadows=function(){r=!1},this.setGlobalState=function(f,h){e=u(f,h,0)},this.setState=function(f,h,p){let g=f.clippingPlanes,v=f.clipIntersection,m=f.clipShadows,d=i.get(f);if(!s||g===null||g.length===0||r&&!m)r?u(null):l();else{let S=r?0:n,T=S*4,y=d.clippingState||null;c.value=y,y=u(g,h,T,p);for(let b=0;b!==T;++b)y[b]=e[b];d.clippingState=y,this.numIntersection=v?this.numPlanes:0,this.numPlanes+=S}};function l(){c.value!==e&&(c.value=e,c.needsUpdate=n>0),t.numPlanes=n,t.numIntersection=0}function u(f,h,p,g){let v=f!==null?f.length:0,m=null;if(v!==0){if(m=c.value,g!==!0||m===null){let d=p+v*4,S=h.matrixWorldInverse;a.getNormalMatrix(S),(m===null||m.length<d)&&(m=new Float32Array(d));for(let T=0,y=p;T!==v;++T,y+=4)o.copy(f[T]).applyMatrix4(S,a),o.normal.toArray(m,y),m[y+3]=o.constant}c.value=m,c.needsUpdate=!0}return t.numPlanes=v,t.numIntersection=0,m}}var Xs=4,Ug=6,Fg=20,Og=256,zr=new Os,Fu=new Nt,Tc=null,Ac=0,Cc=0,Rc=!1,Bg=new P,ji=new P,Qa=class{constructor(t){this._renderer=t,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._lodMeshes=[],this._backgroundBox=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._blurMaterial=null,this._ggxMaterial=null}fromScene(t,e=0,n=.1,s=100,r={}){let{size:o=256,position:a=Bg}=r;Tc=this._renderer.getRenderTarget(),Ac=this._renderer.getActiveCubeFace(),Cc=this._renderer.getActiveMipmapLevel(),Rc=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(o);let c=this._allocateTargets();return c.depthBuffer=!0,this._sceneToCubeUV(t,n,s,c,a),e>0&&this._blur(c,0,0,e),this._applyPMREM(c),this._cleanup(c),c}fromEquirectangular(t,e=null){return this._fromTexture(t,e)}fromCubemap(t,e=null){return this._fromTexture(t,e)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=zu(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=Bu(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose(),this._backgroundBox!==null&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.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._ggxMaterial!==null&&this._ggxMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let t=0;t<this._lodMeshes.length;t++)this._lodMeshes[t].geometry.dispose()}_cleanup(t){this._renderer.setRenderTarget(Tc,Ac,Cc),this._renderer.xr.enabled=Rc,t.scissorTest=!1,Ws(t,0,0,t.width,t.height)}_fromTexture(t,e){t.mapping===Ai||t.mapping===qi?this._setSize(t.image.length===0?16:t.image[0].width||t.image[0].image.width):this._setSize(t.image.width/4),Tc=this._renderer.getRenderTarget(),Ac=this._renderer.getActiveCubeFace(),Cc=this._renderer.getActiveMipmapLevel(),Rc=this._renderer.xr.enabled,this._renderer.xr.enabled=!1;let n=e||this._allocateTargets();return this._textureToCubeUV(t,n),this._applyPMREM(n),this._cleanup(n),n}_allocateTargets(){let t=3*Math.max(this._cubeSize,112),e=4*this._cubeSize,n={magFilter:Fe,minFilter:Fe,generateMipmaps:!1,type:Ln,format:xn,colorSpace:cr,depthBuffer:!1},s=Ou(t,e,n);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==t||this._pingPongRenderTarget.height!==e){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=Ou(t,e,n);let{_lodMax:r}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods}=zg(r)),this._blurMaterial=Vg(r,t,e),this._ggxMaterial=kg(r,t,e)}return s}_compileMaterial(t){let e=new ut(new ve,t);this._renderer.compile(e,zr)}_sceneToCubeUV(t,e,n,s,r){let c=new Ue(90,1,e,n),l=[1,-1,1,1,1,1],u=[1,1,1,-1,-1,-1],f=this._renderer,h=f.autoClear,p=f.toneMapping;f.getClearColor(Fu),f.toneMapping=Rn,f.autoClear=!1,f.state.buffers.depth.getReversed()&&(f.setRenderTarget(s),f.clearDepth(),f.setRenderTarget(null)),this._backgroundBox===null&&(this._backgroundBox=new ut(new ge,new Vn({name:"PMREM.Background",side:Ze,depthWrite:!1,depthTest:!1})));let v=this._backgroundBox,m=v.material,d=!1,S=t.background;S?S.isColor&&(m.color.copy(S),t.background=null,d=!0):(m.color.copy(Fu),d=!0);for(let T=0;T<6;T++){let y=T%3;y===0?(c.up.set(0,l[T],0),c.position.set(r.x,r.y,r.z),c.lookAt(r.x+u[T],r.y,r.z)):y===1?(c.up.set(0,0,l[T]),c.position.set(r.x,r.y,r.z),c.lookAt(r.x,r.y+u[T],r.z)):(c.up.set(0,l[T],0),c.position.set(r.x,r.y,r.z),c.lookAt(r.x,r.y,r.z+u[T]));let b=this._cubeSize;Ws(s,y*b,T>2?b:0,b,b),f.setRenderTarget(s),d&&f.render(v,c),f.render(t,c)}f.toneMapping=p,f.autoClear=h,t.background=S}_textureToCubeUV(t,e){let n=this._renderer,s=t.mapping===Ai||t.mapping===qi;s?(this._cubemapMaterial===null&&(this._cubemapMaterial=zu()),this._cubemapMaterial.uniforms.flipEnvMap.value=t.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=Bu());let r=s?this._cubemapMaterial:this._equirectMaterial,o=this._lodMeshes[0];o.material=r;let a=r.uniforms;a.envMap.value=t;let c=this._cubeSize;Ws(e,0,0,3*c,2*c),n.setRenderTarget(e),n.render(o,zr)}_applyPMREM(t){let e=this._renderer,n=e.autoClear;e.autoClear=!1;let s=this._lodMeshes.length;for(let r=1;r<s;r++)this._applyGGXFilter(t,r-1,r);e.autoClear=n}_applyGGXFilter(t,e,n){let s=this._renderer,r=this._pingPongRenderTarget,o=this._ggxMaterial,a=this._lodMeshes[n];a.material=o;let c=o.uniforms,l=n/(this._lodMeshes.length-1),u=e/(this._lodMeshes.length-1),f=Math.sqrt(l*l-u*u),h=l*1.25,p=f*h,{_lodMax:g}=this,v=this._sizeLods[n],m=3*v*(n>g-Xs?n-g+Xs:0),d=4*(this._cubeSize-v);c.envMap.value=t.texture,c.roughness.value=p,c.mipInt.value=g-e,Ws(r,m,d,3*v,2*v),s.setRenderTarget(r),s.render(a,zr),c.envMap.value=r.texture,c.roughness.value=0,c.mipInt.value=g-n,Ws(t,m,d,3*v,2*v),s.setRenderTarget(t),s.render(a,zr)}_blur(t,e,n,s){let r=this._pingPongRenderTarget,o=Math.min(s,Math.PI)/Math.SQRT2;this._blurPass(t,r,e,n,o),this._blurPass(r,t,n,n,o)}_blurPass(t,e,n,s,r){let o=this._renderer,a=this._blurMaterial,c=this._lodMeshes[s];c.material=a;let l=a.uniforms;l.envMap.value=t.texture,l.sigma.value=r,l.mipInt.value=this._lodMax-n;let u=this._sizeLods[s],f=3*u*(s>this._lodMax-Xs?s-this._lodMax+Xs:0),h=4*(this._cubeSize-u);Ws(e,f,h,3*u,2*u),o.setRenderTarget(e),o.render(c,zr)}};function zg(i){let t=[],e=[],n=i,s=i-Xs+1+Ug;for(let r=0;r<s;r++){let o=Math.pow(2,n);t.push(o);let a=1/(o-2),c=-a,l=1+a,u=[c,c,l,c,l,l,c,c,l,l,c,l],f=6,h=6,p=3,g=new Float32Array(p*h*f),v=new Float32Array(p*h*f);for(let d=0;d<f;d++){let S=d%3*2/3-1,T=d>2?0:-1,y=[S,T,0,S+2/3,T,0,S+2/3,T+1,0,S,T,0,S+2/3,T+1,0,S,T+1,0];g.set(y,p*h*d);for(let b=0;b<h;b++){let w=u[b*2]*2-1,C=u[b*2+1]*2-1;d===0?ji.set(1,C,w):d===1?ji.set(-w,1,-C):d===2?ji.set(-w,C,1):d===3?ji.set(-1,C,-w):d===4?ji.set(-w,-1,C):ji.set(w,C,-1),ji.toArray(v,(d*h+b)*p)}}let m=new ve;m.setAttribute("position",new cn(g,p)),m.setAttribute("outputDirection",new cn(v,p)),e.push(new ut(m,null)),n>Xs&&n--}return{lodMeshes:e,sizeLods:t}}function Ou(i,t,e){let n=new Ke(i,t,e);return n.texture.mapping=Ir,n.texture.name="PMREM.cubeUv",n.scissorTest=!0,n}function Ws(i,t,e,n,s){i.viewport.set(t,e,n,s),i.scissor.set(t,e,n,s)}function kg(i,t,e){return new un({name:"PMREMGGXConvolution",defines:{GGX_SAMPLES:Og,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/e,CUBEUV_MAX_MIP:`${i}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:nl(),fragmentShader:`-const blockTypes = [- null,- { name: "Grass", color: [0.4, 0.58, 0.31] },- { name: "Earth", color: [0.48, 0.34, 0.23] },- { name: "Stone", color: [0.51, 0.55, 0.53] },- { name: "Sand", color: [0.81, 0.74, 0.54] },- { name: "Timber", color: [0.43, 0.29, 0.17] },- { name: "Canopy", color: [0.25, 0.47, 0.27] },- { name: "Water", color: [0.24, 0.52, 0.59] },- { name: "Cedar", color: [0.68, 0.46, 0.28] },- { name: "Lantern", color: [1, 0.74, 0.32] },-];-function blockAt(world, x, y, z) {- if (x < 0 || y < 0 || z < 0 || x >= world.w || y >= world.h || z >= world.d)- return 0;- return world.blocks[(y * world.d + z) * world.w + x];-}-function putBlock(world, x, y, z, id) {- if (x < 0 || y < 0 || z < 0 || x >= world.w || y >= world.h || z >= world.d)- return false;- world.blocks[(y * world.d + z) * world.w + x] = id;- return true;-}-function solidBlock(id) {- return id !== 0 && id !== 7;-}-function groundAt(world, x, z) {- for (let y = world.h - 1; y >= 0; y--)- if (solidBlock(blockAt(world, Math.floor(x), y, Math.floor(z))))- return y + 1;- return 0;-}-function voxelWorld(seed) {- const world = {- seed: String(seed),- w: 48,- h: 28,- d: 48,- blocks: new Uint8Array(48 * 28 * 48),- },- r = random(seed, "terrain"),- phase = r() * 6.28,- phase2 = r() * 6.28;- for (let z = 0; z < world.d; z++)- for (let x = 0; x < world.w; x++) {- const radius = Math.hypot((x - 24) / 25, (z - 24) / 26);- let height = clamp(- Math.floor(- 5 +- (1 - radius) * 9 +- Math.sin(x * 0.23 + phase) * 1.6 +- Math.cos(z * 0.24 + phase2) * 1.6,- ),- 2,- 15,- );- if (z > 16 && Math.abs(x - (22 + Math.sin(z * 0.2) * 3)) < 1.6)- height = Math.min(height, 5);- for (let y = 0; y < Math.max(height, 6); y++)- putBlock(- world,- x,- y,- z,- y >= height- ? 7- : y === height - 1- ? height < 8- ? 4- : 1- : y > height - 4- ? 2- : 3,- );- }- const pad = (cx, cz, radius, height) => {- for (let z = cz - radius; z <= cz + radius; z++)- for (let x = cx - radius; x <= cx + radius; x++)- for (let y = 0; y < world.h; y++)- putBlock(world, x, y, z, y < height ? (y === height - 1 ? 1 : 2) : 0);- };- const spawnHeight = Math.max(8, groundAt(world, 31, 35));- pad(31, 35, 3, spawnHeight);- const hutHeight = Math.max(8, groundAt(world, 31, 25));- pad(31, 25, 4, hutHeight);- for (let x = 28; x <= 34; x++)- for (let z = 22; z <= 27; z++) {- putBlock(world, x, hutHeight, z, 8);- for (let y = 1; y <= 3; y++)- if (- (x === 28 || x === 34 || z === 22 || z === 27) &&- !(z === 27 && x === 31 && y <= 2) &&- !((x === 28 || x === 34) && z === 24 && y === 2)- )- putBlock(world, x, hutHeight + y, z, 5);- putBlock(world, x, hutHeight + 4, z, 8);- if (x > 28 && x < 34) putBlock(world, x, hutHeight + 5, z, 8);- }- putBlock(world, 30, hutHeight + 3, 26, 9);- const towerHeight = groundAt(world, 14, 16);- for (let y = towerHeight; y < towerHeight + 7; y++)- for (let x = 13; x <= 15; x++)- for (let z = 15; z <= 17; z++)- putBlock(world, x, y, z, y === towerHeight + 6 ? 9 : 4);- // A graded three-block-wide trail connects the cabin floor to the shore.- for (let z = 28; z <= 37; z++)- for (let x = 30; x <= 32; x++) {- const height = Math.round(- hutHeight + 1 + ((spawnHeight - hutHeight - 1) * (z - 28)) / 9,- );- for (let y = 0; y < world.h; y++)- putBlock(world, x, y, z, y < height ? (y === height - 1 ? 4 : 2) : 0);- }- const trees = random(seed, "trees");- for (let i = 0; i < 65; i++) {- const x = 3 + Math.floor(trees() * 42),- z = 3 + Math.floor(trees() * 42),- y = groundAt(world, x, z);- if (- y < 8 ||- y > 15 ||- blockAt(world, x, y - 1, z) !== 1 ||- (x > 26 && x < 37 && z > 19)- )- continue;- for (let j = 0; j < 4; j++) putBlock(world, x, y + j, z, 5);- for (let dy = 2; dy <= 5; dy++)- for (let dx = -2; dx <= 2; dx++)- for (let dz = -2; dz <= 2; dz++)- if (- Math.abs(dx) + Math.abs(dz) + (dy === 5 ? 1 : 0) < 4 &&- blockAt(world, x + dx, y + dy, z + dz) === 0- )- putBlock(world, x + dx, y + dy, z + dz, 6);- }- world.spawn = {- x: 31.5,- y: groundAt(world, 31, 29) + 0.03,- z: 29.5,- yaw: -0.65,- pitch: -0.18,- };- return world;-}-function raycastWorld(world, origin, direction, max = 7) {- let previous;- for (let d = 0; d <= max; d += 0.035) {- const p = {- x: Math.floor(origin.x + direction.x * d),- y: Math.floor(origin.y + direction.y * d),- z: Math.floor(origin.z + direction.z * d),- };- const id = blockAt(world, p.x, p.y, p.z);- if (solidBlock(id)) return { ...p, id, previous, distance: d };- previous = p;- }- return null;-}-function playerFits(world, x, y, z) {- for (const dx of [-0.24, 0.24])- for (const dz of [-0.24, 0.24])- for (const dy of [0.001, 0.85, 1.65])- if (- solidBlock(- blockAt(- world,- Math.floor(x + dx),- Math.floor(y + dy),- Math.floor(z + dz),- ),- )- )- return false;- return true;-}-function movePlayer(world, player, input, dt = 1 / 60) {- const p = { ...player };- const speed = input.sprint ? 6 : 3.8;- let dx =- Math.sin(p.yaw) * (input.forward || 0) +- Math.cos(p.yaw) * (input.right || 0),- dz =- Math.cos(p.yaw) * (input.forward || 0) -- Math.sin(p.yaw) * (input.right || 0);- const length = Math.max(1, Math.hypot(dx, dz));- dx = (dx / length) * speed * dt;- dz = (dz / length) * speed * dt;- const swimming =- blockAt(world, Math.floor(p.x), Math.floor(p.y + 0.3), Math.floor(p.z)) ===- 7;- for (const [axis, delta] of [- ["x", dx],- ["z", dz],- ]) {- const n = clamp(- p[axis] + delta,- 0.3,- (axis === "x" ? world.w : world.d) - 0.3,- ),- x = axis === "x" ? n : p.x,- z = axis === "z" ? n : p.z;- if (playerFits(world, x, p.y, z)) p[axis] = n;- else if (- (p.grounded || swimming) &&- playerFits(world, x, p.y + (swimming ? 1.3 : 1.05), z)- ) {- p[axis] = n;- p.y += swimming ? 1.3 : 1.05;- }- }- if (input.jump && (p.grounded || swimming)) p.vy = 6;- p.vy = (p.vy || 0) - 16 * dt;- if (swimming && p.y < 5.85) p.vy = Math.max(p.vy, (5.85 - p.y) * 5);- const nextY = p.y + p.vy * dt;- if (playerFits(world, p.x, nextY, p.z)) {- p.y = nextY;- p.grounded = false;- } else {- if (p.vy < 0) {- p.grounded = true;- p.y = Math.ceil(nextY);- }- p.vy = 0;- }- if (p.y < 0) {- Object.assign(p, world.spawn, { vy: 0, grounded: true });- }- return p;-}+ precision highp float;+ precision highp int;-function importWorld(value) {- if (- !value ||- value.format !== "tidelands-1" ||- JSON.stringify(value.size) !== "[48,28,48]" ||- !Array.isArray(value.blocks) ||- value.blocks.length !== 48 * 28 * 48 ||- !value.blocks.every(- (n) => Number.isInteger(n) && n >= 0 && n < blockTypes.length,- )- )- throw new Error("This file is not a valid Tidelands world.");- const world = {- seed: String(value.seed).slice(0, 128),- w: 48,- h: 28,- d: 48,- blocks: Uint8Array.from(value.blocks),- };- const p = value.player;- if (- !p ||- !["x", "y", "z", "yaw", "pitch"].every((k) => Number.isFinite(p[k])) ||- p.x < 0.3 ||- p.x > 47.7 ||- p.z < 0.3 ||- p.z > 47.7 ||- p.y < 0 ||- p.y > 28 ||- !playerFits(world, p.x, p.y, p.z)- )- throw new Error("The saved player position is invalid.");- world.spawn = {- x: p.x,- y: p.y,- z: p.z,- yaw: p.yaw,- pitch: clamp(p.pitch, -1.3, 1.3),- };- return {- world,- player: { ...world.spawn, vy: 0, grounded: false },- timeOfDay: Number.isFinite(value.timeOfDay)- ? clamp(value.timeOfDay, 0, 1)- : 0.32,- };-}+ varying vec3 vOutputDirection;-</script>-<script>-'use strict';-const $ = (s) => document.querySelector(s);-const $$ = (s) => [...document.querySelectorAll(s)];-const params = new URLSearchParams(location.search);-let seed = (params.get("seed") || "42").slice(0, 128);-const reducedMotion = matchMedia("(prefers-reduced-motion: reduce)").matches;-const parentMessage = (message) => {- if (parent !== window) parent.postMessage(message, "*");-};-function toast(message) {- $("#toast").textContent = message;- clearTimeout(toast.timer);- toast.timer = setTimeout(() => {- $("#toast").textContent = "";- }, 3500);-}-function saveFile(name, content, type = "application/json") {- const blob =- content instanceof Blob ? content : new Blob([content], { type });- const url = URL.createObjectURL(blob),- a = document.createElement("a");- a.href = url;- a.download = name;- document.body.append(a);- a.click();- a.remove();- setTimeout(() => URL.revokeObjectURL(url), 30000);-}-function canvasPNG(canvas, name) {- canvas.toBlob((blob) => {- if (blob) saveFile(name, blob);- else toast("Image export failed. Please try again.");- });-}-function setSeed(value) {- seed = String(value).trim().slice(0, 128) || "42";- $("#seed").value = seed;- const url = new URL(location.href);- url.searchParams.set("seed", seed);- try {- history.replaceState(null, "", url);- } catch {- /* Opaque-origin iframe: the shell owns its URL. */- }- parentMessage({ type: "harness:state", seed });- dispatchEvent(new CustomEvent("seedchange", { detail: seed }));-}-$("#seed").value = seed;-$("#seed-form").addEventListener("submit", (e) => {- e.preventDefault();- setSeed($("#seed").value);-});-$("#next-seed").addEventListener("click", () =>- setSeed(/^\d{1,9}$/.test(seed) ? Number(seed) + 1 : hash(seed)),-);-function fitCanvas(canvas, draw, maxDpr = 2) {- const observer = new ResizeObserver(() => {- const box = canvas.getBoundingClientRect(),- dpr = Math.min(devicePixelRatio || 1, maxDpr);- canvas.width = Math.max(1, Math.round(box.width * dpr));- canvas.height = Math.max(1, Math.round(box.height * dpr));- draw?.();- });- observer.observe(canvas);- return observer;-}-const editable = (target) =>- target instanceof Element &&- !!target.closest("input,textarea,select,[contenteditable=true]");-addEventListener("error", (e) =>- parentMessage({ type: "harness:error", message: e.message }),-);-addEventListener("unhandledrejection", (e) =>- parentMessage({- type: "harness:error",- message: String(e.reason?.message || e.reason),- }),-);-function ready() {- document.body.dataset.ready = "true";- parentMessage({ type: "harness:ready", title: document.title, seed });-}+ uniform sampler2D envMap;+ uniform float roughness;+ uniform float mipInt;-let worldDirty = true;-let world,- player,- targetBlock,- gl,- program,- worldBuffer,- worldVertexCount = 0,- lineBuffer,- keys = {},- selected = 8,- overview = false,- cycling = false,- timeOfDay = 0.32,- lastWorldTime = 0,- worldAccum = 0,- drag = null,- edited = 0;-const canvas = $("#world");-function shader(type, source) {- const s = gl.createShader(type);- gl.shaderSource(s, source);- gl.compileShader(s);- if (!gl.getShaderParameter(s, gl.COMPILE_STATUS))- throw new Error(gl.getShaderInfoLog(s));- return s;-}-function initGL() {- gl = canvas.getContext("webgl", {- antialias: true,- alpha: true,- preserveDrawingBuffer: true,- });- if (!gl)- throw new Error(- "This world needs WebGL. Enable hardware acceleration or try another browser.",- );- program = gl.createProgram();- gl.attachShader(- program,- shader(- gl.VERTEX_SHADER,- `attribute vec3 position;attribute vec3 color;attribute vec3 normal;attribute vec2 uv;uniform vec3 eye;uniform vec3 right;uniform vec3 up;uniform vec3 forward;uniform float aspect;varying vec3 vColor;varying vec2 vUV;varying float distance;varying float light;void main(){vec3 p=position-eye;float z=dot(p,forward);gl_Position=vec4(dot(p,right)*1.4/aspect,dot(p,up)*1.4,1.0005*z-.100025,z);vColor=color;vUV=uv;distance=length(p);light=.65+max(0.,dot(normal,normalize(vec3(-.4,.9,.3))))*.35;}`,- ),- );- gl.attachShader(- program,- shader(- gl.FRAGMENT_SHADER,- `precision mediump float;varying vec3 vColor;varying vec2 vUV;varying float distance;varying float light;uniform vec3 sky;uniform float day;void main(){vec2 pixel=floor(vUV*12.);float grain=fract(sin(dot(pixel,vec2(12.9898,78.233)))*43758.5453);float edge=step(.04,fract(vUV.x))*step(.04,fract(vUV.y));if(vColor.b>vColor.r*1.5){grain=.6;edge=1.;}vec3 c=vColor*(.86+grain*.2)*light*(.25+day*.75)*(.88+.12*edge);gl_FragColor=vec4(mix(c,sky,smoothstep(35.,150.,distance)*.65),1.);}`,- ),- );- gl.linkProgram(program);- if (!gl.getProgramParameter(program, gl.LINK_STATUS))- throw new Error(gl.getProgramInfoLog(program));- gl.useProgram(program);- gl.enable(gl.DEPTH_TEST);- worldBuffer = gl.createBuffer();- lineBuffer = gl.createBuffer();-}-const faces = [- {- n: [1, 0, 0],- v: [- [1, 0, 0],- [1, 1, 0],- [1, 1, 1],- [1, 0, 1],- ],- },- {- n: [-1, 0, 0],- v: [- [0, 0, 1],- [0, 1, 1],- [0, 1, 0],- [0, 0, 0],- ],- },- {- n: [0, 1, 0],- v: [- [0, 1, 1],- [1, 1, 1],- [1, 1, 0],- [0, 1, 0],- ],- },- {- n: [0, -1, 0],- v: [- [0, 0, 0],- [1, 0, 0],- [1, 0, 1],- [0, 0, 1],- ],- },- {- n: [0, 0, 1],- v: [- [1, 0, 1],- [1, 1, 1],- [0, 1, 1],- [0, 0, 1],- ],- },- {- n: [0, 0, -1],- v: [- [0, 0, 0],- [0, 1, 0],- [1, 1, 0],- [1, 0, 0],- ],- },-];-function meshWorld() {- const data = [],- uvs = [- [0, 0],- [0, 1],- [1, 1],- [1, 0],- ];- for (let y = 0; y < world.h; y++)- for (let z = 0; z < world.d; z++)- for (let x = 0; x < world.w; x++) {- const id = blockAt(world, x, y, z);- if (!id) continue;- for (const face of faces) {- const [nx, ny, nz] = face.n,- next = blockAt(world, x + nx, y + ny, z + nz);- if (next && (id === 7 || next !== 7)) continue;- let color = blockTypes[id].color;- if (id === 1 && ny === 0) color = [0.43, 0.43, 0.25];- if (id === 7 && ny < 1) continue;- for (const i of [0, 1, 2, 0, 2, 3])- data.push(- x + face.v[i][0],- y + face.v[i][1],- z + face.v[i][2],- ...color,- ...face.n,- ...uvs[i],- );- }- }- for (const [x1, z1, x2, z2] of [- [-160, -160, 208, 0],- [-160, 48, 208, 208],- [-160, 0, 0, 48],- [48, 0, 208, 48],- ]) {- const vertices = [- [x1, 6, z1],- [x2, 6, z1],- [x2, 6, z2],- [x1, 6, z2],- ];- for (const i of [0, 1, 2, 0, 2, 3])- data.push(- ...vertices[i],- 0.24,- 0.52,- 0.59,- 0,- 1,- 0,- vertices[i][0],- vertices[i][2],- );- }- gl.bindBuffer(gl.ARRAY_BUFFER, worldBuffer);- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(data), gl.STATIC_DRAW);- worldVertexCount = data.length / 11;-}-function bindVertices(buffer) {- gl.bindBuffer(gl.ARRAY_BUFFER, buffer);- for (const [name, size, offset] of [- ["position", 3, 0],- ["color", 3, 3],- ["normal", 3, 6],- ["uv", 2, 9],- ]) {- const loc = gl.getAttribLocation(program, name);- gl.enableVertexAttribArray(loc);- gl.vertexAttribPointer(loc, size, gl.FLOAT, false, 44, offset * 4);- }-}-function drawWorld() {- if (!gl || !world) return;- const w = canvas.width,- h = canvas.height;- gl.viewport(0, 0, w, h);- const daylight = 0.25 + 0.75 * Math.max(0, Math.sin(timeOfDay * Math.PI * 2)),- sky = [- lerp(0.075, 0.64, daylight),- lerp(0.12, 0.76, daylight),- lerp(0.19, 0.76, daylight),- ];- canvas.style.background = `radial-gradient(circle at 72% 20%,rgba(255,239,182,${daylight}) 0 3%,transparent 3.2%),linear-gradient(180deg,rgb(${sky.map((n) => Math.round(n * 180)).join(",")}),rgb(${sky.map((n) => Math.round(n * 255)).join(",")}) 65%)`;- gl.clearColor(0, 0, 0, 0);- gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);- const camera = overview- ? { x: 57, y: 36, z: 62, yaw: -2.4, pitch: -0.53 }- : { ...player, y: player.y + 1.6 };- const { yaw, pitch } = camera,- forward = [- Math.sin(yaw) * Math.cos(pitch),- Math.sin(pitch),- Math.cos(yaw) * Math.cos(pitch),- ],- right = [Math.cos(yaw), 0, -Math.sin(yaw)],- up = [- -Math.sin(yaw) * Math.sin(pitch),- Math.cos(pitch),- -Math.cos(yaw) * Math.sin(pitch),- ];- for (const [name, value] of [- ["eye", [camera.x, camera.y, camera.z]],- ["forward", forward],- ["right", right],- ["up", up],- ["sky", sky],- ])- gl.uniform3fv(gl.getUniformLocation(program, name), value);- gl.uniform1f(gl.getUniformLocation(program, "aspect"), w / h);- gl.uniform1f(gl.getUniformLocation(program, "day"), daylight);- bindVertices(worldBuffer);- gl.drawArrays(gl.TRIANGLES, 0, worldVertexCount);- targetBlock = overview- ? null- : raycastWorld(- world,- { x: camera.x, y: camera.y, z: camera.z },- { x: forward[0], y: forward[1], z: forward[2] },- );- if (targetBlock) {- const { x, y, z } = targetBlock,- data = [],- corners = [- [0, 0, 0],- [1, 0, 0],- [1, 1, 0],- [0, 1, 0],- [0, 0, 1],- [1, 0, 1],- [1, 1, 1],- [0, 1, 1],- ];- for (const [a, b] of [- [0, 1],- [1, 2],- [2, 3],- [3, 0],- [4, 5],- [5, 6],- [6, 7],- [7, 4],- [0, 4],- [1, 5],- [2, 6],- [3, 7],- ])- for (const i of [a, b])- data.push(- x + corners[i][0] * 1.004 - 0.002,- y + corners[i][1] * 1.004 - 0.002,- z + corners[i][2] * 1.004 - 0.002,- 1,- 1,- 0.78,- 0,- 1,- 0,- 0.5,- 0.5,- );- gl.bindBuffer(gl.ARRAY_BUFFER, lineBuffer);- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(data), gl.DYNAMIC_DRAW);- bindVertices(lineBuffer);- gl.drawArrays(gl.LINES, 0, data.length / 11);- }- $("#target").textContent = overview- ? "An island shaped by your seed. Return to the trail to build."- : targetBlock- ? `${blockTypes[targetBlock.id].name} · ${targetBlock.distance.toFixed(1)} m · left click breaks / right click places`- : "Click to look · WASD to walk · Space to jump · drag to look on touch";- $("#coordinates").textContent =- `${player.x.toFixed(1)} / ${player.y.toFixed(1)} / ${player.z.toFixed(1)} · ${edited} edits`;- const hour = Math.floor(timeOfDay * 24);- $("#world-clock").textContent =- `${String(hour).padStart(2, "0")}:${String(Math.floor(timeOfDay * 24 * 60) % 60).padStart(2, "0")} · island ${seed.slice(0, 14)}`;-}-let clickAudio;-function blockClick() {- try {- clickAudio ??= new (window.AudioContext || window.webkitAudioContext)();- clickAudio.resume();- const o = clickAudio.createOscillator(),- g = clickAudio.createGain();- o.type = "triangle";- o.frequency.value = selected === 9 ? 660 : 180;- g.gain.setValueAtTime(0.07, clickAudio.currentTime);- g.gain.exponentialRampToValueAtTime(0.001, clickAudio.currentTime + 0.075);- o.connect(g).connect(clickAudio.destination);- o.start();- o.stop(clickAudio.currentTime + 0.08);- } catch {}-}-function editBlock(place) {- if (!targetBlock) return toast("Look at a nearby block first.");- const p = place ? targetBlock.previous : targetBlock;- if (!p || p.y < 1) return toast("The foundation stays in place.");- if (- place &&- Math.abs(p.x + 0.5 - player.x) < 0.75 &&- Math.abs(p.z + 0.5 - player.z) < 0.75 &&- p.y < player.y + 1.8 &&- p.y + 1 > player.y- )- return toast("Step back a little before placing that block.");- if (putBlock(world, p.x, p.y, p.z, place ? selected : 0)) {- edited++;- meshWorld();- blockClick();- drawWorld();- }-}-function newWorld() {- world = voxelWorld(seed);- player = { ...world.spawn, vy: 0, grounded: true };- edited = 0;- meshWorld();- drawWorld();-}-for (const [id, i] of [1, 3, 5, 8, 9].map((id, i) => [id, i])) {- const b = document.createElement("button");- b.setAttribute("aria-label", blockTypes[id].name);- b.title = `${i + 1}: ${blockTypes[id].name}`;- b.setAttribute("aria-pressed", selected === id);- const sw = document.createElement("i");- sw.style.background = `rgb(${blockTypes[id].color.map((n) => Math.round(n * 255)).join(",")})`;- b.append(sw, document.createTextNode(blockTypes[id].name));- b.onclick = () => {- selected = id;- $$("#hotbar button").forEach((button, j) =>- button.setAttribute("aria-pressed", j === i),- );- };- $("#hotbar").append(b);-}-$("#break").onclick = () => editBlock(false);-$("#place").onclick = () => editBlock(true);-$("#overview").onclick = () => {- overview = !overview;- document.body.classList.toggle("overview", overview);- $("#overview").textContent = overview- ? "Back to the trail"- : "Island overview";- document.exitPointerLock?.();- drawWorld();-};-$("#home").onclick = () => {- player = { ...world.spawn, vy: 0, grounded: true };- overview = false;- document.body.classList.remove("overview");- $("#overview").textContent = "Island overview";- drawWorld();-};-$("#daylight").oninput = () => {- timeOfDay = +$("#daylight").value / 100;- drawWorld();-};-$("#cycle").onclick = () => {- cycling = !cycling;- $("#cycle").setAttribute("aria-pressed", cycling);-};-$("#export-world").onclick = () =>- saveFile(- `tidelands-${hash(seed)}.json`,- JSON.stringify({- format: "tidelands-1",- seed,- size: [world.w, world.h, world.d],- blocks: Array.from(world.blocks),- player,- timeOfDay,- }),- );-canvas.oncontextmenu = (e) => e.preventDefault();-canvas.onpointerdown = (e) => {- canvas.focus();- if (overview) return;- if (document.pointerLockElement === canvas) {- editBlock(e.button === 2);- return;- }- drag = { x: e.clientX, y: e.clientY };- if (e.pointerType === "mouse")- canvas.requestPointerLock?.()?.catch?.(() => toast("Drag to look around."));- else canvas.setPointerCapture(e.pointerId);-};-canvas.onpointerup = canvas.onpointercancel = () => {- drag = null;-};-addEventListener("pointerup", () => {- drag = null;-});-document.addEventListener("pointerlockchange", () => {- drag = null;-});-canvas.onpointermove = (e) => {- if (overview) return;- let dx = 0,- dy = 0;- if (document.pointerLockElement === canvas) {- dx = e.movementX;- dy = e.movementY;- } else if (drag) {- dx = e.clientX - drag.x;- dy = e.clientY - drag.y;- drag = { x: e.clientX, y: e.clientY };- }- if (dx || dy) worldDirty = true;- player.yaw += dx * 0.004;- player.pitch = clamp(player.pitch - dy * 0.004, -1.3, 1.3);-};-addEventListener("keydown", (e) => {- if (editable(e.target)) return;- const key = e.key.toLowerCase();- if (- [- "w",- "a",- "s",- "d",- " ",- "shift",- "arrowup",- "arrowdown",- "arrowleft",- "arrowright",- ].includes(key)- ) {- e.preventDefault();- keys[key] = true;- }- if (/^[1-5]$/.test(key)) $$("#hotbar button")[+key - 1].click();-});-addEventListener("keyup", (e) => {- keys[e.key.toLowerCase()] = false;-});-addEventListener("blur", () => {- keys = {};- drag = null;-});-$$(".world-pad button").forEach((b) => {- b.onpointerdown = (e) => {- e.preventDefault();- keys[b.dataset.key] = true;- b.setPointerCapture(e.pointerId);- };- b.onpointerup = b.onpointercancel = () => {- keys[b.dataset.key] = false;- };-});-function worldFrame(time) {- const delta = Math.min(0.1, (time - lastWorldTime) / 1000 || 0);- lastWorldTime = time;- if (!document.hidden) {- const before = { x: player.x, y: player.y, z: player.z };- if (!overview) {- worldAccum += delta;- while (worldAccum >= 1 / 60) {- player = movePlayer(world, player, {- forward:- (keys.w || keys.arrowup ? 1 : 0) -- (keys.s || keys.arrowdown ? 1 : 0),- right:- (keys.d || keys.arrowright ? 1 : 0) -- (keys.a || keys.arrowleft ? 1 : 0),- jump: keys[" "],- sprint: keys.shift,- });- worldAccum -= 1 / 60;- }- }- if (cycling) {- timeOfDay = (timeOfDay + delta / 240) % 1;- $("#daylight").value = timeOfDay * 100;- }- if (- worldDirty ||- cycling ||- Math.hypot(- player.x - before.x,- player.y - before.y,- player.z - before.z,- ) > 0.0001- ) {- drawWorld();- worldDirty = false;- }- }- requestAnimationFrame(worldFrame);-}-try {- initGL();- newWorld();- fitCanvas(canvas, drawWorld, 1.5);- addEventListener("seedchange", newWorld);- requestAnimationFrame(worldFrame);- ready();-} catch (error) {- $("#world-error").hidden = false;- $("#world-error").textContent = error.message;- parentMessage({ type: "harness:error", message: error.message });-}+ #define ENVMAP_TYPE_CUBE_UV+ #include <cube_uv_reflection_fragment>-$("#import-world").onclick = () => $("#world-file").click();-$("#world-file").onchange = async (e) => {- const file = e.target.files[0];- if (!file) return;- try {- if (file.size > 2 * 1024 * 1024)- throw new Error("Choose a Tidelands JSON file smaller than 2 MiB.");- const restored = importWorld(JSON.parse(await file.text()));- setSeed(restored.world.seed);- world = restored.world;- player = restored.player;- timeOfDay = restored.timeOfDay;- $("#daylight").value = timeOfDay * 100;- edited = 0;- meshWorld();- drawWorld();- toast("Your world is restored.");- } catch (error) {- toast(error.message);- } finally {- e.target.value = "";- }-};+ #define PI 3.14159265359++ // Van der Corput radical inverse+ float radicalInverse_VdC(uint bits) {+ bits = (bits << 16u) | (bits >> 16u);+ bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);+ bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);+ bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);+ bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);+ return float(bits) * 2.3283064365386963e-10; // / 0x100000000+ }++ // Hammersley sequence+ vec2 hammersley(uint i, uint N) {+ return vec2(float(i) / float(N), radicalInverse_VdC(i));+ }++ // GGX VNDF importance sampling (Eric Heitz 2018)+ // "Sampling the GGX Distribution of Visible Normals"+ // https://jcgt.org/published/0007/04/01/+ vec3 importanceSampleGGX_VNDF(vec2 Xi, vec3 V, float roughness) {+ float alpha = roughness * roughness;++ // Section 4.1: Orthonormal basis+ vec3 T1 = vec3(1.0, 0.0, 0.0);+ vec3 T2 = cross(V, T1);++ // Section 4.2: Parameterization of projected area+ float r = sqrt(Xi.x);+ float phi = 2.0 * PI * Xi.y;+ float t1 = r * cos(phi);+ float t2 = r * sin(phi);+ float s = 0.5 * (1.0 + V.z);+ t2 = (1.0 - s) * sqrt(1.0 - t1 * t1) + s * t2;++ // Section 4.3: Reprojection onto hemisphere+ vec3 Nh = t1 * T1 + t2 * T2 + sqrt(max(0.0, 1.0 - t1 * t1 - t2 * t2)) * V;++ // Section 3.4: Transform back to ellipsoid configuration+ return normalize(vec3(alpha * Nh.x, alpha * Nh.y, max(0.0, Nh.z)));+ }++ void main() {+ vec3 N = normalize(vOutputDirection);+ vec3 V = N; // Assume view direction equals normal for pre-filtering++ vec3 prefilteredColor = vec3(0.0);+ float totalWeight = 0.0;++ // For very low roughness, just sample the environment directly+ if (roughness < 0.001) {+ gl_FragColor = vec4(bilinearCubeUV(envMap, N, mipInt), 1.0);+ return;+ }++ // Tangent space basis for VNDF sampling+ vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);+ vec3 tangent = normalize(cross(up, N));+ vec3 bitangent = cross(N, tangent);++ for(uint i = 0u; i < uint(GGX_SAMPLES); i++) {+ vec2 Xi = hammersley(i, uint(GGX_SAMPLES));++ // For PMREM, V = N, so in tangent space V is always (0, 0, 1)+ vec3 H_tangent = importanceSampleGGX_VNDF(Xi, vec3(0.0, 0.0, 1.0), roughness);++ // Transform H back to world space+ vec3 H = normalize(tangent * H_tangent.x + bitangent * H_tangent.y + N * H_tangent.z);+ vec3 L = normalize(2.0 * dot(V, H) * H - V);++ float NdotL = max(dot(N, L), 0.0);++ if(NdotL > 0.0) {+ // Sample environment at fixed mip level+ // VNDF importance sampling handles the distribution filtering+ vec3 sampleColor = bilinearCubeUV(envMap, L, mipInt);++ // Weight by NdotL for the split-sum approximation+ // VNDF PDF naturally accounts for the visible microfacet distribution+ prefilteredColor += sampleColor * NdotL;+ totalWeight += NdotL;+ }+ }++ if (totalWeight > 0.0) {+ prefilteredColor = prefilteredColor / totalWeight;+ }++ gl_FragColor = vec4(prefilteredColor, 1.0);+ }+ `,blending:Hn,depthTest:!1,depthWrite:!1})}function Vg(i,t,e){return new un({name:"SphericalGaussianBlur",defines:{SAMPLES:Fg,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/e,CUBEUV_MAX_MIP:`${i}.0`},uniforms:{envMap:{value:null},sigma:{value:0},mipInt:{value:0}},vertexShader:nl(),fragmentShader:`++ precision highp float;+ precision highp int;++ varying vec3 vOutputDirection;++ uniform sampler2D envMap;+ uniform float sigma;+ uniform float mipInt;++ #define ENVMAP_TYPE_CUBE_UV+ #include <cube_uv_reflection_fragment>++ #define PI 3.14159265359+ #define GOLDEN_ANGLE 2.39996322973++ void main() {++ if ( sigma == 0.0 ) {++ gl_FragColor = vec4( bilinearCubeUV( envMap, vOutputDirection, mipInt ), 1.0 );+ return;++ }++ vec3 outputDirection = normalize( vOutputDirection );++ vec3 up = abs( outputDirection.z ) < 0.999 ? vec3( 0.0, 0.0, 1.0 ) : vec3( 1.0, 0.0, 0.0 );+ vec3 tangent = normalize( cross( up, outputDirection ) );+ vec3 bitangent = cross( outputDirection, tangent );++ // Truncate the kernel at three standard deviations or at the antipode.+ float thetaMax = min( 3.0 * sigma, PI );+ float truncation = 1.0 - exp( - 0.5 * thetaMax * thetaMax / ( sigma * sigma ) );++ vec3 accumColor = vec3( 0.0 );+ float accumWeight = 0.0;++ for ( int i = 0; i < SAMPLES; i ++ ) {++ // Stratified inverse-CDF sampling of the Gaussian, placed on a golden-angle spiral.+ float stratum = ( float( i ) + 0.5 ) / float( SAMPLES );+ float theta = sigma * sqrt( - 2.0 * log( 1.0 - stratum * truncation ) );+ float phi = float( i ) * GOLDEN_ANGLE;++ vec3 offset = cos( phi ) * tangent + sin( phi ) * bitangent;+ vec3 sampleDirection = cos( theta ) * outputDirection + sin( theta ) * offset;++ // Correct the planar sample density to solid angle.+ float weight = sin( theta ) / theta;++ accumColor += weight * bilinearCubeUV( envMap, sampleDirection, mipInt );+ accumWeight += weight;++ }++ gl_FragColor = vec4( accumColor / accumWeight, 1.0 );++ }+ `,blending:Hn,depthTest:!1,depthWrite:!1})}function Bu(){return new un({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:nl(),fragmentShader:`++ precision mediump float;+ precision mediump int;++ varying vec3 vOutputDirection;++ uniform sampler2D envMap;++ #include <common>++ void main() {++ vec3 outputDirection = normalize( vOutputDirection );+ vec2 uv = equirectUv( outputDirection );++ gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );++ }+ `,blending:Hn,depthTest:!1,depthWrite:!1})}function zu(){return new un({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:nl(),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:Hn,depthTest:!1,depthWrite:!1})}function nl(){return`++ precision mediump float;+ precision mediump int;++ attribute vec3 outputDirection;++ varying vec3 vOutputDirection;++ void main() {++ vOutputDirection = outputDirection;+ gl_Position = vec4( position, 1.0 );++ }+ `}var tl=class extends Ke{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 xr(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 <begin_vertex>+ #include <project_vertex>++ }+ `,fragmentShader:`++ uniform sampler2D tEquirect;++ varying vec3 vWorldDirection;++ #include <common>++ void main() {++ vec3 direction = normalize( vWorldDirection );++ vec2 sampleUV = equirectUv( direction );++ gl_FragColor = texture2D( tEquirect, sampleUV );++ }+ `},s=new ge(5,5,5),r=new un({name:"CubemapFromEquirect",uniforms:Zi(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:Ze,blending:Hn});r.uniforms.tEquirect.value=e;let o=new ut(s,r),a=e.minFilter;return e.minFilter===Ci&&(e.minFilter=Fe),new oa(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)}};function Hg(i){let t=new WeakMap,e=new WeakMap,n=null;function s(h,p=!1){return h==null?null:p?o(h):r(h)}function r(h){if(h&&h.isTexture){let p=h.mapping;if(p===ca||p===ha)if(t.has(h)){let g=t.get(h).texture;return a(g,h.mapping)}else{let g=h.image;if(g&&g.height>0){let v=new tl(g.height);return v.fromEquirectangularTexture(i,h),t.set(h,v),h.addEventListener("dispose",l),a(v.texture,h.mapping)}else return null}}return h}function o(h){if(h&&h.isTexture){let p=h.mapping,g=p===ca||p===ha,v=p===Ai||p===qi;if(g||v){let m=e.get(h),d=m!==void 0?m.texture.pmremVersion:0;if(h.isRenderTargetTexture&&h.pmremVersion!==d)return n===null&&(n=new Qa(i)),m=g?n.fromEquirectangular(h,m):n.fromCubemap(h,m),m.texture.pmremVersion=h.pmremVersion,e.set(h,m),m.texture;if(m!==void 0)return m.texture;{let S=h.image;return g&&S&&S.height>0||v&&S&&c(S)?(n===null&&(n=new Qa(i)),m=g?n.fromEquirectangular(h):n.fromCubemap(h),m.texture.pmremVersion=h.pmremVersion,e.set(h,m),h.addEventListener("dispose",u),m.texture):null}}}return h}function a(h,p){return p===ca?h.mapping=Ai:p===ha&&(h.mapping=qi),h}function c(h){let p=0,g=6;for(let v=0;v<g;v++)h[v]!==void 0&&p++;return p===g}function l(h){let p=h.target;p.removeEventListener("dispose",l);let g=t.get(p);g!==void 0&&(t.delete(p),g.dispose())}function u(h){let p=h.target;p.removeEventListener("dispose",u);let g=e.get(p);g!==void 0&&(e.delete(p),g.dispose())}function f(){t=new WeakMap,e=new WeakMap,n!==null&&(n.dispose(),n=null)}return{get:s,dispose:f}}function Gg(i){let t={};function e(n){if(t[n]!==void 0)return t[n];let s=i.getExtension(n);return t[n]=s,s}return{has:function(n){return e(n)!==null},init:function(){e("EXT_color_buffer_float"),e("WEBGL_clip_cull_distance"),e("OES_texture_float_linear"),e("EXT_color_buffer_half_float"),e("WEBGL_multisampled_render_to_texture"),e("WEBGL_render_shared_exponent")},get:function(n){let s=e(n);return s===null&&Hi("WebGLRenderer: "+n+" extension not supported."),s}}}function Wg(i,t,e,n){let s={},r=new WeakMap;function o(f){let h=f.target;h.index!==null&&t.remove(h.index);for(let g in h.attributes)t.remove(h.attributes[g]);h.removeEventListener("dispose",o),delete s[h.id];let p=r.get(h);p&&(t.remove(p),r.delete(h)),n.releaseStatesOfGeometry(h),h.isInstancedBufferGeometry===!0&&delete h._maxInstanceCount,e.memory.geometries--}function a(f,h){return s[h.id]===!0||(h.addEventListener("dispose",o),s[h.id]=!0,e.memory.geometries++),h}function c(f){let h=f.attributes;for(let p in h)t.update(h[p],i.ARRAY_BUFFER)}function l(f){let h=[],p=f.index,g=f.attributes.position,v=0;if(g===void 0)return;if(p!==null){let S=p.array;v=p.version;for(let T=0,y=S.length;T<y;T+=3){let b=S[T+0],w=S[T+1],C=S[T+2];h.push(b,w,w,C,C,b)}}else{let S=g.array;v=g.version;for(let T=0,y=S.length/3-1;T<y;T+=3){let b=T+0,w=T+1,C=T+2;h.push(b,w,w,C,C,b)}}let m=new(g.count>=65535?gr:mr)(h,1);m.version=v;let d=r.get(f);d&&t.remove(d),r.set(f,m)}function u(f){let h=r.get(f);if(h){let p=f.index;p!==null&&h.version<p.version&&l(f)}else l(f);return r.get(f)}return{get:a,update:c,getWireframeAttribute:u}}function Xg(i,t,e){let n;function s(f){n=f}let r,o;function a(f){r=f.type,o=f.bytesPerElement}function c(f,h){i.drawElements(n,h,r,f*o),e.update(h,n,1)}function l(f,h,p){p!==0&&(i.drawElementsInstanced(n,h,r,f*o,p),e.update(h,n,p))}function u(f,h,p){if(p===0)return;t.get("WEBGL_multi_draw").multiDrawElementsWEBGL(n,h,0,r,f,0,p);let v=0;for(let m=0;m<p;m++)v+=h[m];e.update(v,n,1)}this.setMode=s,this.setIndex=a,this.render=c,this.renderInstances=l,this.renderMultiDraw=u}function Yg(i){let t={geometries:0,textures:0},e={frame:0,calls:0,triangles:0,points:0,lines:0};function n(r,o,a){switch(e.calls++,o){case i.TRIANGLES:e.triangles+=a*(r/3);break;case i.LINES:e.lines+=a*(r/2);break;case i.LINE_STRIP:e.lines+=a*(r-1);break;case i.LINE_LOOP:e.lines+=a*r;break;case i.POINTS:e.points+=a*r;break;default:Dt("WebGLInfo: Unknown draw mode:",o);break}}function s(){e.calls=0,e.triangles=0,e.points=0,e.lines=0}return{memory:t,render:e,programs:null,autoReset:!0,reset:s,update:n}}function qg(i,t,e){let n=new WeakMap,s=new me;function r(o,a,c){let l=o.morphTargetInfluences,u=a.morphAttributes.position||a.morphAttributes.normal||a.morphAttributes.color,f=u!==void 0?u.length:0,h=n.get(a);if(h===void 0||h.count!==f){let E=function(){C.dispose(),n.delete(a),a.removeEventListener("dispose",E)};h!==void 0&&h.texture.dispose();let p=a.morphAttributes.position!==void 0,g=a.morphAttributes.normal!==void 0,v=a.morphAttributes.color!==void 0,m=a.morphAttributes.position||[],d=a.morphAttributes.normal||[],S=a.morphAttributes.color||[],T=0;p===!0&&(T=1),g===!0&&(T=2),v===!0&&(T=3);let y=a.attributes.position.count*T,b=1;y>t.maxTextureSize&&(b=Math.ceil(y/t.maxTextureSize),y=t.maxTextureSize);let w=new Float32Array(y*b*4*f),C=new dr(w,y,b,f);C.type=In,C.needsUpdate=!0;let _=T*4;for(let R=0;R<f;R++){let L=m[R],F=d[R],z=S[R],I=y*b*4*R;for(let O=0;O<L.count;O++){let G=O*_;p===!0&&(s.fromBufferAttribute(L,O),w[I+G+0]=s.x,w[I+G+1]=s.y,w[I+G+2]=s.z,w[I+G+3]=0),g===!0&&(s.fromBufferAttribute(F,O),w[I+G+4]=s.x,w[I+G+5]=s.y,w[I+G+6]=s.z,w[I+G+7]=0),v===!0&&(s.fromBufferAttribute(z,O),w[I+G+8]=s.x,w[I+G+9]=s.y,w[I+G+10]=s.z,w[I+G+11]=z.itemSize===4?s.w:1)}}h={count:f,texture:C,size:new Pt(y,b)},n.set(a,h),a.addEventListener("dispose",E)}if(o.isInstancedMesh===!0&&o.morphTexture!==null)c.getUniforms().setValue(i,"morphTexture",o.morphTexture,e);else{let p=0;for(let v=0;v<l.length;v++)p+=l[v];let g=a.morphTargetsRelative?1:1-p;c.getUniforms().setValue(i,"morphTargetBaseInfluence",g),c.getUniforms().setValue(i,"morphTargetInfluences",l)}c.getUniforms().setValue(i,"morphTargetsTexture",h.texture,e),c.getUniforms().setValue(i,"morphTargetsTextureSize",h.size)}return{update:r}}function Zg(i,t,e,n,s){let r=new WeakMap;function o(l){let u=s.render.frame,f=l.geometry,h=t.get(l,f);if(r.get(h)!==u&&(t.update(h),r.set(h,u)),l.isInstancedMesh&&(l.hasEventListener("dispose",c)===!1&&l.addEventListener("dispose",c),r.get(l)!==u&&(e.update(l.instanceMatrix,i.ARRAY_BUFFER),l.instanceColor!==null&&e.update(l.instanceColor,i.ARRAY_BUFFER),r.set(l,u))),l.isSkinnedMesh){let p=l.skeleton;r.get(p)!==u&&(p.update(),r.set(p,u))}return h}function a(){r=new WeakMap}function c(l){let u=l.target;u.removeEventListener("dispose",c),n.releaseStatesOfObject(u),e.remove(u.instanceMatrix),u.instanceColor!==null&&e.remove(u.instanceColor)}return{update:o,dispose:a}}var jg={[sc]:"LINEAR_TONE_MAPPING",[rc]:"REINHARD_TONE_MAPPING",[oc]:"CINEON_TONE_MAPPING",[Pr]:"ACES_FILMIC_TONE_MAPPING",[lc]:"AGX_TONE_MAPPING",[cc]:"NEUTRAL_TONE_MAPPING",[ac]:"CUSTOM_TONE_MAPPING"};function Jg(i,t,e,n,s,r){let o=new Ke(t,e,{type:i,depthBuffer:s,stencilBuffer:r,samples:n?4:0,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1,resolveDepthBuffer:!1,resolveStencilBuffer:!1}),a=null,c=null,l=new ve;l.setAttribute("position",new Yt([-1,3,0,-1,-1,0,3,-1,0],3)),l.setAttribute("uv",new Yt([0,2,0,0,2,0],2));let u=new qo({uniforms:{tDiffuse:{value:null}},vertexShader:`+ precision highp float;++ uniform mat4 modelViewMatrix;+ uniform mat4 projectionMatrix;++ attribute vec3 position;+ attribute vec2 uv;++ varying vec2 vUv;++ void main() {+ vUv = uv;+ gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );+ }`,fragmentShader:`+ precision highp float;++ uniform sampler2D tDiffuse;++ varying vec2 vUv;++ #include <tonemapping_pars_fragment>+ #include <colorspace_pars_fragment>++ void main() {+ gl_FragColor = texture2D( tDiffuse, vUv );++ #ifdef LINEAR_TONE_MAPPING+ gl_FragColor.rgb = LinearToneMapping( gl_FragColor.rgb );+ #elif defined( REINHARD_TONE_MAPPING )+ gl_FragColor.rgb = ReinhardToneMapping( gl_FragColor.rgb );+ #elif defined( CINEON_TONE_MAPPING )+ gl_FragColor.rgb = CineonToneMapping( gl_FragColor.rgb );+ #elif defined( ACES_FILMIC_TONE_MAPPING )+ gl_FragColor.rgb = ACESFilmicToneMapping( gl_FragColor.rgb );+ #elif defined( AGX_TONE_MAPPING )+ gl_FragColor.rgb = AgXToneMapping( gl_FragColor.rgb );+ #elif defined( NEUTRAL_TONE_MAPPING )+ gl_FragColor.rgb = NeutralToneMapping( gl_FragColor.rgb );+ #elif defined( CUSTOM_TONE_MAPPING )+ gl_FragColor.rgb = CustomToneMapping( gl_FragColor.rgb );+ #endif++ #ifdef SRGB_TRANSFER+ gl_FragColor = sRGBTransferOETF( gl_FragColor );+ #endif+ }`,depthTest:!1,depthWrite:!1}),f=new ut(l,u),h=new Os(-1,1,1,-1,0,1),p=null,g=null,v=!1,m,d=null,S=[],T=!1;this.setSize=function(y,b){o.setSize(y,b),a!==null&&a.setSize(y,b),c!==null&&c.setSize(y,b);for(let w=0;w<S.length;w++){let C=S[w];C.setSize&&C.setSize(y,b)}},this.setEffects=function(y){S=y,T=S.length>0&&S[0].isRenderPass===!0;let b=o.width,w=o.height;S.length>0&&a===null&&(a=new Ke(b,w,{type:Ln,depthBuffer:!1,stencilBuffer:!1}),c=new Ke(b,w,{type:Ln,depthBuffer:!1,stencilBuffer:!1}));for(let C=0;C<S.length;C++){let _=S[C];_.setSize&&_.setSize(b,w)}},this.begin=function(y,b){if(v||y.toneMapping===Rn&&S.length===0)return!1;if(d=b,b!==null){let w=b.width,C=b.height;(o.width!==w||o.height!==C)&&this.setSize(w,C)}return T===!1&&y.setRenderTarget(o),m=y.toneMapping,y.toneMapping=Rn,!0},this.hasRenderPass=function(){return T},this.end=function(y,b){y.toneMapping=m,v=!0;let w=o,C=a;for(let _=0;_<S.length;_++){let E=S[_];E.enabled!==!1&&(E.render(y,C,w,b),E.needsSwap!==!1&&(w=C,C=C===a?c:a))}if(p!==y.outputColorSpace||g!==y.toneMapping){p=y.outputColorSpace,g=y.toneMapping,u.defines={},Xt.getTransfer(p)===Qt&&(u.defines.SRGB_TRANSFER="");let _=jg[g];_&&(u.defines[_]=""),u.needsUpdate=!0}u.uniforms.tDiffuse.value=w.texture,y.setRenderTarget(d),y.render(f,h),d=null,v=!1},this.isCompositing=function(){return v},this.dispose=function(){o.dispose(),a!==null&&a.dispose(),c!==null&&c.dispose(),l.dispose(),u.dispose()}}var rd=new $e,Lc=new vi(1,1),od=new dr,ad=new Vo,ld=new xr,ku=[],Vu=[],Hu=new Float32Array(16),Gu=new Float32Array(9),Wu=new Float32Array(4);function qs(i,t,e){let n=i[0];if(n<=0||n>0)return i;let s=t*e,r=ku[s];if(r===void 0&&(r=new Float32Array(s),ku[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 Ce(i,t){if(i.length!==t.length)return!1;for(let e=0,n=i.length;e<n;e++)if(i[e]!==t[e])return!1;return!0}function Re(i,t){for(let e=0,n=t.length;e<n;e++)i[e]=t[e]}function il(i,t){let e=Vu[t];e===void 0&&(e=new Int32Array(t),Vu[t]=e);for(let n=0;n!==t;++n)e[n]=i.allocateTextureUnit();return e}function $g(i,t){let e=this.cache;e[0]!==t&&(i.uniform1f(this.addr,t),e[0]=t)}function Kg(i,t){let e=this.cache;if(t.x!==void 0)(e[0]!==t.x||e[1]!==t.y)&&(i.uniform2f(this.addr,t.x,t.y),e[0]=t.x,e[1]=t.y);else{if(Ce(e,t))return;i.uniform2fv(this.addr,t),Re(e,t)}}function Qg(i,t){let e=this.cache;if(t.x!==void 0)(e[0]!==t.x||e[1]!==t.y||e[2]!==t.z)&&(i.uniform3f(this.addr,t.x,t.y,t.z),e[0]=t.x,e[1]=t.y,e[2]=t.z);else if(t.r!==void 0)(e[0]!==t.r||e[1]!==t.g||e[2]!==t.b)&&(i.uniform3f(this.addr,t.r,t.g,t.b),e[0]=t.r,e[1]=t.g,e[2]=t.b);else{if(Ce(e,t))return;i.uniform3fv(this.addr,t),Re(e,t)}}function t0(i,t){let e=this.cache;if(t.x!==void 0)(e[0]!==t.x||e[1]!==t.y||e[2]!==t.z||e[3]!==t.w)&&(i.uniform4f(this.addr,t.x,t.y,t.z,t.w),e[0]=t.x,e[1]=t.y,e[2]=t.z,e[3]=t.w);else{if(Ce(e,t))return;i.uniform4fv(this.addr,t),Re(e,t)}}function e0(i,t){let e=this.cache,n=t.elements;if(n===void 0){if(Ce(e,t))return;i.uniformMatrix2fv(this.addr,!1,t),Re(e,t)}else{if(Ce(e,n))return;Wu.set(n),i.uniformMatrix2fv(this.addr,!1,Wu),Re(e,n)}}function n0(i,t){let e=this.cache,n=t.elements;if(n===void 0){if(Ce(e,t))return;i.uniformMatrix3fv(this.addr,!1,t),Re(e,t)}else{if(Ce(e,n))return;Gu.set(n),i.uniformMatrix3fv(this.addr,!1,Gu),Re(e,n)}}function i0(i,t){let e=this.cache,n=t.elements;if(n===void 0){if(Ce(e,t))return;i.uniformMatrix4fv(this.addr,!1,t),Re(e,t)}else{if(Ce(e,n))return;Hu.set(n),i.uniformMatrix4fv(this.addr,!1,Hu),Re(e,n)}}function s0(i,t){let e=this.cache;e[0]!==t&&(i.uniform1i(this.addr,t),e[0]=t)}function r0(i,t){let e=this.cache;if(t.x!==void 0)(e[0]!==t.x||e[1]!==t.y)&&(i.uniform2i(this.addr,t.x,t.y),e[0]=t.x,e[1]=t.y);else{if(Ce(e,t))return;i.uniform2iv(this.addr,t),Re(e,t)}}function o0(i,t){let e=this.cache;if(t.x!==void 0)(e[0]!==t.x||e[1]!==t.y||e[2]!==t.z)&&(i.uniform3i(this.addr,t.x,t.y,t.z),e[0]=t.x,e[1]=t.y,e[2]=t.z);else{if(Ce(e,t))return;i.uniform3iv(this.addr,t),Re(e,t)}}function a0(i,t){let e=this.cache;if(t.x!==void 0)(e[0]!==t.x||e[1]!==t.y||e[2]!==t.z||e[3]!==t.w)&&(i.uniform4i(this.addr,t.x,t.y,t.z,t.w),e[0]=t.x,e[1]=t.y,e[2]=t.z,e[3]=t.w);else{if(Ce(e,t))return;i.uniform4iv(this.addr,t),Re(e,t)}}function l0(i,t){let e=this.cache;e[0]!==t&&(i.uniform1ui(this.addr,t),e[0]=t)}function c0(i,t){let e=this.cache;if(t.x!==void 0)(e[0]!==t.x||e[1]!==t.y)&&(i.uniform2ui(this.addr,t.x,t.y),e[0]=t.x,e[1]=t.y);else{if(Ce(e,t))return;i.uniform2uiv(this.addr,t),Re(e,t)}}function h0(i,t){let e=this.cache;if(t.x!==void 0)(e[0]!==t.x||e[1]!==t.y||e[2]!==t.z)&&(i.uniform3ui(this.addr,t.x,t.y,t.z),e[0]=t.x,e[1]=t.y,e[2]=t.z);else{if(Ce(e,t))return;i.uniform3uiv(this.addr,t),Re(e,t)}}function u0(i,t){let e=this.cache;if(t.x!==void 0)(e[0]!==t.x||e[1]!==t.y||e[2]!==t.z||e[3]!==t.w)&&(i.uniform4ui(this.addr,t.x,t.y,t.z,t.w),e[0]=t.x,e[1]=t.y,e[2]=t.z,e[3]=t.w);else{if(Ce(e,t))return;i.uniform4uiv(this.addr,t),Re(e,t)}}function d0(i,t,e){let n=this.cache,s=e.allocateTextureUnit();n[0]!==s&&(i.uniform1i(this.addr,s),n[0]=s);let r;this.type===i.SAMPLER_2D_SHADOW?(Lc.compareFunction=e.isReversedDepthBuffer()?Ja:ja,r=Lc):r=rd,e.setTexture2D(t||r,s)}function f0(i,t,e){let n=this.cache,s=e.allocateTextureUnit();n[0]!==s&&(i.uniform1i(this.addr,s),n[0]=s),e.setTexture3D(t||ad,s)}function p0(i,t,e){let n=this.cache,s=e.allocateTextureUnit();n[0]!==s&&(i.uniform1i(this.addr,s),n[0]=s),e.setTextureCube(t||ld,s)}function m0(i,t,e){let n=this.cache,s=e.allocateTextureUnit();n[0]!==s&&(i.uniform1i(this.addr,s),n[0]=s),e.setTexture2DArray(t||od,s)}function g0(i){switch(i){case 5126:return $g;case 35664:return Kg;case 35665:return Qg;case 35666:return t0;case 35674:return e0;case 35675:return n0;case 35676:return i0;case 5124:case 35670:return s0;case 35667:case 35671:return r0;case 35668:case 35672:return o0;case 35669:case 35673:return a0;case 5125:return l0;case 36294:return c0;case 36295:return h0;case 36296:return u0;case 35678:case 36198:case 36298:case 36306:case 35682:return d0;case 35679:case 36299:case 36307:return f0;case 35680:case 36300:case 36308:case 36293:return p0;case 36289:case 36303:case 36311:case 36292:return m0}}function _0(i,t){i.uniform1fv(this.addr,t)}function x0(i,t){let e=qs(t,this.size,2);i.uniform2fv(this.addr,e)}function y0(i,t){let e=qs(t,this.size,3);i.uniform3fv(this.addr,e)}function v0(i,t){let e=qs(t,this.size,4);i.uniform4fv(this.addr,e)}function M0(i,t){let e=qs(t,this.size,4);i.uniformMatrix2fv(this.addr,!1,e)}function S0(i,t){let e=qs(t,this.size,9);i.uniformMatrix3fv(this.addr,!1,e)}function b0(i,t){let e=qs(t,this.size,16);i.uniformMatrix4fv(this.addr,!1,e)}function w0(i,t){i.uniform1iv(this.addr,t)}function E0(i,t){i.uniform2iv(this.addr,t)}function T0(i,t){i.uniform3iv(this.addr,t)}function A0(i,t){i.uniform4iv(this.addr,t)}function C0(i,t){i.uniform1uiv(this.addr,t)}function R0(i,t){i.uniform2uiv(this.addr,t)}function P0(i,t){i.uniform3uiv(this.addr,t)}function I0(i,t){i.uniform4uiv(this.addr,t)}function L0(i,t,e){let n=this.cache,s=t.length,r=il(e,s);Ce(n,r)||(i.uniform1iv(this.addr,r),Re(n,r));let o;this.type===i.SAMPLER_2D_SHADOW?o=Lc:o=rd;for(let a=0;a!==s;++a)e.setTexture2D(t[a]||o,r[a])}function D0(i,t,e){let n=this.cache,s=t.length,r=il(e,s);Ce(n,r)||(i.uniform1iv(this.addr,r),Re(n,r));for(let o=0;o!==s;++o)e.setTexture3D(t[o]||ad,r[o])}function N0(i,t,e){let n=this.cache,s=t.length,r=il(e,s);Ce(n,r)||(i.uniform1iv(this.addr,r),Re(n,r));for(let o=0;o!==s;++o)e.setTextureCube(t[o]||ld,r[o])}function U0(i,t,e){let n=this.cache,s=t.length,r=il(e,s);Ce(n,r)||(i.uniform1iv(this.addr,r),Re(n,r));for(let o=0;o!==s;++o)e.setTexture2DArray(t[o]||od,r[o])}function F0(i){switch(i){case 5126:return _0;case 35664:return x0;case 35665:return y0;case 35666:return v0;case 35674:return M0;case 35675:return S0;case 35676:return b0;case 5124:case 35670:return w0;case 35667:case 35671:return E0;case 35668:case 35672:return T0;case 35669:case 35673:return A0;case 5125:return C0;case 36294:return R0;case 36295:return P0;case 36296:return I0;case 35678:case 36198:case 36298:case 36306:case 35682:return L0;case 35679:case 36299:case 36307:return D0;case 35680:case 36300:case 36308:case 36293:return N0;case 36289:case 36303:case 36311:case 36292:return U0}}var Dc=class{constructor(t,e,n){this.id=t,this.addr=n,this.cache=[],this.type=e.type,this.setValue=g0(e.type)}},Nc=class{constructor(t,e,n){this.id=t,this.addr=n,this.cache=[],this.type=e.type,this.size=e.size,this.setValue=F0(e.type)}},Uc=class{constructor(t){this.id=t,this.seq=[],this.map={}}setValue(t,e,n){let s=this.seq;for(let r=0,o=s.length;r!==o;++r){let a=s[r];a.setValue(t,e[a.id],n)}}},Pc=/(\w+)(\])?(\[|\.)?/g;function Xu(i,t){i.seq.push(t),i.map[t.id]=t}function O0(i,t,e){let n=i.name,s=n.length;for(Pc.lastIndex=0;;){let r=Pc.exec(n),o=Pc.lastIndex,a=r[1],c=r[2]==="]",l=r[3];if(c&&(a=a|0),l===void 0||l==="["&&o+2===s){Xu(e,l===void 0?new Dc(a,i,t):new Nc(a,i,t));break}else{let f=e.map[a];f===void 0&&(f=new Uc(a),Xu(e,f)),e=f}}}var Ys=class{constructor(t,e){this.seq=[],this.map={};let n=t.getProgramParameter(e,t.ACTIVE_UNIFORMS);for(let o=0;o<n;++o){let a=t.getActiveUniform(e,o),c=t.getUniformLocation(e,a.name);O0(a,c,this)}let s=[],r=[];for(let o of this.seq)o.type===t.SAMPLER_2D_SHADOW||o.type===t.SAMPLER_CUBE_SHADOW||o.type===t.SAMPLER_2D_ARRAY_SHADOW?s.push(o):r.push(o);s.length>0&&(this.seq=s.concat(r))}setValue(t,e,n,s){let r=this.map[e];r!==void 0&&r.setValue(t,n,s)}setOptional(t,e,n){let s=e[n];s!==void 0&&this.setValue(t,n,s)}static upload(t,e,n,s){for(let r=0,o=e.length;r!==o;++r){let a=e[r],c=n[a.id];c.needsUpdate!==!1&&a.setValue(t,c.value,s)}}static seqWithValue(t,e){let n=[];for(let s=0,r=t.length;s!==r;++s){let o=t[s];o.id in e&&n.push(o)}return n}};function Yu(i,t,e){let n=i.createShader(t);return i.shaderSource(n,e),i.compileShader(n),n}var B0=37297,z0=0;function k0(i,t){let e=i.split(`+`),n=[],s=Math.max(t-6,0),r=Math.min(t+6,e.length);for(let o=s;o<r;o++){let a=o+1;n.push(`${a===t?">":" "} ${a}: ${e[o]}`)}return n.join(`+`)}var qu=new Ut;function V0(i){Xt._getMatrix(qu,Xt.workingColorSpace,i);let t=`mat3( ${qu.elements.map(e=>e.toFixed(4))} )`;switch(Xt.getTransfer(i)){case hr:return[t,"LinearTransferOETF"];case Qt:return[t,"sRGBTransferOETF"];default:return It("WebGLProgram: Unsupported color space: ",i),[t,"LinearTransferOETF"]}}function Zu(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+`++`+k0(i.getShaderSource(t),a)}else return r}function H0(i,t){let e=V0(t);return[`vec4 ${i}( vec4 value ) {`,` return ${e[1]}( vec4( value.rgb * ${e[0]}, value.a ) );`,"}"].join(`+`)}var G0={[sc]:"Linear",[rc]:"Reinhard",[oc]:"Cineon",[Pr]:"ACESFilmic",[lc]:"AgX",[cc]:"Neutral",[ac]:"Custom"};function W0(i,t){let e=G0[t];return e===void 0?(It("WebGLProgram: Unsupported toneMapping:",t),"vec3 "+i+"( vec3 color ) { return LinearToneMapping( color ); }"):"vec3 "+i+"( vec3 color ) { return "+e+"ToneMapping( color ); }"}var Ka=new P;function X0(){Xt.getLuminanceCoefficients(Ka);let i=Ka.x.toFixed(4),t=Ka.y.toFixed(4),e=Ka.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${i}, ${t}, ${e} );`," return dot( weights, rgb );","}"].join(`+`)}function Y0(i){return[i.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",i.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(Vr).join(`+`)}function q0(i){let t=[];for(let e in i){let n=i[e];n!==!1&&t.push("#define "+e+" "+n)}return t.join(`+`)}function Z0(i,t){let e={},n=i.getProgramParameter(t,i.ACTIVE_ATTRIBUTES);for(let s=0;s<n;s++){let r=i.getActiveAttrib(t,s),o=r.name,a=1;r.type===i.FLOAT_MAT2&&(a=2),r.type===i.FLOAT_MAT3&&(a=3),r.type===i.FLOAT_MAT4&&(a=4),e[o]={type:r.type,location:i.getAttribLocation(t,o),locationSize:a}}return e}function Vr(i){return i!==""}function ju(i,t){let e=t.numSpotLightShadows+t.numSpotLightMaps-t.numSpotLightShadowsWithMaps;return i.replace(/NUM_SUN_LIGHTS/g,t.numSunLights).replace(/NUM_DIR_LIGHTS/g,t.numDirLights).replace(/NUM_SPOT_LIGHTS/g,t.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,t.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,e).replace(/NUM_RECT_AREA_LIGHTS/g,t.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,t.numPointLights).replace(/NUM_HEMI_LIGHTS/g,t.numHemiLights).replace(/NUM_SUN_LIGHT_SHADOWS/g,t.numSunLightShadows).replace(/NUM_DIR_LIGHT_SHADOWS/g,t.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,t.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,t.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,t.numPointLightShadows)}function Ju(i,t){return i.replace(/NUM_CLIPPING_PLANES/g,t.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,t.numClippingPlanes-t.numClipIntersection)}var j0=/^[ \t]*#include +<([\w\d./]+)>/gm;function Fc(i){return i.replace(j0,$0)}var J0=new Map;function $0(i,t){let e=zt[t];if(e===void 0){let n=J0.get(t);if(n!==void 0)e=zt[n],It('WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',t,n);else throw new Error("THREE.WebGLProgram: Can not resolve #include <"+t+">")}return Fc(e)}var K0=/#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 $u(i){return i.replace(K0,Q0)}function Q0(i,t,e,n){let s="";for(let r=parseInt(t);r<parseInt(e);r++)s+=n.replace(/\[\s*i\s*\]/g,"[ "+r+" ]").replace(/UNROLLED_LOOP_INDEX/g,r);return s}function Ku(i){let t=`precision ${i.precision} float;+ precision ${i.precision} int;+ precision ${i.precision} sampler2D;+ precision ${i.precision} samplerCube;+ precision ${i.precision} sampler3D;+ precision ${i.precision} sampler2DArray;+ precision ${i.precision} sampler2DShadow;+ precision ${i.precision} samplerCubeShadow;+ precision ${i.precision} sampler2DArrayShadow;+ precision ${i.precision} isampler2D;+ precision ${i.precision} isampler3D;+ precision ${i.precision} isamplerCube;+ precision ${i.precision} isampler2DArray;+ precision ${i.precision} usampler2D;+ precision ${i.precision} usampler3D;+ precision ${i.precision} usamplerCube;+ precision ${i.precision} usampler2DArray;+ `;return i.precision==="highp"?t+=`+#define HIGH_PRECISION`:i.precision==="mediump"?t+=`+#define MEDIUM_PRECISION`:i.precision==="lowp"&&(t+=`+#define LOW_PRECISION`),t}var t_={[Rr]:"SHADOWMAP_TYPE_PCF",[zs]:"SHADOWMAP_TYPE_VSM"};function e_(i){return t_[i.shadowMapType]||"SHADOWMAP_TYPE_BASIC"}var n_={[Ai]:"ENVMAP_TYPE_CUBE",[qi]:"ENVMAP_TYPE_CUBE",[Ir]:"ENVMAP_TYPE_CUBE_UV"};function i_(i){return i.envMap===!1?"ENVMAP_TYPE_CUBE":n_[i.envMapMode]||"ENVMAP_TYPE_CUBE"}var s_={[qi]:"ENVMAP_MODE_REFRACTION"};function r_(i){return i.envMap===!1?"ENVMAP_MODE_REFLECTION":s_[i.envMapMode]||"ENVMAP_MODE_REFLECTION"}var o_={[ic]:"ENVMAP_BLENDING_MULTIPLY",[mu]:"ENVMAP_BLENDING_MIX",[gu]:"ENVMAP_BLENDING_ADD"};function a_(i){return i.envMap===!1?"ENVMAP_BLENDING_NONE":o_[i.combine]||"ENVMAP_BLENDING_NONE"}function l_(i){let t=i.envMapCubeUVHeight;if(t===null)return null;let e=Math.log2(t)-2,n=1/t;return{texelWidth:1/(3*Math.max(Math.pow(2,e),112)),texelHeight:n,maxMip:e}}function c_(i,t,e,n){let s=i.getContext(),r=e.defines,o=e.vertexShader,a=e.fragmentShader,c=e_(e),l=i_(e),u=r_(e),f=a_(e),h=l_(e),p=Y0(e),g=q0(r),v=s.createProgram(),m,d,S=e.glslVersion?"#version "+e.glslVersion+`+`:"";e.isRawShaderMaterial?(m=["#define SHADER_TYPE "+e.shaderType,"#define SHADER_NAME "+e.shaderName,g].filter(Vr).join(`+`),m.length>0&&(m+=`+`),d=["#define SHADER_TYPE "+e.shaderType,"#define SHADER_NAME "+e.shaderName,g].filter(Vr).join(`+`),d.length>0&&(d+=`+`)):(m=[Ku(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 "+u:"",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.vertexNormals?"#define HAS_NORMAL":"",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 "+c:"",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(Vr).join(`+`),d=[Ku(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 "+l:"",e.envMap?"#define "+u:"",e.envMap?"#define "+f:"",h?"#define CUBEUV_TEXEL_WIDTH "+h.texelWidth:"",h?"#define CUBEUV_TEXEL_HEIGHT "+h.texelHeight:"",h?"#define CUBEUV_MAX_MIP "+h.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.packedNormalMap?"#define USE_PACKED_NORMALMAP":"",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.retroreflection?"#define USE_RETROREFLECTION":"",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?"#define USE_COLOR":"",e.vertexAlphas||e.batchingColor?"#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 "+c:"",e.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",e.numLightProbes>0?"#define USE_LIGHT_PROBES":"",e.numLightProbeGrids>0?"#define USE_LIGHT_PROBES_GRID":"",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!==Rn?"#define TONE_MAPPING":"",e.toneMapping!==Rn?zt.tonemapping_pars_fragment:"",e.toneMapping!==Rn?W0("toneMapping",e.toneMapping):"",e.dithering?"#define DITHERING":"",e.opaque?"#define OPAQUE":"",zt.colorspace_pars_fragment,H0("linearToOutputTexel",e.outputColorSpace),X0(),e.useDepthPacking?"#define DEPTH_PACKING "+e.depthPacking:"",`+`].filter(Vr).join(`+`)),o=Fc(o),o=ju(o,e),o=Ju(o,e),a=Fc(a),a=ju(a,e),a=Ju(a,e),o=$u(o),a=$u(a),e.isRawShaderMaterial!==!0&&(S=`#version 300 es+`,m=[p,"#define attribute in","#define varying out","#define texture2D texture"].join(`+`)+`+`+m,d=["#define varying in",e.glslVersion===xc?"":"layout(location = 0) out highp vec4 pc_fragColor;",e.glslVersion===xc?"":"#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(`+`)+`+`+d);let T=S+m+o,y=S+d+a,b=Yu(s,s.VERTEX_SHADER,T),w=Yu(s,s.FRAGMENT_SHADER,y);s.attachShader(v,b),s.attachShader(v,w),e.index0AttributeName!==void 0?s.bindAttribLocation(v,0,e.index0AttributeName):e.hasPositionAttribute===!0&&s.bindAttribLocation(v,0,"position"),s.linkProgram(v);function C(L){if(i.debug.checkShaderErrors){let F=s.getProgramInfoLog(v)||"",z=s.getShaderInfoLog(b)||"",I=s.getShaderInfoLog(w)||"",O=F.trim(),G=z.trim(),X=I.trim(),et=!0,Y=!0;if(s.getProgramParameter(v,s.LINK_STATUS)===!1)if(et=!1,typeof i.debug.onShaderError=="function")i.debug.onShaderError(s,v,b,w);else{let K=Zu(s,b,"vertex"),nt=Zu(s,w,"fragment");Dt("WebGLProgram: Shader Error "+s.getError()+" - VALIDATE_STATUS "+s.getProgramParameter(v,s.VALIDATE_STATUS)+`++Material Name: `+L.name+`+Material Type: `+L.type+`++Program Info Log: `+O+`+`+K+`+`+nt)}else O!==""?It("WebGLProgram: Program Info Log:",O):(G===""||X==="")&&(Y=!1);Y&&(L.diagnostics={runnable:et,programLog:O,vertexShader:{log:G,prefix:m},fragmentShader:{log:X,prefix:d}})}s.deleteShader(b),s.deleteShader(w),_=new Ys(s,v),E=Z0(s,v)}let _;this.getUniforms=function(){return _===void 0&&C(this),_};let E;this.getAttributes=function(){return E===void 0&&C(this),E};let R=e.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return R===!1&&(R=s.getProgramParameter(v,B0)),R},this.destroy=function(){n.releaseStatesOfProgram(this),s.deleteProgram(v),this.program=void 0},this.type=e.shaderType,this.name=e.shaderName,this.id=z0++,this.cacheKey=t,this.usedTimes=1,this.program=v,this.vertexShader=b,this.fragmentShader=w,this}var h_=0,Oc=class{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(t,e,n){let s=this._getShaderCacheForMaterial(t);return s.has(e)===!1&&(s.add(e),e.usedTimes++),s.has(n)===!1&&(s.add(n),n.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}getVertexShaderStage(t){return this._getShaderStage(t.vertexShader)}getFragmentShaderStage(t){return this._getShaderStage(t.fragmentShader)}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 Bc(t),e.set(t,n)),n}},Bc=class{constructor(t){this.id=h_++,this.code=t,this.usedTimes=0}};function u_(i){return i===Pi||i===Or||i===Br}function d_(i,t,e,n,s,r){let o=new Ls,a=new Oc,c=new Set,l=[],u=new Map,f=n.logarithmicDepthBuffer,h=n.precision,p={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distance",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 g(_){return c.add(_),_===0?"uv":`uv${_}`}function v(_,E,R,L,F,z){let I=L.fog,O=F.geometry,G=_.isMeshStandardMaterial||_.isMeshLambertMaterial||_.isMeshPhongMaterial?L.environment:null,X=_.isMeshStandardMaterial||_.isMeshLambertMaterial&&!_.envMap||_.isMeshPhongMaterial&&!_.envMap,et=t.get(_.envMap||G,X),Y=et&&et.mapping===Ir?et.image.height:null,K=p[_.type];_.precision!==null&&(h=n.getMaxPrecision(_.precision),h!==_.precision&&It("WebGLProgram.getParameters:",_.precision,"not supported, using",h,"instead."));let nt=O.morphAttributes.position||O.morphAttributes.normal||O.morphAttributes.color,Et=nt!==void 0?nt.length:0,Tt=0;O.morphAttributes.position!==void 0&&(Tt=1),O.morphAttributes.normal!==void 0&&(Tt=2),O.morphAttributes.color!==void 0&&(Tt=3);let te,qt,Jt,Z;if(K){let le=Wn[K];te=le.vertexShader,qt=le.fragmentShader}else{te=_.vertexShader,qt=_.fragmentShader;let le=a.getVertexShaderStage(_),$t=a.getFragmentShaderStage(_);a.update(_,le,$t),Jt=le.id,Z=$t.id}let Q=i.getRenderTarget(),vt=i.state.buffers.depth.getReversed(),Ft=F.isInstancedMesh===!0,xt=F.isBatchedMesh===!0,kt=!!_.map,Ae=!!_.matcap,Ht=!!et,jt=!!_.aoMap,ae=!!_.lightMap,Wt=!!_.bumpMap&&_.wireframe===!1,fe=!!_.normalMap,Ie=!!_.displacementMap,Je=!!_.emissiveMap,xe=!!_.metalnessMap,we=!!_.roughnessMap,U=_.anisotropy>0,Be=_.clearcoat>0,ee=_.dispersion>0,A=_.retroreflectivity>0,x=_.iridescence>0,B=_.sheen>0,H=_.transmission>0,q=U&&!!_.anisotropyMap,rt=Be&&!!_.clearcoatMap,ot=Be&&!!_.clearcoatNormalMap,j=Be&&!!_.clearcoatRoughnessMap,$=x&&!!_.iridescenceMap,at=x&&!!_.iridescenceThicknessMap,At=B&&!!_.sheenColorMap,dt=B&&!!_.sheenRoughnessMap,lt=!!_.specularMap,Ct=!!_.specularColorMap,Lt=!!_.specularIntensityMap,Ot=H&&!!_.transmissionMap,N=H&&!!_.thicknessMap,ct=!!_.gradientMap,J=!!_.alphaMap,ht=_.alphaTest>0,gt=!!_.alphaHash,it=!!_.extensions,Rt=Rn;_.toneMapped&&(Q===null||Q.isXRRenderTarget===!0)&&(Rt=i.toneMapping);let bt={shaderID:K,shaderType:_.type,shaderName:_.name,vertexShader:te,fragmentShader:qt,defines:_.defines,customVertexShaderID:Jt,customFragmentShaderID:Z,isRawShaderMaterial:_.isRawShaderMaterial===!0,glslVersion:_.glslVersion,precision:h,batching:xt,batchingColor:xt&&F._colorsTexture!==null,instancing:Ft,instancingColor:Ft&&F.instanceColor!==null,instancingMorph:Ft&&F.morphTexture!==null,outputColorSpace:Q===null?i.outputColorSpace:Q.isXRRenderTarget===!0?Q.texture.colorSpace:Xt.workingColorSpace,alphaToCoverage:!!_.alphaToCoverage,map:kt,matcap:Ae,envMap:Ht,envMapMode:Ht&&et.mapping,envMapCubeUVHeight:Y,aoMap:jt,lightMap:ae,bumpMap:Wt,normalMap:fe,displacementMap:Ie,emissiveMap:Je,normalMapObjectSpace:fe&&_.normalMapType===yu,normalMapTangentSpace:fe&&_.normalMapType===Za,packedNormalMap:fe&&_.normalMapType===Za&&u_(_.normalMap.format),metalnessMap:xe,roughnessMap:we,anisotropy:U,anisotropyMap:q,clearcoat:Be,clearcoatMap:rt,clearcoatNormalMap:ot,clearcoatRoughnessMap:j,dispersion:ee,retroreflection:A,iridescence:x,iridescenceMap:$,iridescenceThicknessMap:at,sheen:B,sheenColorMap:At,sheenRoughnessMap:dt,specularMap:lt,specularColorMap:Ct,specularIntensityMap:Lt,transmission:H,transmissionMap:Ot,thicknessMap:N,gradientMap:ct,opaque:_.transparent===!1&&_.blending===ks&&_.alphaToCoverage===!1,alphaMap:J,alphaTest:ht,alphaHash:gt,combine:_.combine,mapUv:kt&&g(_.map.channel),aoMapUv:jt&&g(_.aoMap.channel),lightMapUv:ae&&g(_.lightMap.channel),bumpMapUv:Wt&&g(_.bumpMap.channel),normalMapUv:fe&&g(_.normalMap.channel),displacementMapUv:Ie&&g(_.displacementMap.channel),emissiveMapUv:Je&&g(_.emissiveMap.channel),metalnessMapUv:xe&&g(_.metalnessMap.channel),roughnessMapUv:we&&g(_.roughnessMap.channel),anisotropyMapUv:q&&g(_.anisotropyMap.channel),clearcoatMapUv:rt&&g(_.clearcoatMap.channel),clearcoatNormalMapUv:ot&&g(_.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:j&&g(_.clearcoatRoughnessMap.channel),iridescenceMapUv:$&&g(_.iridescenceMap.channel),iridescenceThicknessMapUv:at&&g(_.iridescenceThicknessMap.channel),sheenColorMapUv:At&&g(_.sheenColorMap.channel),sheenRoughnessMapUv:dt&&g(_.sheenRoughnessMap.channel),specularMapUv:lt&&g(_.specularMap.channel),specularColorMapUv:Ct&&g(_.specularColorMap.channel),specularIntensityMapUv:Lt&&g(_.specularIntensityMap.channel),transmissionMapUv:Ot&&g(_.transmissionMap.channel),thicknessMapUv:N&&g(_.thicknessMap.channel),alphaMapUv:J&&g(_.alphaMap.channel),vertexTangents:!!O.attributes.tangent&&(fe||U),vertexNormals:!!O.attributes.normal,vertexColors:_.vertexColors,vertexAlphas:_.vertexColors===!0&&!!O.attributes.color&&O.attributes.color.itemSize===4,pointsUvs:F.isPoints===!0&&!!O.attributes.uv&&(kt||J),fog:!!I,useFog:_.fog===!0,fogExp2:!!I&&I.isFogExp2,flatShading:_.wireframe===!1&&(_.flatShading===!0||O.attributes.normal===void 0&&fe===!1&&(_.isMeshLambertMaterial||_.isMeshPhongMaterial||_.isMeshStandardMaterial||_.isMeshPhysicalMaterial)),sizeAttenuation:_.sizeAttenuation===!0,logarithmicDepthBuffer:f,reversedDepthBuffer:vt,skinning:F.isSkinnedMesh===!0,hasPositionAttribute:O.attributes.position!==void 0,morphTargets:O.morphAttributes.position!==void 0,morphNormals:O.morphAttributes.normal!==void 0,morphColors:O.morphAttributes.color!==void 0,morphTargetsCount:Et,morphTextureStride:Tt,numSunLights:E.sun.length,numDirLights:E.directional.length,numPointLights:E.point.length,numSpotLights:E.spot.length,numSpotLightMaps:E.spotLightMap.length,numRectAreaLights:E.rectArea.length,numHemiLights:E.hemi.length,numSunLightShadows:E.sunShadowMap.length,numDirLightShadows:E.directionalShadowMap.length,numPointLightShadows:E.pointShadowMap.length,numSpotLightShadows:E.spotShadowMap.length,numSpotLightShadowsWithMaps:E.numSpotLightShadowsWithMaps,numLightProbes:E.numLightProbes,numLightProbeGrids:z.length,numClippingPlanes:r.numPlanes,numClipIntersection:r.numIntersection,dithering:_.dithering,shadowMapEnabled:i.shadowMap.enabled&&R.length>0,shadowMapType:i.shadowMap.type,toneMapping:Rt,decodeVideoTexture:kt&&_.map.isVideoTexture===!0&&Xt.getTransfer(_.map.colorSpace)===Qt,decodeVideoTextureEmissive:Je&&_.emissiveMap.isVideoTexture===!0&&Xt.getTransfer(_.emissiveMap.colorSpace)===Qt,premultipliedAlpha:_.premultipliedAlpha,doubleSided:_.side===_n,flipSided:_.side===Ze,useDepthPacking:_.depthPacking>=0,depthPacking:_.depthPacking||0,index0AttributeName:_.index0AttributeName,extensionClipCullDistance:it&&_.extensions.clipCullDistance===!0&&e.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(it&&_.extensions.multiDraw===!0||xt)&&e.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:e.has("KHR_parallel_shader_compile"),customProgramCacheKey:_.customProgramCacheKey()};return bt.vertexUv1s=c.has(1),bt.vertexUv2s=c.has(2),bt.vertexUv3s=c.has(3),c.clear(),bt}function m(_){let E=[];if(_.shaderID?E.push(_.shaderID):(E.push(_.customVertexShaderID),E.push(_.customFragmentShaderID)),_.defines!==void 0)for(let R in _.defines)E.push(R),E.push(_.defines[R]);return _.isRawShaderMaterial===!1&&(d(E,_),S(E,_),E.push(i.outputColorSpace)),E.push(_.customProgramCacheKey),E.join()}function d(_,E){_.push(E.precision),_.push(E.outputColorSpace),_.push(E.envMapMode),_.push(E.envMapCubeUVHeight),_.push(E.mapUv),_.push(E.alphaMapUv),_.push(E.lightMapUv),_.push(E.aoMapUv),_.push(E.bumpMapUv),_.push(E.normalMapUv),_.push(E.displacementMapUv),_.push(E.emissiveMapUv),_.push(E.metalnessMapUv),_.push(E.roughnessMapUv),_.push(E.anisotropyMapUv),_.push(E.clearcoatMapUv),_.push(E.clearcoatNormalMapUv),_.push(E.clearcoatRoughnessMapUv),_.push(E.iridescenceMapUv),_.push(E.iridescenceThicknessMapUv),_.push(E.sheenColorMapUv),_.push(E.sheenRoughnessMapUv),_.push(E.specularMapUv),_.push(E.specularColorMapUv),_.push(E.specularIntensityMapUv),_.push(E.transmissionMapUv),_.push(E.thicknessMapUv),_.push(E.combine),_.push(E.fogExp2),_.push(E.sizeAttenuation),_.push(E.morphTargetsCount),_.push(E.morphAttributeCount),_.push(E.numSunLights),_.push(E.numDirLights),_.push(E.numPointLights),_.push(E.numSpotLights),_.push(E.numSpotLightMaps),_.push(E.numHemiLights),_.push(E.numRectAreaLights),_.push(E.numSunLightShadows),_.push(E.numDirLightShadows),_.push(E.numPointLightShadows),_.push(E.numSpotLightShadows),_.push(E.numSpotLightShadowsWithMaps),_.push(E.numLightProbes),_.push(E.shadowMapType),_.push(E.toneMapping),_.push(E.numClippingPlanes),_.push(E.numClipIntersection),_.push(E.depthPacking)}function S(_,E){o.disableAll(),E.instancing&&o.enable(0),E.instancingColor&&o.enable(1),E.instancingMorph&&o.enable(2),E.matcap&&o.enable(3),E.envMap&&o.enable(4),E.normalMapObjectSpace&&o.enable(5),E.normalMapTangentSpace&&o.enable(6),E.clearcoat&&o.enable(7),E.iridescence&&o.enable(8),E.alphaTest&&o.enable(9),E.vertexColors&&o.enable(10),E.vertexAlphas&&o.enable(11),E.vertexUv1s&&o.enable(12),E.vertexUv2s&&o.enable(13),E.vertexUv3s&&o.enable(14),E.vertexTangents&&o.enable(15),E.anisotropy&&o.enable(16),E.alphaHash&&o.enable(17),E.batching&&o.enable(18),E.dispersion&&o.enable(19),E.retroreflection&&o.enable(24),E.batchingColor&&o.enable(20),E.gradientMap&&o.enable(21),E.packedNormalMap&&o.enable(22),E.vertexNormals&&o.enable(23),_.push(o.mask),o.disableAll(),E.fog&&o.enable(0),E.useFog&&o.enable(1),E.flatShading&&o.enable(2),E.logarithmicDepthBuffer&&o.enable(3),E.reversedDepthBuffer&&o.enable(4),E.skinning&&o.enable(5),E.morphTargets&&o.enable(6),E.morphNormals&&o.enable(7),E.morphColors&&o.enable(8),E.premultipliedAlpha&&o.enable(9),E.shadowMapEnabled&&o.enable(10),E.doubleSided&&o.enable(11),E.flipSided&&o.enable(12),E.useDepthPacking&&o.enable(13),E.dithering&&o.enable(14),E.transmission&&o.enable(15),E.sheen&&o.enable(16),E.opaque&&o.enable(17),E.pointsUvs&&o.enable(18),E.decodeVideoTexture&&o.enable(19),E.decodeVideoTextureEmissive&&o.enable(20),E.alphaToCoverage&&o.enable(21),E.numLightProbeGrids>0&&o.enable(22),E.hasPositionAttribute&&o.enable(23),_.push(o.mask)}function T(_){let E=p[_.type],R;if(E){let L=Wn[E];R=Du.clone(L.uniforms)}else R=_.uniforms;return R}function y(_,E){let R=u.get(E);return R!==void 0?++R.usedTimes:(R=new c_(i,E,_,s),l.push(R),u.set(E,R)),R}function b(_){if(--_.usedTimes===0){let E=l.indexOf(_);l[E]=l[l.length-1],l.pop(),u.delete(_.cacheKey),_.destroy()}}function w(_){a.remove(_)}function C(){a.dispose()}return{getParameters:v,getProgramCacheKey:m,getUniforms:T,acquireProgram:y,releaseProgram:b,releaseShaderCache:w,programs:l,dispose:C}}function f_(){let i=new WeakMap;function t(o){return i.has(o)}function e(o){let a=i.get(o);return a===void 0&&(a={},i.set(o,a)),a}function n(o){i.delete(o)}function s(o,a,c){i.get(o)[a]=c}function r(){i=new WeakMap}return{has:t,get:e,remove:n,update:s,dispose:r}}function p_(i,t){return i.groupOrder!==t.groupOrder?i.groupOrder-t.groupOrder:i.renderOrder!==t.renderOrder?i.renderOrder-t.renderOrder:i.material.id!==t.material.id?i.material.id-t.material.id:i.materialVariant!==t.materialVariant?i.materialVariant-t.materialVariant:i.z!==t.z?i.z-t.z:i.id-t.id}function Qu(i,t){return i.groupOrder!==t.groupOrder?i.groupOrder-t.groupOrder:i.renderOrder!==t.renderOrder?i.renderOrder-t.renderOrder:i.z!==t.z?t.z-i.z:i.id-t.id}function td(){let i=[],t=0,e=[],n=[],s=[];function r(){t=0,e.length=0,n.length=0,s.length=0}function o(h){let p=0;return h.isInstancedMesh&&(p+=2),h.isSkinnedMesh&&(p+=1),p}function a(h,p,g,v,m,d){let S=i[t];return S===void 0?(S={id:h.id,object:h,geometry:p,material:g,materialVariant:o(h),groupOrder:v,renderOrder:h.renderOrder,z:m,group:d},i[t]=S):(S.id=h.id,S.object=h,S.geometry=p,S.material=g,S.materialVariant=o(h),S.groupOrder=v,S.renderOrder=h.renderOrder,S.z=m,S.group=d),t++,S}function c(h,p,g,v,m,d,S){S.reversedDepth===!0&&(m=-m);let T=a(h,p,g,v,m,d);g.transmission>0?n.push(T):g.transparent===!0?s.push(T):e.push(T)}function l(h,p,g,v,m,d){let S=a(h,p,g,v,m,d);g.transmission>0?n.unshift(S):g.transparent===!0?s.unshift(S):e.unshift(S)}function u(h,p){e.length>1&&e.sort(h||p_),n.length>1&&n.sort(p||Qu),s.length>1&&s.sort(p||Qu)}function f(){for(let h=t,p=i.length;h<p;h++){let g=i[h];if(g.id===null)break;g.id=null,g.object=null,g.geometry=null,g.material=null,g.group=null}}return{opaque:e,transmissive:n,transparent:s,init:r,push:c,unshift:l,finish:f,sort:u}}function m_(){let i=new WeakMap;function t(n,s){let r=i.get(n),o;return r===void 0?(o=new td,i.set(n,[o])):s>=r.length?(o=new td,r.push(o)):o=r[s],o}function e(){i=new WeakMap}return{get:t,dispose:e}}function g_(){let i={};return{get:function(t){if(i[t.id]!==void 0)return i[t.id];let e;switch(t.type){case"SunLight":case"DirectionalLight":e={direction:new P,color:new Nt};break;case"SpotLight":e={position:new P,direction:new P,color:new Nt,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":e={position:new P,color:new Nt,distance:0,decay:0};break;case"HemisphereLight":e={direction:new P,skyColor:new Nt,groundColor:new Nt};break;case"RectAreaLight":e={color:new Nt,position:new P,halfWidth:new P,halfHeight:new P};break}return i[t.id]=e,e}}}function __(){let i={};return{get:function(t){if(i[t.id]!==void 0)return i[t.id];let e;switch(t.type){case"SunLight":case"DirectionalLight":e={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Pt};break;case"SpotLight":e={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Pt};break;case"PointLight":e={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Pt,shadowCameraNear:1,shadowCameraFar:1e3};break}return i[t.id]=e,e}}}var x_=0;function y_(i,t){return(t.castShadow?2:0)-(i.castShadow?2:0)+(t.map?1:0)-(i.map?1:0)}function v_(i){let t=new g_,e=__(),n={version:0,hash:{sunLength:-1,directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numSunShadows:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],sun:[],sunShadow:[],sunShadowMap:[],sunShadowMatrix:[],sunShadowCascade:[],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 l=0;l<9;l++)n.probe.push(new P);let s=new P,r=new se,o=new se;function a(l){let u=0,f=0,h=0;for(let F=0;F<9;F++)n.probe[F].set(0,0,0);let p=0,g=0,v=0,m=0,d=0,S=0,T=0,y=0,b=0,w=0,C=0,_=0,E=0,R=0;l.sort(y_);for(let F=0,z=l.length;F<z;F++){let I=l[F],O=I.color,G=I.intensity,X=I.distance,et=null;if(I.shadow&&I.shadow.map&&(I.shadow.map.texture.format===Pi?et=I.shadow.map.texture:et=I.shadow.map.depthTexture||I.shadow.map.texture),I.isAmbientLight)u+=O.r*G,f+=O.g*G,h+=O.b*G;else if(I.isLightProbe){for(let Y=0;Y<9;Y++)n.probe[Y].addScaledVector(I.sh.coefficients[Y],G);R++}else if(I.isSunLight){let Y=t.get(I);if(Y.color.copy(I.color).multiplyScalar(I.intensity),I.castShadow){let K=I.shadow,nt=e.get(I);nt.shadowIntensity=K.intensity,nt.shadowBias=K.bias,nt.shadowNormalBias=K.normalBias,nt.shadowRadius=K.radius,nt.shadowMapSize.copy(K.mapSize).multiply(K.getFrameExtents()),n.sunShadow[g]=nt,n.sunShadowMap[g]=et;let Et=K.getViewportCount();for(let Tt=0;Tt<Et;Tt++)n.sunShadowMatrix[v+Tt]=K.getMatrix(Tt),n.sunShadowCascade[v+Tt]=K._cascadeData[Tt];v+=Et,g++}n.sun[p]=Y,p++}else if(I.isDirectionalLight){let Y=t.get(I);if(Y.color.copy(I.color).multiplyScalar(I.intensity),I.castShadow){let K=I.shadow,nt=e.get(I);nt.shadowIntensity=K.intensity,nt.shadowBias=K.bias,nt.shadowNormalBias=K.normalBias,nt.shadowRadius=K.radius,nt.shadowMapSize=K.mapSize,n.directionalShadow[m]=nt,n.directionalShadowMap[m]=et,n.directionalShadowMatrix[m]=I.shadow.matrix,b++}n.directional[m]=Y,m++}else if(I.isSpotLight){let Y=t.get(I);Y.position.setFromMatrixPosition(I.matrixWorld),Y.color.copy(O).multiplyScalar(G),Y.distance=X,Y.coneCos=Math.cos(I.angle),Y.penumbraCos=Math.cos(I.angle*(1-I.penumbra)),Y.decay=I.decay,n.spot[S]=Y;let K=I.shadow;if(I.map&&(n.spotLightMap[_]=I.map,_++,K.updateMatrices(I),I.castShadow&&E++),n.spotLightMatrix[S]=K.matrix,I.castShadow){let nt=e.get(I);nt.shadowIntensity=K.intensity,nt.shadowBias=K.bias,nt.shadowNormalBias=K.normalBias,nt.shadowRadius=K.radius,nt.shadowMapSize=K.mapSize,n.spotShadow[S]=nt,n.spotShadowMap[S]=et,C++}S++}else if(I.isRectAreaLight){let Y=t.get(I);Y.color.copy(O).multiplyScalar(G),Y.halfWidth.set(I.width*.5,0,0),Y.halfHeight.set(0,I.height*.5,0),n.rectArea[T]=Y,T++}else if(I.isPointLight){let Y=t.get(I);if(Y.color.copy(I.color).multiplyScalar(I.intensity),Y.distance=I.distance,Y.decay=I.decay,I.castShadow){let K=I.shadow,nt=e.get(I);nt.shadowIntensity=K.intensity,nt.shadowBias=K.bias,nt.shadowNormalBias=K.normalBias,nt.shadowRadius=K.radius,nt.shadowMapSize=K.mapSize,nt.shadowCameraNear=K.camera.near,nt.shadowCameraFar=K.camera.far,n.pointShadow[d]=nt,n.pointShadowMap[d]=et,n.pointShadowMatrix[d]=I.shadow.matrix,w++}n.point[d]=Y,d++}else if(I.isHemisphereLight){let Y=t.get(I);Y.skyColor.copy(I.color).multiplyScalar(G),Y.groundColor.copy(I.groundColor).multiplyScalar(G),n.hemi[y]=Y,y++}}T>0&&(i.has("OES_texture_float_linear")===!0?(n.rectAreaLTC1=ft.LTC_FLOAT_1,n.rectAreaLTC2=ft.LTC_FLOAT_2):(n.rectAreaLTC1=ft.LTC_HALF_1,n.rectAreaLTC2=ft.LTC_HALF_2)),n.ambient[0]=u,n.ambient[1]=f,n.ambient[2]=h;let L=n.hash;(L.sunLength!==p||L.directionalLength!==m||L.pointLength!==d||L.spotLength!==S||L.rectAreaLength!==T||L.hemiLength!==y||L.numSunShadows!==g||L.numDirectionalShadows!==b||L.numPointShadows!==w||L.numSpotShadows!==C||L.numSpotMaps!==_||L.numLightProbes!==R)&&(n.sun.length=p,n.directional.length=m,n.spot.length=S,n.rectArea.length=T,n.point.length=d,n.hemi.length=y,n.sunShadow.length=g,n.sunShadowMap.length=g,n.sunShadowMatrix.length=v,n.sunShadowCascade.length=v,n.directionalShadow.length=b,n.directionalShadowMap.length=b,n.directionalShadowMatrix.length=b,n.pointShadow.length=w,n.pointShadowMap.length=w,n.pointShadowMatrix.length=w,n.spotShadow.length=C,n.spotShadowMap.length=C,n.spotLightMatrix.length=C+_-E,n.spotLightMap.length=_,n.numSpotLightShadowsWithMaps=E,n.numLightProbes=R,L.sunLength=p,L.directionalLength=m,L.pointLength=d,L.spotLength=S,L.rectAreaLength=T,L.hemiLength=y,L.numSunShadows=g,L.numDirectionalShadows=b,L.numPointShadows=w,L.numSpotShadows=C,L.numSpotMaps=_,L.numLightProbes=R,n.version=x_++)}function c(l,u){let f=0,h=0,p=0,g=0,v=0,m=0,d=u.matrixWorldInverse;for(let S=0,T=l.length;S<T;S++){let y=l[S];if(y.isSunLight){let b=n.sun[f];b.direction.setFromMatrixPosition(y.matrixWorld),b.direction.transformDirection(d),f++}else if(y.isDirectionalLight){let b=n.directional[h];b.direction.setFromMatrixPosition(y.matrixWorld),s.setFromMatrixPosition(y.target.matrixWorld),b.direction.sub(s),b.direction.transformDirection(d),h++}else if(y.isSpotLight){let b=n.spot[g];b.position.setFromMatrixPosition(y.matrixWorld),b.position.applyMatrix4(d),b.direction.setFromMatrixPosition(y.matrixWorld),s.setFromMatrixPosition(y.target.matrixWorld),b.direction.sub(s),b.direction.transformDirection(d),g++}else if(y.isRectAreaLight){let b=n.rectArea[v];b.position.setFromMatrixPosition(y.matrixWorld),b.position.applyMatrix4(d),o.identity(),r.copy(y.matrixWorld),r.premultiply(d),o.extractRotation(r),b.halfWidth.set(y.width*.5,0,0),b.halfHeight.set(0,y.height*.5,0),b.halfWidth.applyMatrix4(o),b.halfHeight.applyMatrix4(o),v++}else if(y.isPointLight){let b=n.point[p];b.position.setFromMatrixPosition(y.matrixWorld),b.position.applyMatrix4(d),p++}else if(y.isHemisphereLight){let b=n.hemi[m];b.direction.setFromMatrixPosition(y.matrixWorld),b.direction.transformDirection(d),m++}}}return{setup:a,setupView:c,state:n}}function ed(i){let t=new v_(i),e=[],n=[],s=[];function r(h){f.camera=h,e.length=0,n.length=0,s.length=0}function o(h){e.push(h)}function a(h){n.push(h)}function c(h){s.push(h)}function l(){t.setup(e)}function u(h){t.setupView(e,h)}let f={lightsArray:e,shadowsArray:n,lightProbeGridArray:s,camera:null,lights:t,transmissionRenderTarget:{},textureUnits:0};return{init:r,state:f,setupLights:l,setupLightsView:u,pushLight:o,pushShadow:a,pushLightProbeGrid:c}}function M_(i){let t=new WeakMap;function e(s,r=0){let o=t.get(s),a;return o===void 0?(a=new ed(i),t.set(s,[a])):r>=o.length?(a=new ed(i),o.push(a)):a=o[r],a}function n(){t=new WeakMap}return{get:e,dispose:n}}var S_=`void main() {+ gl_Position = vec4( position, 1.0 );+}`,b_=`uniform sampler2D shadow_pass;+uniform vec2 resolution;+uniform float radius;+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 = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ).rg;+ mean += distribution.x;+ squared_mean += distribution.y * distribution.y + distribution.x * distribution.x;+ #else+ float depth = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ).r;+ mean += depth;+ squared_mean += depth * depth;+ #endif+ }+ mean = mean / samples;+ squared_mean = squared_mean / samples;+ float std_dev = sqrt( max( 0.0, squared_mean - mean * mean ) );+ gl_FragColor = vec4( mean, std_dev, 0.0, 1.0 );+}`,w_=[new P(1,0,0),new P(-1,0,0),new P(0,1,0),new P(0,-1,0),new P(0,0,1),new P(0,0,-1)],E_=[new P(0,-1,0),new P(0,-1,0),new P(0,0,1),new P(0,0,-1),new P(0,-1,0),new P(0,-1,0)],nd=new se,kr=new P,Ic=new P;function T_(i,t,e){let n=new Ns,s=new Pt,r=new Pt,o=new me,a=new Zo,c=new jo,l={},u=e.maxTextureSize,f={[Ti]:Ze,[Ze]:Ti,[_n]:_n},h=new un({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new Pt},radius:{value:4}},vertexShader:S_,fragmentShader:b_}),p=h.clone();p.defines.HORIZONTAL_PASS=1;let g=new ve;g.setAttribute("position",new cn(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));let v=new ut(g,h),m=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=Rr;let d=this.type;this.render=function(w,C,_){if(m.enabled===!1||m.autoUpdate===!1&&m.needsUpdate===!1||w.length===0)return;this.type===la&&(It("WebGLShadowMap: PCFSoftShadowMap has been removed. Using PCFShadowMap instead."),this.type=Rr);let E=i.getRenderTarget(),R=i.getActiveCubeFace(),L=i.getActiveMipmapLevel(),F=i.state;F.setBlending(Hn),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=d!==this.type;z&&C.traverse(function(I){I.material&&(Array.isArray(I.material)?I.material.forEach(O=>O.needsUpdate=!0):I.material.needsUpdate=!0)});for(let I=0,O=w.length;I<O;I++){let G=w[I],X=G.shadow;if(X===void 0){It("WebGLShadowMap:",G,"has no shadow.");continue}if(X.autoUpdate===!1&&X.needsUpdate===!1)continue;s.copy(X.mapSize);let et=X.getFrameExtents();s.multiply(et),r.copy(X.mapSize),(s.x>u||s.y>u)&&(s.x>u&&(r.x=Math.floor(u/et.x),s.x=r.x*et.x,X.mapSize.x=r.x),s.y>u&&(r.y=Math.floor(u/et.y),s.y=r.y*et.y,X.mapSize.y=r.y));let Y=i.state.buffers.depth.getReversed();if(X.camera._reversedDepth=Y,X.map===null||z===!0){if(X.map!==null&&(X.map.depthTexture!==null&&(X.map.depthTexture.dispose(),X.map.depthTexture=null),X.map.dispose()),this.type===zs){if(G.isPointLight){It("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}X.map=new Ke(s.x,s.y,{format:Pi,type:Ln,minFilter:Fe,magFilter:Fe,generateMipmaps:!1}),X.map.texture.name=G.name+".shadowMap",X.map.depthTexture=new vi(s.x,s.y,In),X.map.depthTexture.name=G.name+".shadowMapDepth",X.map.depthTexture.format=kn,X.map.depthTexture.compareFunction=null,X.map.depthTexture.minFilter=De,X.map.depthTexture.magFilter=De}else G.isPointLight?(X.map=new tl(s.x),X.map.depthTexture=new Xo(s.x,Pn)):(X.map=new Ke(s.x,s.y),X.map.depthTexture=new vi(s.x,s.y,Pn)),X.map.depthTexture.name=G.name+".shadowMap",X.map.depthTexture.format=kn,this.type===Rr?(X.map.depthTexture.compareFunction=Y?Ja:ja,X.map.depthTexture.minFilter=Fe,X.map.depthTexture.magFilter=Fe):(X.map.depthTexture.compareFunction=null,X.map.depthTexture.minFilter=De,X.map.depthTexture.magFilter=De);X.camera.updateProjectionMatrix()}X.map.isWebGLCubeRenderTarget!==!0&&(X.map.width!==s.x||X.map.height!==s.y)&&X.map.setSize(s.x,s.y);let K=X.map.isWebGLCubeRenderTarget?6:X.getViewportCount();G.isPointLight!==!0&&X.updateMatrices(G,_);for(let nt=0;nt<K;nt++){let Et=X.getCamera(nt);if(G.isPointLight){let Tt=X.camera,te=X.matrix,qt=G.distance||Tt.far;qt!==Tt.far&&(Tt.far=qt,Tt.updateProjectionMatrix()),kr.setFromMatrixPosition(G.matrixWorld),Tt.position.copy(kr),Ic.copy(Tt.position),Ic.add(w_[nt]),Tt.up.copy(E_[nt]),Tt.lookAt(Ic),Tt.updateMatrixWorld(),te.makeTranslation(-kr.x,-kr.y,-kr.z),nd.multiplyMatrices(Tt.projectionMatrix,Tt.matrixWorldInverse),X._frustum.setFromProjectionMatrix(nd,Tt.coordinateSystem,Tt.reversedDepth)}if(X.map.isWebGLCubeRenderTarget)i.setRenderTarget(X.map,nt),i.clear();else{nt===0&&(i.setRenderTarget(X.map),i.clear());let Tt=X.getViewport(nt);o.set(r.x*Tt.x,r.y*Tt.y,r.x*Tt.z,r.y*Tt.w),F.viewport(o)}n=X.getFrustum(nt),y(C,_,Et,G,this.type)}X.isPointLightShadow!==!0&&this.type===zs&&S(X,_),X.needsUpdate=!1}d=this.type,m.needsUpdate=!1,i.setRenderTarget(E,R,L)};function S(w,C){let _=t.update(v);h.defines.VSM_SAMPLES!==w.blurSamples&&(h.defines.VSM_SAMPLES=w.blurSamples,p.defines.VSM_SAMPLES=w.blurSamples,h.needsUpdate=!0,p.needsUpdate=!0),w.mapPass===null?w.mapPass=new Ke(s.x,s.y,{format:Pi,type:Ln}):(w.mapPass.width!==w.map.width||w.mapPass.height!==w.map.height)&&w.mapPass.setSize(w.map.width,w.map.height),h.uniforms.shadow_pass.value=w.map.depthTexture,h.uniforms.resolution.value.set(w.map.width,w.map.height),h.uniforms.radius.value=w.radius,i.setRenderTarget(w.mapPass),i.clear(),i.renderBufferDirect(C,null,_,h,v,null),p.uniforms.shadow_pass.value=w.mapPass.texture,p.uniforms.resolution.value.set(w.map.width,w.map.height),p.uniforms.radius.value=w.radius,i.setRenderTarget(w.map),i.clear(),i.renderBufferDirect(C,null,_,p,v,null)}function T(w,C,_,E){let R=null,L=_.isPointLight===!0?w.customDistanceMaterial:w.customDepthMaterial;if(L!==void 0)R=L;else if(R=_.isPointLight===!0?c:a,i.localClippingEnabled&&C.clipShadows===!0&&Array.isArray(C.clippingPlanes)&&C.clippingPlanes.length!==0||C.displacementMap&&C.displacementScale!==0||C.alphaMap&&C.alphaTest>0||C.map&&C.alphaTest>0||C.alphaToCoverage===!0){let F=R.uuid,z=C.uuid,I=l[F];I===void 0&&(I={},l[F]=I);let O=I[z];O===void 0&&(O=R.clone(),I[z]=O,C.addEventListener("dispose",b)),R=O}if(R.visible=C.visible,R.wireframe=C.wireframe,E===zs?R.side=C.shadowSide!==null?C.shadowSide:C.side:R.side=C.shadowSide!==null?C.shadowSide:f[C.side],R.alphaMap=C.alphaMap,R.alphaTest=C.alphaToCoverage===!0?.5:C.alphaTest,R.map=C.map,R.clipShadows=C.clipShadows,R.clippingPlanes=C.clippingPlanes,R.clipIntersection=C.clipIntersection,R.displacementMap=C.displacementMap,R.displacementScale=C.displacementScale,R.displacementBias=C.displacementBias,R.wireframeLinewidth=C.wireframeLinewidth,R.linewidth=C.linewidth,_.isPointLight===!0&&R.isMeshDistanceMaterial===!0){let F=i.properties.get(R);F.light=_}return R}function y(w,C,_,E,R){if(w.visible===!1)return;if(w.layers.test(C.layers)&&(w.isMesh||w.isLine||w.isPoints)&&(w.castShadow||w.receiveShadow&&R===zs)&&(!w.frustumCulled||w.intersectsFrustum(n))){w.modelViewMatrix.multiplyMatrices(_.matrixWorldInverse,w.matrixWorld);let z=t.update(w),I=w.material;if(Array.isArray(I)){let O=z.groups;for(let G=0,X=O.length;G<X;G++){let et=O[G],Y=I[et.materialIndex];if(Y&&Y.visible){let K=T(w,Y,E,R);w.onBeforeShadow(i,w,C,_,z,K,et),i.renderBufferDirect(_,null,z,K,w,et),w.onAfterShadow(i,w,C,_,z,K,et)}}}else if(I.visible){let O=T(w,I,E,R);w.onBeforeShadow(i,w,C,_,z,O,null),i.renderBufferDirect(_,null,z,O,w,null),w.onAfterShadow(i,w,C,_,z,O,null)}}let F=w.children;for(let z=0,I=F.length;z<I;z++)y(F[z],C,_,E,R)}function b(w){w.target.removeEventListener("dispose",b);for(let _ in l){let E=l[_],R=w.target.uuid;R in E&&(E[R].dispose(),delete E[R])}}}function A_(i,t){function e(){let N=!1,ct=new me,J=null,ht=new me(0,0,0,0);return{setMask:function(gt){J!==gt&&!N&&(i.colorMask(gt,gt,gt,gt),J=gt)},setLocked:function(gt){N=gt},setClear:function(gt,it,Rt,bt,le){le===!0&&(gt*=bt,it*=bt,Rt*=bt),ct.set(gt,it,Rt,bt),ht.equals(ct)===!1&&(i.clearColor(gt,it,Rt,bt),ht.copy(ct))},reset:function(){N=!1,J=null,ht.set(-1,0,0,0)}}}function n(){let N=!1,ct=!1,J=null,ht=null,gt=null;return{setReversed:function(it){if(ct!==it){let Rt=t.get("EXT_clip_control");it?Rt.clipControlEXT(Rt.LOWER_LEFT_EXT,Rt.ZERO_TO_ONE_EXT):Rt.clipControlEXT(Rt.LOWER_LEFT_EXT,Rt.NEGATIVE_ONE_TO_ONE_EXT),ct=it;let bt=gt;gt=null,this.setClear(bt)}},getReversed:function(){return ct},setTest:function(it){it?Q(i.DEPTH_TEST):vt(i.DEPTH_TEST)},setMask:function(it){J!==it&&!N&&(i.depthMask(it),J=it)},setFunc:function(it){if(ct&&(it=Iu[it]),ht!==it){switch(it){case Ro:i.depthFunc(i.NEVER);break;case Po:i.depthFunc(i.ALWAYS);break;case Io:i.depthFunc(i.LESS);break;case As:i.depthFunc(i.LEQUAL);break;case Lo:i.depthFunc(i.EQUAL);break;case Do:i.depthFunc(i.GEQUAL);break;case No:i.depthFunc(i.GREATER);break;case Uo:i.depthFunc(i.NOTEQUAL);break;default:i.depthFunc(i.LEQUAL)}ht=it}},setLocked:function(it){N=it},setClear:function(it){gt!==it&&(gt=it,ct&&(it=1-it),i.clearDepth(it))},reset:function(){N=!1,J=null,ht=null,gt=null,ct=!1}}}function s(){let N=!1,ct=null,J=null,ht=null,gt=null,it=null,Rt=null,bt=null,le=null;return{setTest:function($t){N||($t?Q(i.STENCIL_TEST):vt(i.STENCIL_TEST))},setMask:function($t){ct!==$t&&!N&&(i.stencilMask($t),ct=$t)},setFunc:function($t,vn,Fn){(J!==$t||ht!==vn||gt!==Fn)&&(i.stencilFunc($t,vn,Fn),J=$t,ht=vn,gt=Fn)},setOp:function($t,vn,Fn){(it!==$t||Rt!==vn||bt!==Fn)&&(i.stencilOp($t,vn,Fn),it=$t,Rt=vn,bt=Fn)},setLocked:function($t){N=$t},setClear:function($t){le!==$t&&(i.clearStencil($t),le=$t)},reset:function(){N=!1,ct=null,J=null,ht=null,gt=null,it=null,Rt=null,bt=null,le=null}}}let r=new e,o=new n,a=new s,c=new WeakMap,l=new WeakMap,u={},f={},h={},p=new WeakMap,g=[],v=null,m=!1,d=null,S=null,T=null,y=null,b=null,w=null,C=null,_=new Nt(0,0,0),E=0,R=!1,L=null,F=null,z=null,I=null,O=null,G=i.getParameter(i.MAX_COMBINED_TEXTURE_IMAGE_UNITS),X=!1,et=0,Y=i.getParameter(i.VERSION);Y.indexOf("WebGL")!==-1?(et=parseFloat(/^WebGL (\d)/.exec(Y)[1]),X=et>=1):Y.indexOf("OpenGL ES")!==-1&&(et=parseFloat(/^OpenGL ES (\d)/.exec(Y)[1]),X=et>=2);let K=null,nt={},Et=i.getParameter(i.SCISSOR_BOX),Tt=i.getParameter(i.VIEWPORT),te=new me().fromArray(Et),qt=new me().fromArray(Tt);function Jt(N,ct,J,ht){let gt=new Uint8Array(4),it=i.createTexture();i.bindTexture(N,it),i.texParameteri(N,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(N,i.TEXTURE_MAG_FILTER,i.NEAREST);for(let Rt=0;Rt<J;Rt++)N===i.TEXTURE_3D||N===i.TEXTURE_2D_ARRAY?i.texImage3D(ct,0,i.RGBA,1,1,ht,0,i.RGBA,i.UNSIGNED_BYTE,gt):i.texImage2D(ct+Rt,0,i.RGBA,1,1,0,i.RGBA,i.UNSIGNED_BYTE,gt);return it}let Z={};Z[i.TEXTURE_2D]=Jt(i.TEXTURE_2D,i.TEXTURE_2D,1),Z[i.TEXTURE_CUBE_MAP]=Jt(i.TEXTURE_CUBE_MAP,i.TEXTURE_CUBE_MAP_POSITIVE_X,6),Z[i.TEXTURE_2D_ARRAY]=Jt(i.TEXTURE_2D_ARRAY,i.TEXTURE_2D_ARRAY,1,1),Z[i.TEXTURE_3D]=Jt(i.TEXTURE_3D,i.TEXTURE_3D,1,1),r.setClear(0,0,0,1),o.setClear(1),a.setClear(0),Q(i.DEPTH_TEST),o.setFunc(As),Wt(!1),fe($l),Q(i.CULL_FACE),jt(Hn);function Q(N){u[N]!==!0&&(i.enable(N),u[N]=!0)}function vt(N){u[N]!==!1&&(i.disable(N),u[N]=!1)}function Ft(N,ct){return h[N]!==ct?(i.bindFramebuffer(N,ct),h[N]=ct,N===i.DRAW_FRAMEBUFFER&&(h[i.FRAMEBUFFER]=ct),N===i.FRAMEBUFFER&&(h[i.DRAW_FRAMEBUFFER]=ct),!0):!1}function xt(N,ct){let J=g,ht=!1;if(N){J=p.get(ct),J===void 0&&(J=[],p.set(ct,J));let gt=N.textures;if(J.length!==gt.length||J[0]!==i.COLOR_ATTACHMENT0){for(let it=0,Rt=gt.length;it<Rt;it++)J[it]=i.COLOR_ATTACHMENT0+it;J.length=gt.length,ht=!0}}else J[0]!==i.BACK&&(J[0]=i.BACK,ht=!0);ht&&i.drawBuffers(J)}function kt(N){return v!==N?(i.useProgram(N),v=N,!0):!1}let Ae={[Yi]:i.FUNC_ADD,[Kh]:i.FUNC_SUBTRACT,[Qh]:i.FUNC_REVERSE_SUBTRACT};Ae[tu]=i.MIN,Ae[eu]=i.MAX;let Ht={[nu]:i.ZERO,[iu]:i.ONE,[su]:i.SRC_COLOR,[ec]:i.SRC_ALPHA,[hu]:i.SRC_ALPHA_SATURATE,[lu]:i.DST_COLOR,[ou]:i.DST_ALPHA,[ru]:i.ONE_MINUS_SRC_COLOR,[nc]:i.ONE_MINUS_SRC_ALPHA,[cu]:i.ONE_MINUS_DST_COLOR,[au]:i.ONE_MINUS_DST_ALPHA,[uu]:i.CONSTANT_COLOR,[du]:i.ONE_MINUS_CONSTANT_COLOR,[fu]:i.CONSTANT_ALPHA,[pu]:i.ONE_MINUS_CONSTANT_ALPHA};function jt(N,ct,J,ht,gt,it,Rt,bt,le,$t){if(N===Hn){m===!0&&(vt(i.BLEND),m=!1);return}if(m===!1&&(Q(i.BLEND),m=!0),N!==$h){if(N!==d||$t!==R){if((S!==Yi||b!==Yi)&&(i.blendEquation(i.FUNC_ADD),S=Yi,b=Yi),$t)switch(N){case ks:i.blendFuncSeparate(i.ONE,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA);break;case Kl:i.blendFunc(i.ONE,i.ONE);break;case Ql:i.blendFuncSeparate(i.ZERO,i.ONE_MINUS_SRC_COLOR,i.ZERO,i.ONE);break;case tc:i.blendFuncSeparate(i.DST_COLOR,i.ONE_MINUS_SRC_ALPHA,i.ZERO,i.ONE);break;default:Dt("WebGLState: Invalid blending: ",N);break}else switch(N){case ks:i.blendFuncSeparate(i.SRC_ALPHA,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA);break;case Kl:i.blendFuncSeparate(i.SRC_ALPHA,i.ONE,i.ONE,i.ONE);break;case Ql:Dt("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case tc:Dt("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:Dt("WebGLState: Invalid blending: ",N);break}T=null,y=null,w=null,C=null,_.set(0,0,0),E=0,d=N,R=$t}return}gt=gt||ct,it=it||J,Rt=Rt||ht,(ct!==S||gt!==b)&&(i.blendEquationSeparate(Ae[ct],Ae[gt]),S=ct,b=gt),(J!==T||ht!==y||it!==w||Rt!==C)&&(i.blendFuncSeparate(Ht[J],Ht[ht],Ht[it],Ht[Rt]),T=J,y=ht,w=it,C=Rt),(bt.equals(_)===!1||le!==E)&&(i.blendColor(bt.r,bt.g,bt.b,le),_.copy(bt),E=le),d=N,R=!1}function ae(N,ct){N.side===_n?vt(i.CULL_FACE):Q(i.CULL_FACE);let J=N.side===Ze;ct&&(J=!J),Wt(J),N.blending===ks&&N.transparent===!1?jt(Hn):jt(N.blending,N.blendEquation,N.blendSrc,N.blendDst,N.blendEquationAlpha,N.blendSrcAlpha,N.blendDstAlpha,N.blendColor,N.blendAlpha,N.premultipliedAlpha),o.setFunc(N.depthFunc),o.setTest(N.depthTest),o.setMask(N.depthWrite),r.setMask(N.colorWrite);let ht=N.stencilWrite;a.setTest(ht),ht&&(a.setMask(N.stencilWriteMask),a.setFunc(N.stencilFunc,N.stencilRef,N.stencilFuncMask),a.setOp(N.stencilFail,N.stencilZFail,N.stencilZPass)),Je(N.polygonOffset,N.polygonOffsetFactor,N.polygonOffsetUnits),N.alphaToCoverage===!0?Q(i.SAMPLE_ALPHA_TO_COVERAGE):vt(i.SAMPLE_ALPHA_TO_COVERAGE)}function Wt(N){L!==N&&(N?i.frontFace(i.CW):i.frontFace(i.CCW),L=N)}function fe(N){N!==jh?(Q(i.CULL_FACE),N!==F&&(N===$l?i.cullFace(i.BACK):N===Jh?i.cullFace(i.FRONT):i.cullFace(i.FRONT_AND_BACK))):vt(i.CULL_FACE),F=N}function Ie(N){N!==z&&(X&&i.lineWidth(N),z=N)}function Je(N,ct,J){N?(Q(i.POLYGON_OFFSET_FILL),(I!==ct||O!==J)&&(I=ct,O=J,o.getReversed()&&(ct=-ct),i.polygonOffset(ct,J))):vt(i.POLYGON_OFFSET_FILL)}function xe(N){N?Q(i.SCISSOR_TEST):vt(i.SCISSOR_TEST)}function we(N){N===void 0&&(N=i.TEXTURE0+G-1),K!==N&&(i.activeTexture(N),K=N)}function U(N,ct,J){J===void 0&&(K===null?J=i.TEXTURE0+G-1:J=K);let ht=nt[J];ht===void 0&&(ht={type:void 0,texture:void 0},nt[J]=ht),(ht.type!==N||ht.texture!==ct)&&(K!==J&&(i.activeTexture(J),K=J),i.bindTexture(N,ct||Z[N]),ht.type=N,ht.texture=ct)}function Be(){let N=nt[K];N!==void 0&&N.type!==void 0&&(i.bindTexture(N.type,null),N.type=void 0,N.texture=void 0)}function ee(){try{i.compressedTexImage2D(...arguments)}catch(N){Dt("WebGLState:",N)}}function A(){try{i.compressedTexImage3D(...arguments)}catch(N){Dt("WebGLState:",N)}}function x(){try{i.texSubImage2D(...arguments)}catch(N){Dt("WebGLState:",N)}}function B(){try{i.texSubImage3D(...arguments)}catch(N){Dt("WebGLState:",N)}}function H(){try{i.compressedTexSubImage2D(...arguments)}catch(N){Dt("WebGLState:",N)}}function q(){try{i.compressedTexSubImage3D(...arguments)}catch(N){Dt("WebGLState:",N)}}function rt(){try{i.texStorage2D(...arguments)}catch(N){Dt("WebGLState:",N)}}function ot(){try{i.texStorage3D(...arguments)}catch(N){Dt("WebGLState:",N)}}function j(){try{i.texImage2D(...arguments)}catch(N){Dt("WebGLState:",N)}}function $(){try{i.texImage3D(...arguments)}catch(N){Dt("WebGLState:",N)}}function at(N){return f[N]!==void 0?f[N]:i.getParameter(N)}function At(N,ct){f[N]!==ct&&(i.pixelStorei(N,ct),f[N]=ct)}function dt(N){te.equals(N)===!1&&(i.scissor(N.x,N.y,N.z,N.w),te.copy(N))}function lt(N){qt.equals(N)===!1&&(i.viewport(N.x,N.y,N.z,N.w),qt.copy(N))}function Ct(N,ct){let J=l.get(ct);J===void 0&&(J=new WeakMap,l.set(ct,J));let ht=J.get(N);ht===void 0&&(ht=i.getUniformBlockIndex(ct,N.name),J.set(N,ht))}function Lt(N,ct){let ht=l.get(ct).get(N);c.get(ct)!==ht&&(i.uniformBlockBinding(ct,ht,N.__bindingPointIndex),c.set(ct,ht))}function Ot(){i.disable(i.BLEND),i.disable(i.CULL_FACE),i.disable(i.DEPTH_TEST),i.disable(i.POLYGON_OFFSET_FILL),i.disable(i.SCISSOR_TEST),i.disable(i.STENCIL_TEST),i.disable(i.SAMPLE_ALPHA_TO_COVERAGE),i.blendEquation(i.FUNC_ADD),i.blendFunc(i.ONE,i.ZERO),i.blendFuncSeparate(i.ONE,i.ZERO,i.ONE,i.ZERO),i.blendColor(0,0,0,0),i.colorMask(!0,!0,!0,!0),i.clearColor(0,0,0,0),i.depthMask(!0),i.depthFunc(i.LESS),o.setReversed(!1),i.clearDepth(1),i.stencilMask(4294967295),i.stencilFunc(i.ALWAYS,0,4294967295),i.stencilOp(i.KEEP,i.KEEP,i.KEEP),i.clearStencil(0),i.cullFace(i.BACK),i.frontFace(i.CCW),i.polygonOffset(0,0),i.activeTexture(i.TEXTURE0),i.bindFramebuffer(i.FRAMEBUFFER,null),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,null),i.bindFramebuffer(i.READ_FRAMEBUFFER,null),i.useProgram(null),i.lineWidth(1),i.scissor(0,0,i.canvas.width,i.canvas.height),i.viewport(0,0,i.canvas.width,i.canvas.height),i.pixelStorei(i.PACK_ALIGNMENT,4),i.pixelStorei(i.UNPACK_ALIGNMENT,4),i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,!1),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,i.BROWSER_DEFAULT_WEBGL),i.pixelStorei(i.PACK_ROW_LENGTH,0),i.pixelStorei(i.PACK_SKIP_PIXELS,0),i.pixelStorei(i.PACK_SKIP_ROWS,0),i.pixelStorei(i.UNPACK_ROW_LENGTH,0),i.pixelStorei(i.UNPACK_IMAGE_HEIGHT,0),i.pixelStorei(i.UNPACK_SKIP_PIXELS,0),i.pixelStorei(i.UNPACK_SKIP_ROWS,0),i.pixelStorei(i.UNPACK_SKIP_IMAGES,0),u={},f={},K=null,nt={},h={},p=new WeakMap,g=[],v=null,m=!1,d=null,S=null,T=null,y=null,b=null,w=null,C=null,_=new Nt(0,0,0),E=0,R=!1,L=null,F=null,z=null,I=null,O=null,te.set(0,0,i.canvas.width,i.canvas.height),qt.set(0,0,i.canvas.width,i.canvas.height),r.reset(),o.reset(),a.reset()}return{buffers:{color:r,depth:o,stencil:a},enable:Q,disable:vt,bindFramebuffer:Ft,drawBuffers:xt,useProgram:kt,setBlending:jt,setMaterial:ae,setFlipSided:Wt,setCullFace:fe,setLineWidth:Ie,setPolygonOffset:Je,setScissorTest:xe,activeTexture:we,bindTexture:U,unbindTexture:Be,compressedTexImage2D:ee,compressedTexImage3D:A,texImage2D:j,texImage3D:$,pixelStorei:At,getParameter:at,updateUBOMapping:Ct,uniformBlockBinding:Lt,texStorage2D:rt,texStorage3D:ot,texSubImage2D:x,texSubImage3D:B,compressedTexSubImage2D:H,compressedTexSubImage3D:q,scissor:dt,viewport:lt,reset:Ot}}function C_(i,t,e,n,s,r,o){let a=t.has("WEBGL_multisampled_render_to_texture")?t.get("WEBGL_multisampled_render_to_texture"):null,c=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),l=new Pt,u=new WeakMap,f=new Set,h,p=new WeakMap,g=!1;try{g=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function v(A,x){return g?new OffscreenCanvas(A,x):ur("canvas")}function m(A,x,B){let H=1,q=ee(A);if((q.width>B||q.height>B)&&(H=B/Math.max(q.width,q.height)),H<1)if(typeof HTMLImageElement<"u"&&A instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&A instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&A instanceof ImageBitmap||typeof VideoFrame<"u"&&A instanceof VideoFrame){let rt=Math.floor(H*q.width),ot=Math.floor(H*q.height);h===void 0&&(h=v(rt,ot));let j=x?v(rt,ot):h;return j.width=rt,j.height=ot,j.getContext("2d").drawImage(A,0,0,rt,ot),It("WebGLRenderer: Texture has been resized from ("+q.width+"x"+q.height+") to ("+rt+"x"+ot+")."),j}else return"data"in A&&It("WebGLRenderer: Image in DataTexture is too big ("+q.width+"x"+q.height+")."),A;return A}function d(A){return A.generateMipmaps}function S(A){i.generateMipmap(A)}function T(A){return A.isWebGLCubeRenderTarget?i.TEXTURE_CUBE_MAP:A.isWebGL3DRenderTarget?i.TEXTURE_3D:A.isWebGLArrayRenderTarget||A.isCompressedArrayTexture?i.TEXTURE_2D_ARRAY:i.TEXTURE_2D}function y(A,x,B,H,q,rt=!1){if(A!==null){if(i[A]!==void 0)return i[A];It("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+A+"'")}let ot;H&&(ot=t.get("EXT_texture_norm16"),ot||It("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension"));let j=x;if(x===i.RED&&(B===i.FLOAT&&(j=i.R32F),B===i.HALF_FLOAT&&(j=i.R16F),B===i.UNSIGNED_BYTE&&(j=i.R8),B===i.UNSIGNED_SHORT&&ot&&(j=ot.R16_EXT),B===i.SHORT&&ot&&(j=ot.R16_SNORM_EXT)),x===i.RED_INTEGER&&(B===i.UNSIGNED_BYTE&&(j=i.R8UI),B===i.UNSIGNED_SHORT&&(j=i.R16UI),B===i.UNSIGNED_INT&&(j=i.R32UI),B===i.BYTE&&(j=i.R8I),B===i.SHORT&&(j=i.R16I),B===i.INT&&(j=i.R32I)),x===i.RG&&(B===i.FLOAT&&(j=i.RG32F),B===i.HALF_FLOAT&&(j=i.RG16F),B===i.UNSIGNED_BYTE&&(j=i.RG8),B===i.UNSIGNED_SHORT&&ot&&(j=ot.RG16_EXT),B===i.SHORT&&ot&&(j=ot.RG16_SNORM_EXT)),x===i.RG_INTEGER&&(B===i.UNSIGNED_BYTE&&(j=i.RG8UI),B===i.UNSIGNED_SHORT&&(j=i.RG16UI),B===i.UNSIGNED_INT&&(j=i.RG32UI),B===i.BYTE&&(j=i.RG8I),B===i.SHORT&&(j=i.RG16I),B===i.INT&&(j=i.RG32I)),x===i.RGB_INTEGER&&(B===i.UNSIGNED_BYTE&&(j=i.RGB8UI),B===i.UNSIGNED_SHORT&&(j=i.RGB16UI),B===i.UNSIGNED_INT&&(j=i.RGB32UI),B===i.BYTE&&(j=i.RGB8I),B===i.SHORT&&(j=i.RGB16I),B===i.INT&&(j=i.RGB32I)),x===i.RGBA_INTEGER&&(B===i.UNSIGNED_BYTE&&(j=i.RGBA8UI),B===i.UNSIGNED_SHORT&&(j=i.RGBA16UI),B===i.UNSIGNED_INT&&(j=i.RGBA32UI),B===i.BYTE&&(j=i.RGBA8I),B===i.SHORT&&(j=i.RGBA16I),B===i.INT&&(j=i.RGBA32I)),x===i.RGB&&(B===i.UNSIGNED_SHORT&&ot&&(j=ot.RGB16_EXT),B===i.SHORT&&ot&&(j=ot.RGB16_SNORM_EXT),B===i.UNSIGNED_INT_5_9_9_9_REV&&(j=i.RGB9_E5),B===i.UNSIGNED_INT_10F_11F_11F_REV&&(j=i.R11F_G11F_B10F)),x===i.RGBA){let $=rt?hr:Xt.getTransfer(q);B===i.FLOAT&&(j=i.RGBA32F),B===i.HALF_FLOAT&&(j=i.RGBA16F),B===i.UNSIGNED_BYTE&&(j=$===Qt?i.SRGB8_ALPHA8:i.RGBA8),B===i.UNSIGNED_SHORT&&ot&&(j=ot.RGBA16_EXT),B===i.SHORT&&ot&&(j=ot.RGBA16_SNORM_EXT),B===i.UNSIGNED_SHORT_4_4_4_4&&(j=i.RGBA4),B===i.UNSIGNED_SHORT_5_5_5_1&&(j=i.RGB5_A1)}return(j===i.R16F||j===i.R32F||j===i.RG16F||j===i.RG32F||j===i.RGBA16F||j===i.RGBA32F)&&t.get("EXT_color_buffer_float"),j}function b(A,x){let B;return A?x===null||x===Pn||x===Hs?B=i.DEPTH24_STENCIL8:x===In?B=i.DEPTH32F_STENCIL8:x===Vs&&(B=i.DEPTH24_STENCIL8,It("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):x===null||x===Pn||x===Hs?B=i.DEPTH_COMPONENT24:x===In?B=i.DEPTH_COMPONENT32F:x===Vs&&(B=i.DEPTH_COMPONENT16),B}function w(A,x){return d(A)===!0||A.isFramebufferTexture&&A.minFilter!==De&&A.minFilter!==Fe?Math.log2(Math.max(x.width,x.height))+1:A.mipmaps!==void 0&&A.mipmaps.length>0?A.mipmaps.length:A.isCompressedTexture&&Array.isArray(A.image)?x.mipmaps.length:1}function C(A){let x=A.target;x.removeEventListener("dispose",C),E(x),x.isVideoTexture&&u.delete(x),x.isHTMLTexture&&f.delete(x)}function _(A){let x=A.target;x.removeEventListener("dispose",_),L(x)}function E(A){let x=n.get(A);if(x.__webglInit===void 0)return;let B=A.source,H=p.get(B);if(H){let q=H[x.__cacheKey];q.usedTimes--,q.usedTimes===0&&R(A),Object.keys(H).length===0&&p.delete(B)}n.remove(A)}function R(A){let x=n.get(A);i.deleteTexture(x.__webglTexture);let B=A.source,H=p.get(B);delete H[x.__cacheKey],o.memory.textures--}function L(A){let x=n.get(A);if(A.depthTexture&&(A.depthTexture.dispose(),n.remove(A.depthTexture)),A.isWebGLCubeRenderTarget)for(let H=0;H<6;H++){if(Array.isArray(x.__webglFramebuffer[H]))for(let q=0;q<x.__webglFramebuffer[H].length;q++)i.deleteFramebuffer(x.__webglFramebuffer[H][q]);else i.deleteFramebuffer(x.__webglFramebuffer[H]);x.__webglDepthbuffer&&i.deleteRenderbuffer(x.__webglDepthbuffer[H])}else{if(Array.isArray(x.__webglFramebuffer))for(let H=0;H<x.__webglFramebuffer.length;H++)i.deleteFramebuffer(x.__webglFramebuffer[H]);else i.deleteFramebuffer(x.__webglFramebuffer);if(x.__webglDepthbuffer&&i.deleteRenderbuffer(x.__webglDepthbuffer),x.__webglMultisampledFramebuffer&&i.deleteFramebuffer(x.__webglMultisampledFramebuffer),x.__webglColorRenderbuffer)for(let H=0;H<x.__webglColorRenderbuffer.length;H++)x.__webglColorRenderbuffer[H]&&i.deleteRenderbuffer(x.__webglColorRenderbuffer[H]);x.__webglDepthRenderbuffer&&i.deleteRenderbuffer(x.__webglDepthRenderbuffer)}let B=A.textures;for(let H=0,q=B.length;H<q;H++){let rt=n.get(B[H]);rt.__webglTexture&&(i.deleteTexture(rt.__webglTexture),o.memory.textures--),n.remove(B[H])}n.remove(A)}let F=0;function z(){F=0}function I(){return F}function O(A){F=A}function G(){let A=F;return A>=s.maxTextures&&It("WebGLTextures: Trying to use "+(A+1)+" texture units while this GPU supports only "+s.maxTextures),F+=1,A}function X(A){let x=[];return x.push(A.wrapS),x.push(A.wrapT),x.push(A.wrapR||0),x.push(A.magFilter),x.push(A.minFilter),x.push(A.anisotropy),x.push(A.internalFormat),x.push(A.format),x.push(A.type),x.push(A.generateMipmaps),x.push(A.premultiplyAlpha),x.push(A.flipY),x.push(A.unpackAlignment),x.push(A.colorSpace),x.join()}function et(A,x){let B=n.get(A);if(A.isVideoTexture&&U(A),A.isRenderTargetTexture===!1&&A.isExternalTexture!==!0&&A.version>0&&B.__version!==A.version){let H=A.image;if(H===null)It("WebGLRenderer: Texture marked for update but no image data found.");else if(H.complete===!1)It("WebGLRenderer: Texture marked for update but image is incomplete");else{vt(B,A,x);return}}else A.isExternalTexture&&(B.__webglTexture=A.sourceTexture?A.sourceTexture:null);e.bindTexture(i.TEXTURE_2D,B.__webglTexture,i.TEXTURE0+x)}function Y(A,x){let B=n.get(A);if(A.isRenderTargetTexture===!1&&A.version>0&&B.__version!==A.version){vt(B,A,x);return}else A.isExternalTexture&&(B.__webglTexture=A.sourceTexture?A.sourceTexture:null);e.bindTexture(i.TEXTURE_2D_ARRAY,B.__webglTexture,i.TEXTURE0+x)}function K(A,x){let B=n.get(A);if(A.isRenderTargetTexture===!1&&A.version>0&&B.__version!==A.version){vt(B,A,x);return}e.bindTexture(i.TEXTURE_3D,B.__webglTexture,i.TEXTURE0+x)}function nt(A,x){let B=n.get(A);if(A.isCubeDepthTexture!==!0&&A.version>0&&B.__version!==A.version){Ft(B,A,x);return}e.bindTexture(i.TEXTURE_CUBE_MAP,B.__webglTexture,i.TEXTURE0+x)}let Et={[Fo]:i.REPEAT,[zn]:i.CLAMP_TO_EDGE,[Oo]:i.MIRRORED_REPEAT},Tt={[De]:i.NEAREST,[_u]:i.NEAREST_MIPMAP_NEAREST,[Lr]:i.NEAREST_MIPMAP_LINEAR,[Fe]:i.LINEAR,[ua]:i.LINEAR_MIPMAP_NEAREST,[Ci]:i.LINEAR_MIPMAP_LINEAR},te={[Mu]:i.NEVER,[Tu]:i.ALWAYS,[Su]:i.LESS,[ja]:i.LEQUAL,[bu]:i.EQUAL,[Ja]:i.GEQUAL,[wu]:i.GREATER,[Eu]:i.NOTEQUAL};function qt(A,x){if(x.type===In&&t.has("OES_texture_float_linear")===!1&&(x.magFilter===Fe||x.magFilter===ua||x.magFilter===Lr||x.magFilter===Ci||x.minFilter===Fe||x.minFilter===ua||x.minFilter===Lr||x.minFilter===Ci)&&It("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),i.texParameteri(A,i.TEXTURE_WRAP_S,Et[x.wrapS]),i.texParameteri(A,i.TEXTURE_WRAP_T,Et[x.wrapT]),(A===i.TEXTURE_3D||A===i.TEXTURE_2D_ARRAY)&&i.texParameteri(A,i.TEXTURE_WRAP_R,Et[x.wrapR]),i.texParameteri(A,i.TEXTURE_MAG_FILTER,Tt[x.magFilter]),i.texParameteri(A,i.TEXTURE_MIN_FILTER,Tt[x.minFilter]),x.compareFunction&&(i.texParameteri(A,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE),i.texParameteri(A,i.TEXTURE_COMPARE_FUNC,te[x.compareFunction])),t.has("EXT_texture_filter_anisotropic")===!0){if(x.magFilter===De||x.minFilter!==Lr&&x.minFilter!==Ci||x.type===In&&t.has("OES_texture_float_linear")===!1)return;if(x.anisotropy>1||n.get(x).__currentAnisotropy){let B=t.get("EXT_texture_filter_anisotropic");i.texParameterf(A,B.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(x.anisotropy,s.getMaxAnisotropy())),n.get(x).__currentAnisotropy=x.anisotropy}}}function Jt(A,x){let B=!1;A.__webglInit===void 0&&(A.__webglInit=!0,x.addEventListener("dispose",C));let H=x.source,q=p.get(H);q===void 0&&(q={},p.set(H,q));let rt=X(x);if(rt!==A.__cacheKey){q[rt]===void 0&&(q[rt]={texture:i.createTexture(),usedTimes:0},o.memory.textures++,B=!0),q[rt].usedTimes++;let ot=q[A.__cacheKey];ot!==void 0&&(q[A.__cacheKey].usedTimes--,ot.usedTimes===0&&R(x)),A.__cacheKey=rt,A.__webglTexture=q[rt].texture}return B}function Z(A,x,B){return Math.floor(Math.floor(A/B)/x)}function Q(A,x,B,H){let rt=A.updateRanges;if(rt.length===0)e.texSubImage2D(i.TEXTURE_2D,0,0,0,x.width,x.height,B,H,x.data);else{rt.sort((At,dt)=>At.start-dt.start);let ot=0;for(let At=1;At<rt.length;At++){let dt=rt[ot],lt=rt[At],Ct=dt.start+dt.count,Lt=Z(lt.start,x.width,4),Ot=Z(dt.start,x.width,4);lt.start<=Ct+1&&Lt===Ot&&Z(lt.start+lt.count-1,x.width,4)===Lt?dt.count=Math.max(dt.count,lt.start+lt.count-dt.start):(++ot,rt[ot]=lt)}rt.length=ot+1;let j=e.getParameter(i.UNPACK_ROW_LENGTH),$=e.getParameter(i.UNPACK_SKIP_PIXELS),at=e.getParameter(i.UNPACK_SKIP_ROWS);e.pixelStorei(i.UNPACK_ROW_LENGTH,x.width);for(let At=0,dt=rt.length;At<dt;At++){let lt=rt[At],Ct=Math.floor(lt.start/4),Lt=Math.ceil(lt.count/4),Ot=Ct%x.width,N=Math.floor(Ct/x.width),ct=Lt,J=1;e.pixelStorei(i.UNPACK_SKIP_PIXELS,Ot),e.pixelStorei(i.UNPACK_SKIP_ROWS,N),e.texSubImage2D(i.TEXTURE_2D,0,Ot,N,ct,J,B,H,x.data)}A.clearUpdateRanges(),e.pixelStorei(i.UNPACK_ROW_LENGTH,j),e.pixelStorei(i.UNPACK_SKIP_PIXELS,$),e.pixelStorei(i.UNPACK_SKIP_ROWS,at)}}function vt(A,x,B){let H=i.TEXTURE_2D;(x.isDataArrayTexture||x.isCompressedArrayTexture)&&(H=i.TEXTURE_2D_ARRAY),x.isData3DTexture&&(H=i.TEXTURE_3D);let q=Jt(A,x),rt=x.source;e.bindTexture(H,A.__webglTexture,i.TEXTURE0+B);let ot=n.get(rt);if(rt.version!==ot.__version||q===!0){if(e.activeTexture(i.TEXTURE0+B),(typeof ImageBitmap<"u"&&x.image instanceof ImageBitmap)===!1){let J=Xt.getPrimaries(Xt.workingColorSpace),ht=x.colorSpace===si?null:Xt.getPrimaries(x.colorSpace),gt=x.colorSpace===si||J===ht?i.NONE:i.BROWSER_DEFAULT_WEBGL;e.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,x.flipY),e.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,x.premultiplyAlpha),e.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,gt)}e.pixelStorei(i.UNPACK_ALIGNMENT,x.unpackAlignment);let $=m(x.image,!1,s.maxTextureSize);$=Be(x,$);let at=r.convert(x.format,x.colorSpace),At=r.convert(x.type),dt=y(x.internalFormat,at,At,x.normalized,x.colorSpace,x.isVideoTexture);qt(H,x);let lt,Ct=x.mipmaps,Lt=x.isVideoTexture!==!0,Ot=ot.__version===void 0||q===!0,N=rt.dataReady,ct=w(x,$);if(x.isDepthTexture)dt=b(x.format===Ri,x.type),Ot&&(Lt?e.texStorage2D(i.TEXTURE_2D,1,dt,$.width,$.height):e.texImage2D(i.TEXTURE_2D,0,dt,$.width,$.height,0,at,At,null));else if(x.isDataTexture)if(Ct.length>0){Lt&&Ot&&e.texStorage2D(i.TEXTURE_2D,ct,dt,Ct[0].width,Ct[0].height);for(let J=0,ht=Ct.length;J<ht;J++)lt=Ct[J],Lt?N&&e.texSubImage2D(i.TEXTURE_2D,J,0,0,lt.width,lt.height,at,At,lt.data):e.texImage2D(i.TEXTURE_2D,J,dt,lt.width,lt.height,0,at,At,lt.data);x.generateMipmaps=!1}else Lt?(Ot&&e.texStorage2D(i.TEXTURE_2D,ct,dt,$.width,$.height),N&&Q(x,$,at,At)):e.texImage2D(i.TEXTURE_2D,0,dt,$.width,$.height,0,at,At,$.data);else if(x.isCompressedTexture)if(x.isCompressedArrayTexture){Lt&&Ot&&e.texStorage3D(i.TEXTURE_2D_ARRAY,ct,dt,Ct[0].width,Ct[0].height,$.depth);for(let J=0,ht=Ct.length;J<ht;J++)if(lt=Ct[J],x.format!==xn)if(at!==null)if(Lt){if(N)if(x.layerUpdates.size>0){let gt=Ec(lt.width,lt.height,x.format,x.type);for(let it of x.layerUpdates){let Rt=lt.data.subarray(it*gt/lt.data.BYTES_PER_ELEMENT,(it+1)*gt/lt.data.BYTES_PER_ELEMENT);e.compressedTexSubImage3D(i.TEXTURE_2D_ARRAY,J,0,0,it,lt.width,lt.height,1,at,Rt)}}else e.compressedTexSubImage3D(i.TEXTURE_2D_ARRAY,J,0,0,0,lt.width,lt.height,$.depth,at,lt.data)}else e.compressedTexImage3D(i.TEXTURE_2D_ARRAY,J,dt,lt.width,lt.height,$.depth,0,lt.data,0,0);else It("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else Lt?N&&e.texSubImage3D(i.TEXTURE_2D_ARRAY,J,0,0,0,lt.width,lt.height,$.depth,at,At,lt.data):e.texImage3D(i.TEXTURE_2D_ARRAY,J,dt,lt.width,lt.height,$.depth,0,at,At,lt.data);x.layerUpdates.size>0&&x.clearLayerUpdates()}else{Lt&&Ot&&e.texStorage2D(i.TEXTURE_2D,ct,dt,Ct[0].width,Ct[0].height);for(let J=0,ht=Ct.length;J<ht;J++)lt=Ct[J],x.format!==xn?at!==null?Lt?N&&e.compressedTexSubImage2D(i.TEXTURE_2D,J,0,0,lt.width,lt.height,at,lt.data):e.compressedTexImage2D(i.TEXTURE_2D,J,dt,lt.width,lt.height,0,lt.data):It("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):Lt?N&&e.texSubImage2D(i.TEXTURE_2D,J,0,0,lt.width,lt.height,at,At,lt.data):e.texImage2D(i.TEXTURE_2D,J,dt,lt.width,lt.height,0,at,At,lt.data)}else if(x.isDataArrayTexture)if(Lt){if(Ot&&e.texStorage3D(i.TEXTURE_2D_ARRAY,ct,dt,$.width,$.height,$.depth),N)if(x.layerUpdates.size>0){let J=Ec($.width,$.height,x.format,x.type);for(let ht of x.layerUpdates){let gt=$.data.subarray(ht*J/$.data.BYTES_PER_ELEMENT,(ht+1)*J/$.data.BYTES_PER_ELEMENT);e.texSubImage3D(i.TEXTURE_2D_ARRAY,0,0,0,ht,$.width,$.height,1,at,At,gt)}x.clearLayerUpdates()}else e.texSubImage3D(i.TEXTURE_2D_ARRAY,0,0,0,0,$.width,$.height,$.depth,at,At,$.data)}else e.texImage3D(i.TEXTURE_2D_ARRAY,0,dt,$.width,$.height,$.depth,0,at,At,$.data);else if(x.isData3DTexture)Lt?(Ot&&e.texStorage3D(i.TEXTURE_3D,ct,dt,$.width,$.height,$.depth),N&&e.texSubImage3D(i.TEXTURE_3D,0,0,0,0,$.width,$.height,$.depth,at,At,$.data)):e.texImage3D(i.TEXTURE_3D,0,dt,$.width,$.height,$.depth,0,at,At,$.data);else if(x.isFramebufferTexture){if(Ot)if(Lt)e.texStorage2D(i.TEXTURE_2D,ct,dt,$.width,$.height);else{let J=$.width,ht=$.height;for(let gt=0;gt<ct;gt++)e.texImage2D(i.TEXTURE_2D,gt,dt,J,ht,0,at,At,null),J>>=1,ht>>=1}}else if(x.isHTMLTexture){if("texElementImage2D"in i){let J=i.canvas;if(J.hasAttribute("layoutsubtree")||J.setAttribute("layoutsubtree","true"),$.parentNode!==J){J.appendChild($),f.add(x),J.onpaint=ht=>{let gt=ht.changedElements;for(let it of f)gt.includes(it.image)&&(it.needsUpdate=!0)},J.requestPaint();return}if(i.texElementImage2D.length===3)i.texElementImage2D(i.TEXTURE_2D,i.RGBA8,$);else{let gt=i.RGBA,it=i.RGBA,Rt=i.UNSIGNED_BYTE;i.texElementImage2D(i.TEXTURE_2D,0,gt,it,Rt,$)}i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE)}}else if(Ct.length>0){if(Lt&&Ot){let J=ee(Ct[0]);e.texStorage2D(i.TEXTURE_2D,ct,dt,J.width,J.height)}for(let J=0,ht=Ct.length;J<ht;J++)lt=Ct[J],Lt?N&&e.texSubImage2D(i.TEXTURE_2D,J,0,0,at,At,lt):e.texImage2D(i.TEXTURE_2D,J,dt,at,At,lt);x.generateMipmaps=!1}else if(Lt){if(Ot){let J=ee($);e.texStorage2D(i.TEXTURE_2D,ct,dt,J.width,J.height)}N&&e.texSubImage2D(i.TEXTURE_2D,0,0,0,at,At,$)}else e.texImage2D(i.TEXTURE_2D,0,dt,at,At,$);d(x)&&S(H),ot.__version=rt.version,x.onUpdate&&x.onUpdate(x)}A.__version=x.version}function Ft(A,x,B){if(x.image.length!==6)return;let H=Jt(A,x),q=x.source;e.bindTexture(i.TEXTURE_CUBE_MAP,A.__webglTexture,i.TEXTURE0+B);let rt=n.get(q);if(q.version!==rt.__version||H===!0){e.activeTexture(i.TEXTURE0+B);let ot=Xt.getPrimaries(Xt.workingColorSpace),j=x.colorSpace===si?null:Xt.getPrimaries(x.colorSpace),$=x.colorSpace===si||ot===j?i.NONE:i.BROWSER_DEFAULT_WEBGL;e.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,x.flipY),e.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,x.premultiplyAlpha),e.pixelStorei(i.UNPACK_ALIGNMENT,x.unpackAlignment),e.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,$);let at=x.isCompressedTexture||x.image[0].isCompressedTexture,At=x.image[0]&&x.image[0].isDataTexture,dt=[];for(let it=0;it<6;it++)!at&&!At?dt[it]=m(x.image[it],!0,s.maxCubemapSize):dt[it]=At?x.image[it].image:x.image[it],dt[it]=Be(x,dt[it]);let lt=dt[0],Ct=r.convert(x.format,x.colorSpace),Lt=r.convert(x.type),Ot=y(x.internalFormat,Ct,Lt,x.normalized,x.colorSpace),N=x.isVideoTexture!==!0,ct=rt.__version===void 0||H===!0,J=q.dataReady,ht=w(x,lt);qt(i.TEXTURE_CUBE_MAP,x);let gt;if(at){N&&ct&&e.texStorage2D(i.TEXTURE_CUBE_MAP,ht,Ot,lt.width,lt.height);for(let it=0;it<6;it++){gt=dt[it].mipmaps;for(let Rt=0;Rt<gt.length;Rt++){let bt=gt[Rt];x.format!==xn?Ct!==null?N?J&&e.compressedTexSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+it,Rt,0,0,bt.width,bt.height,Ct,bt.data):e.compressedTexImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+it,Rt,Ot,bt.width,bt.height,0,bt.data):It("WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):N?J&&e.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+it,Rt,0,0,bt.width,bt.height,Ct,Lt,bt.data):e.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+it,Rt,Ot,bt.width,bt.height,0,Ct,Lt,bt.data)}}}else{if(gt=x.mipmaps,N&&ct){gt.length>0&&ht++;let it=ee(dt[0]);e.texStorage2D(i.TEXTURE_CUBE_MAP,ht,Ot,it.width,it.height)}for(let it=0;it<6;it++)if(At){N?J&&e.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+it,0,0,0,dt[it].width,dt[it].height,Ct,Lt,dt[it].data):e.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+it,0,Ot,dt[it].width,dt[it].height,0,Ct,Lt,dt[it].data);for(let Rt=0;Rt<gt.length;Rt++){let le=gt[Rt].image[it].image;N?J&&e.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+it,Rt+1,0,0,le.width,le.height,Ct,Lt,le.data):e.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+it,Rt+1,Ot,le.width,le.height,0,Ct,Lt,le.data)}}else{N?J&&e.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+it,0,0,0,Ct,Lt,dt[it]):e.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+it,0,Ot,Ct,Lt,dt[it]);for(let Rt=0;Rt<gt.length;Rt++){let bt=gt[Rt];N?J&&e.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+it,Rt+1,0,0,Ct,Lt,bt.image[it]):e.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+it,Rt+1,Ot,Ct,Lt,bt.image[it])}}}d(x)&&S(i.TEXTURE_CUBE_MAP),rt.__version=q.version,x.onUpdate&&x.onUpdate(x)}A.__version=x.version}function xt(A,x,B,H,q,rt){let ot=r.convert(B.format,B.colorSpace),j=r.convert(B.type),$=y(B.internalFormat,ot,j,B.normalized,B.colorSpace),at=n.get(x),At=n.get(B);if(At.__renderTarget=x,!at.__hasExternalTextures){let dt=Math.max(1,x.width>>rt),lt=Math.max(1,x.height>>rt);q===i.TEXTURE_3D||q===i.TEXTURE_2D_ARRAY?e.texImage3D(q,rt,$,dt,lt,x.depth,0,ot,j,null):e.texImage2D(q,rt,$,dt,lt,0,ot,j,null)}e.bindFramebuffer(i.FRAMEBUFFER,A),we(x)?a.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER,H,q,At.__webglTexture,0,xe(x)):(q===i.TEXTURE_2D||q>=i.TEXTURE_CUBE_MAP_POSITIVE_X&&q<=i.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&i.framebufferTexture2D(i.FRAMEBUFFER,H,q,At.__webglTexture,rt),e.bindFramebuffer(i.FRAMEBUFFER,null)}function kt(A,x,B){if(i.bindRenderbuffer(i.RENDERBUFFER,A),x.depthBuffer){let H=x.depthTexture,q=H&&H.isDepthTexture?H.type:null,rt=b(x.stencilBuffer,q),ot=x.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT;we(x)?a.renderbufferStorageMultisampleEXT(i.RENDERBUFFER,xe(x),rt,x.width,x.height):B?i.renderbufferStorageMultisample(i.RENDERBUFFER,xe(x),rt,x.width,x.height):i.renderbufferStorage(i.RENDERBUFFER,rt,x.width,x.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,ot,i.RENDERBUFFER,A)}else{let H=x.textures;for(let q=0;q<H.length;q++){let rt=H[q],ot=r.convert(rt.format,rt.colorSpace),j=r.convert(rt.type),$=y(rt.internalFormat,ot,j,rt.normalized,rt.colorSpace);we(x)?a.renderbufferStorageMultisampleEXT(i.RENDERBUFFER,xe(x),$,x.width,x.height):B?i.renderbufferStorageMultisample(i.RENDERBUFFER,xe(x),$,x.width,x.height):i.renderbufferStorage(i.RENDERBUFFER,$,x.width,x.height)}}i.bindRenderbuffer(i.RENDERBUFFER,null)}function Ae(A,x,B){let H=x.isWebGLCubeRenderTarget===!0;if(e.bindFramebuffer(i.FRAMEBUFFER,A),!(x.depthTexture&&x.depthTexture.isDepthTexture))throw new Error("THREE.WebGLTextures: renderTarget.depthTexture must be an instance of THREE.DepthTexture.");let q=n.get(x.depthTexture);if(q.__renderTarget=x,(!q.__webglTexture||x.depthTexture.image.width!==x.width||x.depthTexture.image.height!==x.height)&&(x.depthTexture.image.width=x.width,x.depthTexture.image.height=x.height,x.depthTexture.needsUpdate=!0),H){if(q.__webglInit===void 0&&(q.__webglInit=!0,x.depthTexture.addEventListener("dispose",C)),q.__webglTexture===void 0){q.__webglTexture=i.createTexture(),e.bindTexture(i.TEXTURE_CUBE_MAP,q.__webglTexture),qt(i.TEXTURE_CUBE_MAP,x.depthTexture);let at=r.convert(x.depthTexture.format),At=r.convert(x.depthTexture.type),dt;x.depthTexture.format===kn?dt=i.DEPTH_COMPONENT24:x.depthTexture.format===Ri&&(dt=i.DEPTH24_STENCIL8);for(let lt=0;lt<6;lt++)i.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+lt,0,dt,x.width,x.height,0,at,At,null)}}else et(x.depthTexture,0);let rt=q.__webglTexture,ot=xe(x),j=H?i.TEXTURE_CUBE_MAP_POSITIVE_X+B:i.TEXTURE_2D,$=x.depthTexture.format===Ri?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT;if(x.depthTexture.format===kn)we(x)?a.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER,$,j,rt,0,ot):i.framebufferTexture2D(i.FRAMEBUFFER,$,j,rt,0);else if(x.depthTexture.format===Ri)we(x)?a.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER,$,j,rt,0,ot):i.framebufferTexture2D(i.FRAMEBUFFER,$,j,rt,0);else throw new Error("THREE.WebGLTextures: Unknown depthTexture format.")}function Ht(A){let x=n.get(A),B=A.isWebGLCubeRenderTarget===!0;if(x.__boundDepthTexture!==A.depthTexture){let H=A.depthTexture;if(x.__depthDisposeCallback&&x.__depthDisposeCallback(),H){let q=()=>{delete x.__boundDepthTexture,delete x.__depthDisposeCallback,H.removeEventListener("dispose",q)};H.addEventListener("dispose",q),x.__depthDisposeCallback=q}x.__boundDepthTexture=H}if(A.depthTexture&&!x.__autoAllocateDepthBuffer)if(B)for(let H=0;H<6;H++)Ae(x.__webglFramebuffer[H],A,H);else{let H=A.texture.mipmaps;H&&H.length>0?Ae(x.__webglFramebuffer[0],A,0):Ae(x.__webglFramebuffer,A,0)}else if(B){x.__webglDepthbuffer=[];for(let H=0;H<6;H++)if(e.bindFramebuffer(i.FRAMEBUFFER,x.__webglFramebuffer[H]),x.__webglDepthbuffer[H]===void 0)x.__webglDepthbuffer[H]=i.createRenderbuffer(),kt(x.__webglDepthbuffer[H],A,!1);else{let q=A.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,rt=x.__webglDepthbuffer[H];i.bindRenderbuffer(i.RENDERBUFFER,rt),i.framebufferRenderbuffer(i.FRAMEBUFFER,q,i.RENDERBUFFER,rt)}}else{let H=A.texture.mipmaps;if(H&&H.length>0?e.bindFramebuffer(i.FRAMEBUFFER,x.__webglFramebuffer[0]):e.bindFramebuffer(i.FRAMEBUFFER,x.__webglFramebuffer),x.__webglDepthbuffer===void 0)x.__webglDepthbuffer=i.createRenderbuffer(),kt(x.__webglDepthbuffer,A,!1);else{let q=A.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,rt=x.__webglDepthbuffer;i.bindRenderbuffer(i.RENDERBUFFER,rt),i.framebufferRenderbuffer(i.FRAMEBUFFER,q,i.RENDERBUFFER,rt)}}e.bindFramebuffer(i.FRAMEBUFFER,null)}function jt(A,x,B){let H=n.get(A);x!==void 0&&xt(H.__webglFramebuffer,A,A.texture,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,0),B!==void 0&&Ht(A)}function ae(A){let x=A.texture,B=n.get(A),H=n.get(x);A.addEventListener("dispose",_);let q=A.textures,rt=A.isWebGLCubeRenderTarget===!0,ot=q.length>1;if(ot||(H.__webglTexture===void 0&&(H.__webglTexture=i.createTexture()),H.__version=x.version,o.memory.textures++),rt){B.__webglFramebuffer=[];for(let j=0;j<6;j++)if(x.mipmaps&&x.mipmaps.length>0){B.__webglFramebuffer[j]=[];for(let $=0;$<x.mipmaps.length;$++)B.__webglFramebuffer[j][$]=i.createFramebuffer()}else B.__webglFramebuffer[j]=i.createFramebuffer()}else{if(x.mipmaps&&x.mipmaps.length>0){B.__webglFramebuffer=[];for(let j=0;j<x.mipmaps.length;j++)B.__webglFramebuffer[j]=i.createFramebuffer()}else B.__webglFramebuffer=i.createFramebuffer();if(ot)for(let j=0,$=q.length;j<$;j++){let at=n.get(q[j]);at.__webglTexture===void 0&&(at.__webglTexture=i.createTexture(),o.memory.textures++)}if(A.samples>0&&we(A)===!1){B.__webglMultisampledFramebuffer=i.createFramebuffer(),B.__webglColorRenderbuffer=[],e.bindFramebuffer(i.FRAMEBUFFER,B.__webglMultisampledFramebuffer);for(let j=0;j<q.length;j++){let $=q[j];B.__webglColorRenderbuffer[j]=i.createRenderbuffer(),i.bindRenderbuffer(i.RENDERBUFFER,B.__webglColorRenderbuffer[j]);let at=r.convert($.format,$.colorSpace),At=r.convert($.type),dt=y($.internalFormat,at,At,$.normalized,$.colorSpace,A.isXRRenderTarget===!0),lt=xe(A);i.renderbufferStorageMultisample(i.RENDERBUFFER,lt,dt,A.width,A.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+j,i.RENDERBUFFER,B.__webglColorRenderbuffer[j])}i.bindRenderbuffer(i.RENDERBUFFER,null),A.depthBuffer&&(B.__webglDepthRenderbuffer=i.createRenderbuffer(),kt(B.__webglDepthRenderbuffer,A,!0)),e.bindFramebuffer(i.FRAMEBUFFER,null)}}if(rt){e.bindTexture(i.TEXTURE_CUBE_MAP,H.__webglTexture),qt(i.TEXTURE_CUBE_MAP,x);for(let j=0;j<6;j++)if(x.mipmaps&&x.mipmaps.length>0)for(let $=0;$<x.mipmaps.length;$++)xt(B.__webglFramebuffer[j][$],A,x,i.COLOR_ATTACHMENT0,i.TEXTURE_CUBE_MAP_POSITIVE_X+j,$);else xt(B.__webglFramebuffer[j],A,x,i.COLOR_ATTACHMENT0,i.TEXTURE_CUBE_MAP_POSITIVE_X+j,0);d(x)&&S(i.TEXTURE_CUBE_MAP),e.unbindTexture()}else if(ot){for(let j=0,$=q.length;j<$;j++){let at=q[j],At=n.get(at),dt=i.TEXTURE_2D;(A.isWebGL3DRenderTarget||A.isWebGLArrayRenderTarget)&&(dt=A.isWebGL3DRenderTarget?i.TEXTURE_3D:i.TEXTURE_2D_ARRAY),e.bindTexture(dt,At.__webglTexture),qt(dt,at),xt(B.__webglFramebuffer,A,at,i.COLOR_ATTACHMENT0+j,dt,0),d(at)&&S(dt)}e.unbindTexture()}else{let j=i.TEXTURE_2D;if((A.isWebGL3DRenderTarget||A.isWebGLArrayRenderTarget)&&(j=A.isWebGL3DRenderTarget?i.TEXTURE_3D:i.TEXTURE_2D_ARRAY),e.bindTexture(j,H.__webglTexture),qt(j,x),x.mipmaps&&x.mipmaps.length>0)for(let $=0;$<x.mipmaps.length;$++)xt(B.__webglFramebuffer[$],A,x,i.COLOR_ATTACHMENT0,j,$);else xt(B.__webglFramebuffer,A,x,i.COLOR_ATTACHMENT0,j,0);d(x)&&S(j),e.unbindTexture()}A.depthBuffer&&Ht(A)}function Wt(A){let x=A.textures;for(let B=0,H=x.length;B<H;B++){let q=x[B];if(d(q)){let rt=T(A),ot=n.get(q).__webglTexture;e.bindTexture(rt,ot),S(rt),e.unbindTexture()}}}let fe=[],Ie=[];function Je(A){if(A.samples>0){if(we(A)===!1){let x=A.textures,B=A.width,H=A.height,q=i.COLOR_BUFFER_BIT,rt=A.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,ot=n.get(A),j=x.length>1;if(j)for(let at=0;at<x.length;at++)e.bindFramebuffer(i.FRAMEBUFFER,ot.__webglMultisampledFramebuffer),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+at,i.RENDERBUFFER,null),e.bindFramebuffer(i.FRAMEBUFFER,ot.__webglFramebuffer),i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0+at,i.TEXTURE_2D,null,0);e.bindFramebuffer(i.READ_FRAMEBUFFER,ot.__webglMultisampledFramebuffer);let $=A.texture.mipmaps;$&&$.length>0?e.bindFramebuffer(i.DRAW_FRAMEBUFFER,ot.__webglFramebuffer[0]):e.bindFramebuffer(i.DRAW_FRAMEBUFFER,ot.__webglFramebuffer);for(let at=0;at<x.length;at++){if(A.resolveDepthBuffer&&(A.depthBuffer&&(q|=i.DEPTH_BUFFER_BIT),A.stencilBuffer&&A.resolveStencilBuffer&&(q|=i.STENCIL_BUFFER_BIT)),j){i.framebufferRenderbuffer(i.READ_FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.RENDERBUFFER,ot.__webglColorRenderbuffer[at]);let At=n.get(x[at]).__webglTexture;i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,At,0)}i.blitFramebuffer(0,0,B,H,0,0,B,H,q,i.NEAREST),c===!0&&(fe.length=0,Ie.length=0,fe.push(i.COLOR_ATTACHMENT0+at),A.depthBuffer&&A.storeMultisampledDepthBuffer===!1&&(fe.push(rt),Ie.push(rt),i.invalidateFramebuffer(i.DRAW_FRAMEBUFFER,Ie)),i.invalidateFramebuffer(i.READ_FRAMEBUFFER,fe))}if(e.bindFramebuffer(i.READ_FRAMEBUFFER,null),e.bindFramebuffer(i.DRAW_FRAMEBUFFER,null),j)for(let at=0;at<x.length;at++){e.bindFramebuffer(i.FRAMEBUFFER,ot.__webglMultisampledFramebuffer),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+at,i.RENDERBUFFER,ot.__webglColorRenderbuffer[at]);let At=n.get(x[at]).__webglTexture;e.bindFramebuffer(i.FRAMEBUFFER,ot.__webglFramebuffer),i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0+at,i.TEXTURE_2D,At,0)}e.bindFramebuffer(i.DRAW_FRAMEBUFFER,ot.__webglMultisampledFramebuffer)}else if(A.depthBuffer&&A.storeMultisampledDepthBuffer===!1&&c){let x=A.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT;i.invalidateFramebuffer(i.DRAW_FRAMEBUFFER,[x])}}}function xe(A){return Math.min(s.maxSamples,A.samples)}function we(A){let x=n.get(A);return A.samples>0&&t.has("WEBGL_multisampled_render_to_texture")===!0&&x.__useRenderToTexture!==!1}function U(A){let x=o.render.frame;u.get(A)!==x&&(u.set(A,x),A.update())}function Be(A,x){let B=A.colorSpace,H=A.format,q=A.type;return A.isCompressedTexture===!0||A.isVideoTexture===!0||B!==cr&&B!==si&&(Xt.getTransfer(B)===Qt?(H!==xn||q!==Qe)&&It("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):Dt("WebGLTextures: Unsupported texture color space:",B)),x}function ee(A){return typeof HTMLImageElement<"u"&&A instanceof HTMLImageElement?(l.width=A.naturalWidth||A.width,l.height=A.naturalHeight||A.height):typeof VideoFrame<"u"&&A instanceof VideoFrame?(l.width=A.displayWidth,l.height=A.displayHeight):(l.width=A.width,l.height=A.height),l}this.allocateTextureUnit=G,this.resetTextureUnits=z,this.getTextureUnits=I,this.setTextureUnits=O,this.setTexture2D=et,this.setTexture2DArray=Y,this.setTexture3D=K,this.setTextureCube=nt,this.rebindTextures=jt,this.setupRenderTarget=ae,this.updateRenderTargetMipmap=Wt,this.updateMultisampleRenderTarget=Je,this.setupDepthRenderbuffer=Ht,this.setupFrameBufferTexture=xt,this.useMultisampledRTT=we,this.isReversedDepthBuffer=function(){return e.buffers.depth.getReversed()}}function R_(i,t){function e(n,s=si){let r,o=Xt.getTransfer(s);if(n===Qe)return i.UNSIGNED_BYTE;if(n===fa)return i.UNSIGNED_SHORT_4_4_4_4;if(n===pa)return i.UNSIGNED_SHORT_5_5_5_1;if(n===fc)return i.UNSIGNED_INT_5_9_9_9_REV;if(n===pc)return i.UNSIGNED_INT_10F_11F_11F_REV;if(n===uc)return i.BYTE;if(n===dc)return i.SHORT;if(n===Vs)return i.UNSIGNED_SHORT;if(n===da)return i.INT;if(n===Pn)return i.UNSIGNED_INT;if(n===In)return i.FLOAT;if(n===Ln)return i.HALF_FLOAT;if(n===mc)return i.ALPHA;if(n===gc)return i.RGB;if(n===xn)return i.RGBA;if(n===kn)return i.DEPTH_COMPONENT;if(n===Ri)return i.DEPTH_STENCIL;if(n===_c)return i.RED;if(n===ma)return i.RED_INTEGER;if(n===Pi)return i.RG;if(n===ga)return i.RG_INTEGER;if(n===_a)return i.RGBA_INTEGER;if(n===Dr||n===Nr||n===Ur||n===Fr)if(o===Qt)if(r=t.get("WEBGL_compressed_texture_s3tc_srgb"),r!==null){if(n===Dr)return r.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(n===Nr)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(n===Ur)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(n===Fr)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(r=t.get("WEBGL_compressed_texture_s3tc"),r!==null){if(n===Dr)return r.COMPRESSED_RGB_S3TC_DXT1_EXT;if(n===Nr)return r.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(n===Ur)return r.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(n===Fr)return r.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(n===xa||n===ya||n===va||n===Ma)if(r=t.get("WEBGL_compressed_texture_pvrtc"),r!==null){if(n===xa)return r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(n===ya)return r.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(n===va)return r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(n===Ma)return r.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(n===Sa||n===ba||n===wa||n===Ea||n===Ta||n===Or||n===Aa)if(r=t.get("WEBGL_compressed_texture_etc"),r!==null){if(n===Sa||n===ba)return o===Qt?r.COMPRESSED_SRGB8_ETC2:r.COMPRESSED_RGB8_ETC2;if(n===wa)return o===Qt?r.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:r.COMPRESSED_RGBA8_ETC2_EAC;if(n===Ea)return r.COMPRESSED_R11_EAC;if(n===Ta)return r.COMPRESSED_SIGNED_R11_EAC;if(n===Or)return r.COMPRESSED_RG11_EAC;if(n===Aa)return r.COMPRESSED_SIGNED_RG11_EAC}else return null;if(n===Ca||n===Ra||n===Pa||n===Ia||n===La||n===Da||n===Na||n===Ua||n===Fa||n===Oa||n===Ba||n===za||n===ka||n===Va)if(r=t.get("WEBGL_compressed_texture_astc"),r!==null){if(n===Ca)return o===Qt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:r.COMPRESSED_RGBA_ASTC_4x4_KHR;if(n===Ra)return o===Qt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:r.COMPRESSED_RGBA_ASTC_5x4_KHR;if(n===Pa)return o===Qt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:r.COMPRESSED_RGBA_ASTC_5x5_KHR;if(n===Ia)return o===Qt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:r.COMPRESSED_RGBA_ASTC_6x5_KHR;if(n===La)return o===Qt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:r.COMPRESSED_RGBA_ASTC_6x6_KHR;if(n===Da)return o===Qt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:r.COMPRESSED_RGBA_ASTC_8x5_KHR;if(n===Na)return o===Qt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:r.COMPRESSED_RGBA_ASTC_8x6_KHR;if(n===Ua)return o===Qt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:r.COMPRESSED_RGBA_ASTC_8x8_KHR;if(n===Fa)return o===Qt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:r.COMPRESSED_RGBA_ASTC_10x5_KHR;if(n===Oa)return o===Qt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:r.COMPRESSED_RGBA_ASTC_10x6_KHR;if(n===Ba)return o===Qt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:r.COMPRESSED_RGBA_ASTC_10x8_KHR;if(n===za)return o===Qt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:r.COMPRESSED_RGBA_ASTC_10x10_KHR;if(n===ka)return o===Qt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:r.COMPRESSED_RGBA_ASTC_12x10_KHR;if(n===Va)return o===Qt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:r.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(n===Ha||n===Ga||n===Wa)if(r=t.get("EXT_texture_compression_bptc"),r!==null){if(n===Ha)return o===Qt?r.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:r.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(n===Ga)return r.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(n===Wa)return r.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(n===Xa||n===Ya||n===Br||n===qa)if(r=t.get("EXT_texture_compression_rgtc"),r!==null){if(n===Xa)return r.COMPRESSED_RED_RGTC1_EXT;if(n===Ya)return r.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(n===Br)return r.COMPRESSED_RED_GREEN_RGTC2_EXT;if(n===qa)return r.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return n===Hs?i.UNSIGNED_INT_24_8:i[n]!==void 0?i[n]:null}return{convert:e}}var P_=`+void main() {++ gl_Position = vec4( position, 1.0 );++}`,I_=`+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;++ }++}`,zc=class{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(t,e){if(this.texture===null){let n=new yr(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 un({vertexShader:P_,fragmentShader:I_,uniforms:{depthColor:{value:this.texture},depthWidth:{value:e.z},depthHeight:{value:e.w}}});this.mesh=new ut(new ni(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}},kc=class extends En{constructor(t,e){super();let n=this,s=null,r=1,o=null,a="local-floor",c=1,l=null,u=null,f=null,h=null,p=null,g=null,v=typeof XRWebGLBinding<"u",m=new zc,d={},S=e.getContextAttributes(),T=null,y=null,b=[],w=[],C=new Pt,_=null,E=null,R=new Ue;R.viewport=new me;let L=new Ue;L.viewport=new me;let F=[R,L],z=new aa,I=null,O=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(Z){let Q=b[Z];return Q===void 0&&(Q=new Ds,b[Z]=Q),Q.getTargetRaySpace()},this.getControllerGrip=function(Z){let Q=b[Z];return Q===void 0&&(Q=new Ds,b[Z]=Q),Q.getGripSpace()},this.getHand=function(Z){let Q=b[Z];return Q===void 0&&(Q=new Ds,b[Z]=Q),Q.getHandSpace()};function G(Z){let Q=w.indexOf(Z.inputSource);if(Q===-1)return;let vt=b[Q];vt!==void 0&&(vt.update(Z.inputSource,Z.frame,l||o),vt.dispatchEvent({type:Z.type,data:Z.inputSource}))}function X(){s.removeEventListener("select",G),s.removeEventListener("selectstart",G),s.removeEventListener("selectend",G),s.removeEventListener("squeeze",G),s.removeEventListener("squeezestart",G),s.removeEventListener("squeezeend",G),s.removeEventListener("end",X),s.removeEventListener("inputsourceschange",et);for(let Z=0;Z<b.length;Z++){let Q=w[Z];Q!==null&&(w[Z]=null,b[Z].disconnect(Q))}I=null,O=null,m.reset();for(let Z in d)delete d[Z];if(t.setRenderTarget(T),p=null,h=null,f=null,s=null,y=null,Jt.stop(),n.isPresenting=!1,t.setPixelRatio(_),t.setSize(C.width,C.height,!1),E!==null){let Z=E.camera;Z.fov=E.fov,Z.zoom=E.zoom,Z.updateProjectionMatrix(),E=null}n.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(Z){r=Z,n.isPresenting===!0&&It("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(Z){a=Z,n.isPresenting===!0&&It("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return l||o},this.setReferenceSpace=function(Z){l=Z},this.getBaseLayer=function(){return h!==null?h:p},this.getBinding=function(){return f===null&&v&&(f=new XRWebGLBinding(s,e)),f},this.getFrame=function(){return g},this.getSession=function(){return s},this.setSession=async function(Z){if(s=Z,s!==null){if(T=t.getRenderTarget(),s.addEventListener("select",G),s.addEventListener("selectstart",G),s.addEventListener("selectend",G),s.addEventListener("squeeze",G),s.addEventListener("squeezestart",G),s.addEventListener("squeezeend",G),s.addEventListener("end",X),s.addEventListener("inputsourceschange",et),S.xrCompatible!==!0&&await e.makeXRCompatible(),_=t.getPixelRatio(),t.getSize(C),v&&"createProjectionLayer"in XRWebGLBinding.prototype){let vt=null,Ft=null,xt=null;S.depth&&(xt=S.stencil?e.DEPTH24_STENCIL8:e.DEPTH_COMPONENT24,vt=S.stencil?Ri:kn,Ft=S.stencil?Hs:Pn);let kt={colorFormat:e.RGBA8,depthFormat:xt,scaleFactor:r};f=this.getBinding(),h=f.createProjectionLayer(kt),s.updateRenderState({layers:[h]}),t.setPixelRatio(1),t.setSize(h.textureWidth,h.textureHeight,!1),y=new Ke(h.textureWidth,h.textureHeight,{format:xn,type:Qe,depthTexture:new vi(h.textureWidth,h.textureHeight,Ft,void 0,void 0,void 0,void 0,void 0,void 0,vt),stencilBuffer:S.stencil,colorSpace:t.outputColorSpace,samples:S.antialias?4:0,resolveDepthBuffer:h.ignoreDepthValues===!1,resolveStencilBuffer:h.ignoreDepthValues===!1,storeMultisampledDepthBuffer:h.ignoreDepthValues===!1,storeMultisampledStencilBuffer:h.ignoreDepthValues===!1})}else{let vt={antialias:S.antialias,alpha:!0,depth:S.depth,stencil:S.stencil,framebufferScaleFactor:r};p=new XRWebGLLayer(s,e,vt),s.updateRenderState({baseLayer:p}),t.setPixelRatio(1),t.setSize(p.framebufferWidth,p.framebufferHeight,!1),y=new Ke(p.framebufferWidth,p.framebufferHeight,{format:xn,type:Qe,colorSpace:t.outputColorSpace,stencilBuffer:S.stencil,resolveDepthBuffer:p.ignoreDepthValues===!1,resolveStencilBuffer:p.ignoreDepthValues===!1,storeMultisampledDepthBuffer:p.ignoreDepthValues===!1,storeMultisampledStencilBuffer:p.ignoreDepthValues===!1})}y.isXRRenderTarget=!0,this.setFoveation(c),l=null,o=await s.requestReferenceSpace(a),Jt.setContext(s),Jt.start(),n.isPresenting=!0,n.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(s!==null)return s.environmentBlendMode},this.getDepthTexture=function(){return m.getDepthTexture()};function et(Z){for(let Q=0;Q<Z.removed.length;Q++){let vt=Z.removed[Q],Ft=w.indexOf(vt);Ft>=0&&(w[Ft]=null,b[Ft].disconnect(vt))}for(let Q=0;Q<Z.added.length;Q++){let vt=Z.added[Q],Ft=w.indexOf(vt);if(Ft===-1){for(let kt=0;kt<b.length;kt++)if(kt>=w.length){w.push(vt),Ft=kt;break}else if(w[kt]===null){w[kt]=vt,Ft=kt;break}if(Ft===-1)break}let xt=b[Ft];xt&&xt.connect(vt)}}let Y=new P,K=new P;function nt(Z,Q,vt){Y.setFromMatrixPosition(Q.matrixWorld),K.setFromMatrixPosition(vt.matrixWorld);let Ft=Y.distanceTo(K),xt=Q.projectionMatrix.elements,kt=vt.projectionMatrix.elements,Ae=xt[14]/(xt[10]-1),Ht=xt[14]/(xt[10]+1),jt=(xt[9]+1)/xt[5],ae=(xt[9]-1)/xt[5],Wt=(xt[8]-1)/xt[0],fe=(kt[8]+1)/kt[0],Ie=Ae*Wt,Je=Ae*fe,xe=Ft/(-Wt+fe),we=xe*-Wt;if(Q.matrixWorld.decompose(Z.position,Z.quaternion,Z.scale),Z.translateX(we),Z.translateZ(xe),Z.matrixWorld.compose(Z.position,Z.quaternion,Z.scale),Z.matrixWorldInverse.copy(Z.matrixWorld).invert(),xt[10]===-1)Z.projectionMatrix.copy(Q.projectionMatrix),Z.projectionMatrixInverse.copy(Q.projectionMatrixInverse);else{let U=Ae+xe,Be=Ht+xe,ee=Ie-we,A=Je+(Ft-we),x=jt*Ht/Be*U,B=ae*Ht/Be*U;Z.projectionMatrix.makePerspective(ee,A,x,B,U,Be),Z.projectionMatrixInverse.copy(Z.projectionMatrix).invert()}}function Et(Z,Q){Q===null?Z.matrixWorld.copy(Z.matrix):Z.matrixWorld.multiplyMatrices(Q.matrixWorld,Z.matrix),Z.matrixWorldInverse.copy(Z.matrixWorld).invert()}this.updateCamera=function(Z){if(s===null)return;let Q=Z.near,vt=Z.far;m.texture!==null&&(m.depthNear>0&&(Q=m.depthNear),m.depthFar>0&&(vt=m.depthFar)),z.near=L.near=R.near=Q,z.far=L.far=R.far=vt,(I!==z.near||O!==z.far)&&(s.updateRenderState({depthNear:z.near,depthFar:z.far}),I=z.near,O=z.far),z.layers.mask=Z.layers.mask|6,R.layers.mask=z.layers.mask&-5,L.layers.mask=z.layers.mask&-3;let Ft=Z.parent,xt=z.cameras;Et(z,Ft);for(let kt=0;kt<xt.length;kt++)Et(xt[kt],Ft);xt.length===2?nt(z,R,L):z.projectionMatrix.copy(R.projectionMatrix),E===null&&Z.isPerspectiveCamera&&(E={camera:Z,fov:Z.fov,zoom:Z.zoom}),Tt(Z,z,Ft)};function Tt(Z,Q,vt){vt===null?Z.matrix.copy(Q.matrixWorld):(Z.matrix.copy(vt.matrixWorld),Z.matrix.invert(),Z.matrix.multiply(Q.matrixWorld)),Z.matrix.decompose(Z.position,Z.quaternion,Z.scale),Z.updateMatrixWorld(!0),Z.projectionMatrix.copy(Q.projectionMatrix),Z.projectionMatrixInverse.copy(Q.projectionMatrixInverse),Z.isPerspectiveCamera&&(Z.fov=Ps*2*Math.atan(1/Z.projectionMatrix.elements[5]),Z.zoom=1)}this.getCamera=function(){return z},this.getFoveation=function(){if(!(h===null&&p===null))return c},this.setFoveation=function(Z){c=Z,h!==null&&(h.fixedFoveation=Z),p!==null&&p.fixedFoveation!==void 0&&(p.fixedFoveation=Z)},this.hasDepthSensing=function(){return m.texture!==null},this.getDepthSensingMesh=function(){return m.getMesh(z)},this.getCameraTexture=function(Z){return d[Z]};let te=null;function qt(Z,Q){if(u=Q.getViewerPose(l||o),g=Q,u!==null){let vt=u.views;p!==null&&(t.setRenderTargetFramebuffer(y,p.framebuffer),t.setRenderTarget(y));let Ft=!1;vt.length!==z.cameras.length&&(z.cameras.length=0,Ft=!0);for(let Ht=0;Ht<vt.length;Ht++){let jt=vt[Ht],ae=null;if(p!==null)ae=p.getViewport(jt);else{let fe=f.getViewSubImage(h,jt);ae=fe.viewport,Ht===0&&(t.setRenderTargetTextures(y,fe.colorTexture,fe.depthStencilTexture),t.setRenderTarget(y))}let Wt=F[Ht];Wt===void 0&&(Wt=new Ue,Wt.layers.enable(Ht),Wt.viewport=new me,F[Ht]=Wt),Wt.matrix.fromArray(jt.transform.matrix),Wt.matrix.decompose(Wt.position,Wt.quaternion,Wt.scale),Wt.projectionMatrix.fromArray(jt.projectionMatrix),Wt.projectionMatrixInverse.copy(Wt.projectionMatrix).invert(),Wt.viewport.set(ae.x,ae.y,ae.width,ae.height),Ht===0&&(z.matrix.copy(Wt.matrix),z.matrix.decompose(z.position,z.quaternion,z.scale)),Ft===!0&&z.cameras.push(Wt)}let xt=s.enabledFeatures;if(xt&&xt.includes("depth-sensing")&&s.depthUsage=="gpu-optimized"&&v){f=n.getBinding();let Ht=f.getDepthInformation(vt[0]);Ht&&Ht.isValid&&Ht.texture&&m.init(Ht,s.renderState)}if(xt&&xt.includes("camera-access")&&v){t.state.unbindTexture(),f=n.getBinding();for(let Ht=0;Ht<vt.length;Ht++){let jt=vt[Ht].camera;if(jt){let ae=d[jt];ae||(ae=new yr,d[jt]=ae);let Wt=f.getCameraImage(jt);ae.sourceTexture=Wt}}}}for(let vt=0;vt<b.length;vt++){let Ft=w[vt],xt=b[vt];Ft!==null&&xt!==void 0&&xt.update(Ft,Q,l||o)}te&&te(Z,Q),Q.detectedPlanes&&n.dispatchEvent({type:"planesdetected",data:Q}),g=null}let Jt=new id;Jt.setAnimationLoop(qt),this.setAnimationLoop=function(Z){te=Z},this.dispose=function(){}}},L_=new se,cd=new Ut;cd.set(-1,0,0,0,1,0,0,0,1);function D_(i,t){function e(m,d){m.matrixAutoUpdate===!0&&m.updateMatrix(),d.value.copy(m.matrix)}function n(m,d){d.color.getRGB(m.fogColor.value,Sc(i)),d.isFog?(m.fogNear.value=d.near,m.fogFar.value=d.far):d.isFogExp2&&(m.fogDensity.value=d.density)}function s(m,d,S,T,y){d.isNodeMaterial?d.uniformsNeedUpdate=!1:d.isMeshBasicMaterial?r(m,d):d.isMeshLambertMaterial?(r(m,d),d.envMap&&(m.envMapIntensity.value=d.envMapIntensity)):d.isMeshToonMaterial?(r(m,d),f(m,d)):d.isMeshPhongMaterial?(r(m,d),u(m,d),d.envMap&&(m.envMapIntensity.value=d.envMapIntensity)):d.isMeshStandardMaterial?(r(m,d),h(m,d),d.isMeshPhysicalMaterial&&p(m,d,y)):d.isMeshMatcapMaterial?(r(m,d),g(m,d)):d.isMeshDepthMaterial?r(m,d):d.isMeshDistanceMaterial?(r(m,d),v(m,d)):d.isMeshNormalMaterial?r(m,d):d.isLineBasicMaterial?(o(m,d),d.isLineDashedMaterial&&a(m,d)):d.isPointsMaterial?c(m,d,S,T):d.isSpriteMaterial?l(m,d):d.isShadowMaterial?(m.color.value.copy(d.color),m.opacity.value=d.opacity):d.isShaderMaterial&&(d.uniformsNeedUpdate=!1)}function r(m,d){m.opacity.value=d.opacity,d.color&&m.diffuse.value.copy(d.color),d.emissive&&m.emissive.value.copy(d.emissive).multiplyScalar(d.emissiveIntensity),d.map&&(m.map.value=d.map,e(d.map,m.mapTransform)),d.alphaMap&&(m.alphaMap.value=d.alphaMap,e(d.alphaMap,m.alphaMapTransform)),d.bumpMap&&(m.bumpMap.value=d.bumpMap,e(d.bumpMap,m.bumpMapTransform),m.bumpScale.value=d.bumpScale,d.side===Ze&&(m.bumpScale.value*=-1)),d.normalMap&&(m.normalMap.value=d.normalMap,e(d.normalMap,m.normalMapTransform),m.normalScale.value.copy(d.normalScale),d.side===Ze&&m.normalScale.value.negate()),d.displacementMap&&(m.displacementMap.value=d.displacementMap,e(d.displacementMap,m.displacementMapTransform),m.displacementScale.value=d.displacementScale,m.displacementBias.value=d.displacementBias),d.emissiveMap&&(m.emissiveMap.value=d.emissiveMap,e(d.emissiveMap,m.emissiveMapTransform)),d.specularMap&&(m.specularMap.value=d.specularMap,e(d.specularMap,m.specularMapTransform)),d.alphaTest>0&&(m.alphaTest.value=d.alphaTest);let S=t.get(d),T=S.envMap,y=S.envMapRotation;T&&(m.envMap.value=T,m.envMapRotation.value.setFromMatrix4(L_.makeRotationFromEuler(y)).transpose(),T.isCubeTexture&&T.isRenderTargetTexture===!1&&m.envMapRotation.value.premultiply(cd),m.reflectivity.value=d.reflectivity,m.ior.value=d.ior,m.refractionRatio.value=d.refractionRatio),d.lightMap&&(m.lightMap.value=d.lightMap,m.lightMapIntensity.value=d.lightMapIntensity,e(d.lightMap,m.lightMapTransform)),d.aoMap&&(m.aoMap.value=d.aoMap,m.aoMapIntensity.value=d.aoMapIntensity,e(d.aoMap,m.aoMapTransform))}function o(m,d){m.diffuse.value.copy(d.color),m.opacity.value=d.opacity,d.map&&(m.map.value=d.map,e(d.map,m.mapTransform))}function a(m,d){m.dashSize.value=d.dashSize,m.totalSize.value=d.dashSize+d.gapSize,m.scale.value=d.scale}function c(m,d,S,T){m.diffuse.value.copy(d.color),m.opacity.value=d.opacity,m.size.value=d.size*S,m.scale.value=T*.5,d.map&&(m.map.value=d.map,e(d.map,m.uvTransform)),d.alphaMap&&(m.alphaMap.value=d.alphaMap,e(d.alphaMap,m.alphaMapTransform)),d.alphaTest>0&&(m.alphaTest.value=d.alphaTest)}function l(m,d){m.diffuse.value.copy(d.color),m.opacity.value=d.opacity,m.rotation.value=d.rotation,d.map&&(m.map.value=d.map,e(d.map,m.mapTransform)),d.alphaMap&&(m.alphaMap.value=d.alphaMap,e(d.alphaMap,m.alphaMapTransform)),d.alphaTest>0&&(m.alphaTest.value=d.alphaTest)}function u(m,d){m.specular.value.copy(d.specular),m.shininess.value=Math.max(d.shininess,1e-4)}function f(m,d){d.gradientMap&&(m.gradientMap.value=d.gradientMap)}function h(m,d){m.metalness.value=d.metalness,d.metalnessMap&&(m.metalnessMap.value=d.metalnessMap,e(d.metalnessMap,m.metalnessMapTransform)),m.roughness.value=d.roughness,d.roughnessMap&&(m.roughnessMap.value=d.roughnessMap,e(d.roughnessMap,m.roughnessMapTransform)),d.envMap&&(m.envMapIntensity.value=d.envMapIntensity)}function p(m,d,S){m.ior.value=d.ior,d.sheen>0&&(m.sheenColor.value.copy(d.sheenColor).multiplyScalar(d.sheen),m.sheenRoughness.value=d.sheenRoughness,d.sheenColorMap&&(m.sheenColorMap.value=d.sheenColorMap,e(d.sheenColorMap,m.sheenColorMapTransform)),d.sheenRoughnessMap&&(m.sheenRoughnessMap.value=d.sheenRoughnessMap,e(d.sheenRoughnessMap,m.sheenRoughnessMapTransform))),d.clearcoat>0&&(m.clearcoat.value=d.clearcoat,m.clearcoatRoughness.value=d.clearcoatRoughness,d.clearcoatMap&&(m.clearcoatMap.value=d.clearcoatMap,e(d.clearcoatMap,m.clearcoatMapTransform)),d.clearcoatRoughnessMap&&(m.clearcoatRoughnessMap.value=d.clearcoatRoughnessMap,e(d.clearcoatRoughnessMap,m.clearcoatRoughnessMapTransform)),d.clearcoatNormalMap&&(m.clearcoatNormalMap.value=d.clearcoatNormalMap,e(d.clearcoatNormalMap,m.clearcoatNormalMapTransform),m.clearcoatNormalScale.value.copy(d.clearcoatNormalScale),d.side===Ze&&m.clearcoatNormalScale.value.negate())),d.dispersion>0&&(m.dispersion.value=d.dispersion),d.retroreflectivity>0&&(m.retroreflectivity.value=d.retroreflectivity),d.iridescence>0&&(m.iridescence.value=d.iridescence,m.iridescenceIOR.value=d.iridescenceIOR,m.iridescenceThicknessMinimum.value=d.iridescenceThicknessRange[0],m.iridescenceThicknessMaximum.value=d.iridescenceThicknessRange[1],d.iridescenceMap&&(m.iridescenceMap.value=d.iridescenceMap,e(d.iridescenceMap,m.iridescenceMapTransform)),d.iridescenceThicknessMap&&(m.iridescenceThicknessMap.value=d.iridescenceThicknessMap,e(d.iridescenceThicknessMap,m.iridescenceThicknessMapTransform))),d.transmission>0&&(m.transmission.value=d.transmission,m.transmissionSamplerMap.value=S.texture,m.transmissionSamplerSize.value.set(S.width,S.height),d.transmissionMap&&(m.transmissionMap.value=d.transmissionMap,e(d.transmissionMap,m.transmissionMapTransform)),m.thickness.value=d.thickness,d.thicknessMap&&(m.thicknessMap.value=d.thicknessMap,e(d.thicknessMap,m.thicknessMapTransform)),m.attenuationDistance.value=d.attenuationDistance,m.attenuationColor.value.copy(d.attenuationColor)),d.anisotropy>0&&(m.anisotropyVector.value.set(d.anisotropy*Math.cos(d.anisotropyRotation),d.anisotropy*Math.sin(d.anisotropyRotation)),d.anisotropyMap&&(m.anisotropyMap.value=d.anisotropyMap,e(d.anisotropyMap,m.anisotropyMapTransform))),m.specularIntensity.value=d.specularIntensity,m.specularColor.value.copy(d.specularColor),d.specularColorMap&&(m.specularColorMap.value=d.specularColorMap,e(d.specularColorMap,m.specularColorMapTransform)),d.specularIntensityMap&&(m.specularIntensityMap.value=d.specularIntensityMap,e(d.specularIntensityMap,m.specularIntensityMapTransform))}function g(m,d){d.matcap&&(m.matcap.value=d.matcap)}function v(m,d){let S=t.get(d).light;m.referencePosition.value.setFromMatrixPosition(S.matrixWorld),m.nearDistance.value=S.shadow.camera.near,m.farDistance.value=S.shadow.camera.far}return{refreshFogUniforms:n,refreshMaterialUniforms:s}}function N_(i,t,e,n){let s={},r={},o=[],a=i.getParameter(i.MAX_UNIFORM_BUFFER_BINDINGS);function c(y,b){let w=b.program;n.uniformBlockBinding(y,w)}function l(y,b){let w=s[y.id];w===void 0&&(m(y),w=u(y),s[y.id]=w,y.addEventListener("dispose",S));let C=b.program;n.updateUBOMapping(y,C);let _=t.render.frame;r[y.id]!==_&&(h(y),r[y.id]=_)}function u(y){let b=f();y.__bindingPointIndex=b;let w=i.createBuffer(),C=y.__size,_=y.usage;return i.bindBuffer(i.UNIFORM_BUFFER,w),i.bufferData(i.UNIFORM_BUFFER,C,_),i.bindBuffer(i.UNIFORM_BUFFER,null),i.bindBufferBase(i.UNIFORM_BUFFER,b,w),w}function f(){for(let y=0;y<a;y++)if(o.indexOf(y)===-1)return o.push(y),y;return Dt("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function h(y){let b=s[y.id],w=y.uniforms,C=y.__cache;i.bindBuffer(i.UNIFORM_BUFFER,b);for(let _=0,E=w.length;_<E;_++){let R=w[_];if(Array.isArray(R))for(let L=0,F=R.length;L<F;L++)p(R[L],_,L,C);else p(R,_,0,C)}i.bindBuffer(i.UNIFORM_BUFFER,null)}function p(y,b,w,C){if(v(y,b,w,C)===!0){let _=y.__offset,E=y.value;if(Array.isArray(E)){let R=0;for(let L=0;L<E.length;L++){let F=E[L],z=d(F);g(F,y.__data,R),typeof F!="number"&&typeof F!="boolean"&&!F.isMatrix3&&!ArrayBuffer.isView(F)&&(R+=z.storage/Float32Array.BYTES_PER_ELEMENT)}}else g(E,y.__data,0);i.bufferSubData(i.UNIFORM_BUFFER,_,y.__data)}}function g(y,b,w){typeof y=="number"||typeof y=="boolean"?b[0]=y:y.isMatrix3?(b[0]=y.elements[0],b[1]=y.elements[1],b[2]=y.elements[2],b[3]=0,b[4]=y.elements[3],b[5]=y.elements[4],b[6]=y.elements[5],b[7]=0,b[8]=y.elements[6],b[9]=y.elements[7],b[10]=y.elements[8],b[11]=0):ArrayBuffer.isView(y)?b.set(new y.constructor(y.buffer,y.byteOffset,b.length)):y.toArray(b,w)}function v(y,b,w,C){let _=y.value,E=b+"_"+w;if(C[E]===void 0)return typeof _=="number"||typeof _=="boolean"?C[E]=_:ArrayBuffer.isView(_)?C[E]=_.slice():C[E]=_.clone(),!0;{let R=C[E];if(typeof _=="number"||typeof _=="boolean"){if(R!==_)return C[E]=_,!0}else{if(ArrayBuffer.isView(_))return!0;if(R.equals(_)===!1)return R.copy(_),!0}}return!1}function m(y){let b=y.uniforms,w=0,C=16;for(let E=0,R=b.length;E<R;E++){let L=Array.isArray(b[E])?b[E]:[b[E]];for(let F=0,z=L.length;F<z;F++){let I=L[F],O=Array.isArray(I.value)?I.value:[I.value];for(let G=0,X=O.length;G<X;G++){let et=O[G],Y=d(et),K=w%C,nt=K%Y.boundary,Et=K+nt;w+=nt,Et!==0&&C-Et<Y.storage&&(w+=C-Et),I.__data=new Float32Array(Y.storage/Float32Array.BYTES_PER_ELEMENT),I.__offset=w,w+=Y.storage}}}let _=w%C;return _>0&&(w+=C-_),y.__size=w,y.__cache={},this}function d(y){let b={boundary:0,storage:0};return typeof y=="number"||typeof y=="boolean"?(b.boundary=4,b.storage=4):y.isVector2?(b.boundary=8,b.storage=8):y.isVector3||y.isColor?(b.boundary=16,b.storage=12):y.isVector4?(b.boundary=16,b.storage=16):y.isMatrix3?(b.boundary=48,b.storage=48):y.isMatrix4?(b.boundary=64,b.storage=64):y.isTexture?It("WebGLRenderer: Texture samplers can not be part of an uniforms group."):ArrayBuffer.isView(y)?(b.boundary=16,b.storage=y.byteLength):It("WebGLRenderer: Unsupported uniform value type.",y),b}function S(y){let b=y.target;b.removeEventListener("dispose",S);let w=o.indexOf(b.__bindingPointIndex);o.splice(w,1),i.deleteBuffer(s[b.id]),delete s[b.id],delete r[b.id]}function T(){for(let y in s)i.deleteBuffer(s[y]);o=[],s={},r={}}return{bind:c,update:l,dispose:T}}var U_=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]),Gn=null;function F_(){return Gn===null&&(Gn=new Ho(U_,16,16,Pi,Ln),Gn.name="DFG_LUT",Gn.minFilter=Fe,Gn.magFilter=Fe,Gn.wrapS=zn,Gn.wrapT=zn,Gn.generateMipmaps=!1,Gn.needsUpdate=!0),Gn}var el=class{constructor(t={}){let{canvas:e=Cu(),context:n=null,depth:s=!0,stencil:r=!1,alpha:o=!1,antialias:a=!1,premultipliedAlpha:c=!0,preserveDrawingBuffer:l=!1,powerPreference:u="default",failIfMajorPerformanceCaveat:f=!1,reversedDepthBuffer:h=!1,outputBufferType:p=Qe}=t;this.isWebGLRenderer=!0;let g;if(n!==null){if(typeof WebGLRenderingContext<"u"&&n instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");g=n.getContextAttributes().alpha}else g=o;let v=p,m=new Set([_a,ga,ma]),d=new Set([Qe,Pn,Vs,Hs,fa,pa]),S=new Uint32Array(4),T=new Int32Array(4),y=new P,b=null,w=null,C=[],_=[],E=null;this.domElement=e,this.debug={checkShaderErrors:!0,diagnostics:{keywords:!1},onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=Rn,this.toneMappingExposure=1,this.transmissionResolutionScale=1;let R=this,L=!1,F=null,z=null,I=null,O=null;this._outputColorSpace=qe;let G=0,X=0,et=null,Y=-1,K=null,nt=new me,Et=new me,Tt=null,te=new Nt(0),qt=0,Jt=e.width,Z=e.height,Q=1,vt=null,Ft=null,xt=new me(0,0,Jt,Z),kt=new me(0,0,Jt,Z),Ae=!1,Ht=new Ns,jt=!1,ae=!1,Wt=new se,fe=new P,Ie=new me,Je={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0},xe=!1;function we(){return et===null?Q:1}let U=n;function Be(M,D){return e.getContext(M,D)}let ee,A,x,B,H,q,rt,ot,j,$,at,At,dt,lt,Ct,Lt,Ot,N,ct,J,ht,gt,it;try{let M={alpha:!0,depth:s,stencil:r,antialias:a,premultipliedAlpha:c,preserveDrawingBuffer:l,powerPreference:u,failIfMajorPerformanceCaveat:f};if("setAttribute"in e&&e.setAttribute("data-engine",`three.js r${"186"}`),e.addEventListener("webglcontextlost",le,!1),e.addEventListener("webglcontextrestored",$t,!1),e.addEventListener("webglcontextcreationerror",vn,!1),U===null){let D="webgl2";if(U=Be(D,M),U===null)throw Be(D)?new Error("THREE.WebGLRenderer: Error creating WebGL context with your selected attributes."):new Error("THREE.WebGLRenderer: Error creating WebGL context.")}Rt()}catch(M){throw e.removeEventListener("webglcontextlost",le,!1),e.removeEventListener("webglcontextrestored",$t,!1),e.removeEventListener("webglcontextcreationerror",vn,!1),Dt("WebGLRenderer: "+M.message),M}function Rt(){ee=new Gg(U),ee.init(),ht=new R_(U,ee),A=new Dg(U,ee,t,ht),x=new A_(U,ee),A.reversedDepthBuffer&&h&&x.buffers.depth.setReversed(!0),z=U.createFramebuffer(),I=U.createFramebuffer(),O=U.createFramebuffer(),B=new Yg(U),H=new f_,q=new C_(U,ee,x,H,A,ht,B),rt=new Hg(R),ot=new Zf(U),gt=new Ig(U,ot),j=new Wg(U,ot,B,gt),$=new Zg(U,j,ot,gt,B),N=new qg(U,A,q),Ct=new Ng(H),at=new d_(R,rt,ee,A,gt,Ct),At=new D_(R,H),dt=new m_,lt=new M_(ee),Ot=new Pg(R,rt,x,$,g,c),Lt=new T_(R,$,A),it=new N_(U,B,A,x),ct=new Lg(U,ee,B),J=new Xg(U,ee,B),B.programs=at.programs,R.capabilities=A,R.extensions=ee,R.properties=H,R.renderLists=dt,R.shadowMap=Lt,R.state=x,R.info=B}v!==Qe&&(E=new Jg(v,e.width,e.height,a,s,r));let bt=new kc(R,U);this.xr=bt,this.getContext=function(){return U},this.getContextAttributes=function(){return U.getContextAttributes()},this.forceContextLoss=function(){let M=ee.get("WEBGL_lose_context");M&&M.loseContext()},this.forceContextRestore=function(){let M=ee.get("WEBGL_lose_context");M&&M.restoreContext()},this.getPixelRatio=function(){return Q},this.setPixelRatio=function(M){M!==void 0&&(Q=M,this.setSize(Jt,Z,!1))},this.getSize=function(M){return M.set(Jt,Z)},this.setSize=function(M,D,W=!0){if(bt.isPresenting){It("WebGLRenderer: Can't change size while VR device is presenting.");return}Jt=M,Z=D,e.width=Math.floor(M*Q),e.height=Math.floor(D*Q),W===!0&&(e.style.width=M+"px",e.style.height=D+"px"),E!==null&&E.setSize(e.width,e.height),this.setViewport(0,0,M,D)},this.getDrawingBufferSize=function(M){return M.set(Jt*Q,Z*Q).floor()},this.setDrawingBufferSize=function(M,D,W){Jt=M,Z=D,Q=W,e.width=Math.floor(M*W),e.height=Math.floor(D*W),this.setViewport(0,0,M,D)},this.setEffects=function(M){if(v===Qe){Dt("WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.");return}if(M){for(let D=0;D<M.length;D++)if(M[D].isOutputPass===!0){It("WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.");break}}E.setEffects(M||[])},this.getCurrentViewport=function(M){return M.copy(nt)},this.getViewport=function(M){return M.copy(xt)},this.setViewport=function(M,D,W,k){M.isVector4?xt.set(M.x,M.y,M.z,M.w):xt.set(M,D,W,k),x.viewport(nt.copy(xt).multiplyScalar(Q).round())},this.getScissor=function(M){return M.copy(kt)},this.setScissor=function(M,D,W,k){M.isVector4?kt.set(M.x,M.y,M.z,M.w):kt.set(M,D,W,k),x.scissor(Et.copy(kt).multiplyScalar(Q).round())},this.getScissorTest=function(){return Ae},this.setScissorTest=function(M){x.setScissorTest(Ae=M)},this.setOpaqueSort=function(M){vt=M},this.setTransparentSort=function(M){Ft=M},this.getClearColor=function(M){return M.copy(Ot.getClearColor())},this.setClearColor=function(){Ot.setClearColor(...arguments)},this.getClearAlpha=function(){return Ot.getClearAlpha()},this.setClearAlpha=function(){Ot.setClearAlpha(...arguments)},this.clear=function(M=!0,D=!0,W=!0){let k=0;if(M){let V=!1;if(et!==null){let mt=et.texture.format;V=m.has(mt)}if(V){let mt=et.texture.type,yt=d.has(mt),pt=Ot.getClearColor(),Mt=Ot.getClearAlpha(),wt=pt.r,Bt=pt.g,Gt=pt.b;yt?(S[0]=wt,S[1]=Bt,S[2]=Gt,S[3]=Mt,U.clearBufferuiv(U.COLOR,0,S)):(T[0]=wt,T[1]=Bt,T[2]=Gt,T[3]=Mt,U.clearBufferiv(U.COLOR,0,T))}else k|=U.COLOR_BUFFER_BIT}D&&(k|=U.DEPTH_BUFFER_BIT,this.state.buffers.depth.setMask(!0)),W&&(k|=U.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),k!==0&&U.clear(k)},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.setNodesHandler=function(M){M.setRenderer(this),F=M},this.dispose=function(){e.removeEventListener("webglcontextlost",le,!1),e.removeEventListener("webglcontextrestored",$t,!1),e.removeEventListener("webglcontextcreationerror",vn,!1),Ot.dispose(),dt.dispose(),lt.dispose(),H.dispose(),rt.dispose(),$.dispose(),gt.dispose(),it.dispose(),at.dispose(),bt.dispose(),bt.removeEventListener("sessionstart",dh),bt.removeEventListener("sessionend",fh),Fi.stop()};function le(M){M.preventDefault(),yc("WebGLRenderer: Context Lost."),L=!0}function $t(){yc("WebGLRenderer: Context Restored."),L=!1;let M=B.autoReset,D=Lt.enabled,W=Lt.autoUpdate,k=Lt.needsUpdate,V=Lt.type;Rt(),B.autoReset=M,Lt.enabled=D,Lt.autoUpdate=W,Lt.needsUpdate=k,Lt.type=V}function vn(M){Dt("WebGLRenderer: A WebGL context could not be created. Reason: ",M.statusMessage)}function Fn(M){let D=M.target;D.removeEventListener("dispose",Fn),Gd(D)}function Gd(M){Wd(M),H.remove(M)}function Wd(M){let D=H.get(M).programs;D!==void 0&&(D.forEach(function(W){at.releaseProgram(W)}),M.isShaderMaterial&&at.releaseShaderCache(M))}this.renderBufferDirect=function(M,D,W,k,V,mt){D===null&&(D=Je);let yt=V.isMesh&&V.matrixWorld.determinantAffine()<0,pt=qd(M,D,W,k,V);x.setMaterial(k,yt);let Mt=W.index,wt=1;if(k.wireframe===!0){if(Mt=j.getWireframeAttribute(W),Mt===void 0)return;wt=2}let Bt=W.drawRange,Gt=W.attributes.position,St=Bt.start*wt,Kt=(Bt.start+Bt.count)*wt;mt!==null&&(St=Math.max(St,mt.start*wt),Kt=Math.min(Kt,(mt.start+mt.count)*wt)),Mt!==null?(St=Math.max(St,0),Kt=Math.min(Kt,Mt.count)):Gt!=null&&(St=Math.max(St,0),Kt=Math.min(Kt,Gt.count));let Ee=Kt-St;if(Ee<0||Ee===1/0)return;gt.setup(V,k,pt,W,Mt);let he,re=ct;if(Mt!==null&&(he=ot.get(Mt),re=J,re.setIndex(he)),V.isMesh)k.wireframe===!0?(x.setLineWidth(k.wireframeLinewidth*we()),re.setMode(U.LINES)):re.setMode(U.TRIANGLES);else if(V.isLine){let ze=k.linewidth;ze===void 0&&(ze=1),x.setLineWidth(ze*we()),V.isLineSegments?re.setMode(U.LINES):V.isLineLoop?re.setMode(U.LINE_LOOP):re.setMode(U.LINE_STRIP)}else V.isPoints?re.setMode(U.POINTS):V.isSprite&&re.setMode(U.TRIANGLES);if(V.isBatchedMesh)if(ee.get("WEBGL_multi_draw"))re.renderMultiDraw(V._multiDrawStarts,V._multiDrawCounts,V._multiDrawCount);else{let ze=V._multiDrawStarts,_t=V._multiDrawCounts,Xe=V._multiDrawCount,Zt=Mt?ot.get(Mt).bytesPerElement:1,mn=H.get(k).currentProgram.getUniforms();for(let On=0;On<Xe;On++)mn.setValue(U,"_gl_DrawID",On),re.render(ze[On]/Zt,_t[On])}else if(V.isInstancedMesh)re.renderInstances(St,Ee,V.count);else if(W.isInstancedBufferGeometry){let ze=W._maxInstanceCount!==void 0?W._maxInstanceCount:1/0,_t=Math.min(W.instanceCount,ze);re.renderInstances(St,Ee,_t)}else re.render(St,Ee)};function uh(M,D,W,k){F!==null&&M.isNodeMaterial&&F.setObject(k,M),jt===!0&&Ct.setState(M,W,!1),M.transparent===!0&&M.side===_n&&M.forceSinglePass===!1?(M.side=Ze,M.needsUpdate=!0,so(M,D,k),M.side=Ti,M.needsUpdate=!0,so(M,D,k),M.side=_n):so(M,D,k)}this.compile=function(M,D,W=null){W===null&&(W=M),F!==null&&F.renderStart(M,D,W),w=lt.get(W),w.init(D),_.push(w),W.traverseVisible(function(V){V.isLight&&V.layers.test(D.layers)&&(w.pushLight(V),V.castShadow&&w.pushShadow(V))}),M!==W&&M.traverseVisible(function(V){V.isLight&&V.layers.test(D.layers)&&(w.pushLight(V),V.castShadow&&w.pushShadow(V))}),w.setupLights(),F!==null&&F.updateLights(w.state.lightsArray),ae=this.localClippingEnabled,jt=Ct.init(this.clippingPlanes,ae),jt===!0&&Ct.setGlobalState(this.clippingPlanes,D),F!==null&&Lt.render(w.state.shadowsArray,W,D);let k=new Set;return M.traverse(function(V){if(!(V.isMesh||V.isPoints||V.isLine||V.isSprite))return;let mt=V.material;if(mt)if(Array.isArray(mt))for(let yt=0;yt<mt.length;yt++){let pt=mt[yt];uh(pt,W,D,V),k.add(pt)}else uh(mt,W,D,V),k.add(mt)}),w=_.pop(),F!==null&&F.renderEnd(),k},this.compileAsync=function(M,D,W=null){let k=this.compile(M,D,W);return new Promise(V=>{function mt(){if(k.forEach(function(yt){let Mt=H.get(yt).currentProgram;(Mt===void 0||Mt.isReady())&&k.delete(yt)}),k.size===0){V(M);return}setTimeout(mt,10)}ee.get("KHR_parallel_shader_compile")!==null?mt():setTimeout(mt,10)})};let xl=null;function Xd(M){xl&&xl(M)}function dh(){Fi.stop()}function fh(){Fi.start()}let Fi=new id;Fi.setAnimationLoop(Xd),typeof self<"u"&&Fi.setContext(self),this.setAnimationLoop=function(M){xl=M,bt.setAnimationLoop(M),M===null?Fi.stop():Fi.start()},bt.addEventListener("sessionstart",dh),bt.addEventListener("sessionend",fh),this.render=function(M,D){if(D!==void 0&&D.isCamera!==!0){Dt("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(L===!0)return;F!==null&&F.renderStart(M,D);let W=bt.enabled===!0&&bt.isPresenting===!0,k=E!==null&&(et===null||W)&&E.begin(R,et);if(M.matrixWorldAutoUpdate===!0&&M.updateMatrixWorld(),D.parent===null&&D.matrixWorldAutoUpdate===!0&&D.updateMatrixWorld(),bt.enabled===!0&&bt.isPresenting===!0&&(E===null||E.isCompositing()===!1)&&(bt.cameraAutoUpdate===!0&&bt.updateCamera(D),D=bt.getCamera()),M.isScene===!0&&M.onBeforeRender(R,M,D,et),w=lt.get(M,_.length),w.init(D),w.state.textureUnits=q.getTextureUnits(),_.push(w),Wt.multiplyMatrices(D.projectionMatrix,D.matrixWorldInverse),Ht.setFromProjectionMatrix(Wt,wn,D.reversedDepth),ae=this.localClippingEnabled,jt=Ct.init(this.clippingPlanes,ae),b=dt.get(M,C.length),b.init(),C.push(b),bt.enabled===!0&&bt.isPresenting===!0){let yt=R.xr.getDepthSensingMesh();yt!==null&&yl(yt,D,-1/0,R.sortObjects)}yl(M,D,0,R.sortObjects),b.finish(),F!==null&&F.updateLights(w.state.lightsArray),R.sortObjects===!0&&b.sort(vt,Ft),xe=bt.enabled===!1||bt.isPresenting===!1||bt.hasDepthSensing()===!1,xe&&Ot.addToRenderList(b,M),this.info.render.frame++,this.info.autoReset===!0&&this.info.reset(),jt===!0&&Ct.beginShadows();let V=w.state.shadowsArray;if(Lt.render(V,M,D),jt===!0&&Ct.endShadows(),(k&&E.hasRenderPass())===!1){let yt=b.opaque,pt=b.transmissive;if(w.setupLights(),D.isArrayCamera){let Mt=D.cameras;if(pt.length>0)for(let wt=0,Bt=Mt.length;wt<Bt;wt++){let Gt=Mt[wt];mh(yt,pt,M,Gt)}xe&&Ot.render(M);for(let wt=0,Bt=Mt.length;wt<Bt;wt++){let Gt=Mt[wt];ph(b,M,Gt,Gt.viewport)}}else pt.length>0&&mh(yt,pt,M,D),xe&&Ot.render(M),ph(b,M,D)}et!==null&&X===0&&(q.updateMultisampleRenderTarget(et),q.updateRenderTargetMipmap(et)),k&&E.end(R),M.isScene===!0&&M.onAfterRender(R,M,D),gt.resetDefaultState(),Y=-1,K=null,_.pop(),_.length>0?(w=_[_.length-1],q.setTextureUnits(w.state.textureUnits),jt===!0&&Ct.setGlobalState(R.clippingPlanes,w.state.camera)):w=null,C.pop(),C.length>0?b=C[C.length-1]:b=null,F!==null&&F.renderEnd()};function yl(M,D,W,k){if(M.visible===!1)return;if(M.layers.test(D.layers)){if(M.isGroup)W=M.renderOrder;else if(M.isLOD)M.autoUpdate===!0&&M.update(D);else if(M.isLightProbeGrid)w.pushLightProbeGrid(M);else if(M.isLight)w.pushLight(M),M.castShadow&&w.pushShadow(M);else if(M.isSprite){if(!M.frustumCulled||M.intersectsFrustum(Ht)){k&&Ie.setFromMatrixPosition(M.matrixWorld).applyMatrix4(Wt);let yt=$.update(M),pt=M.material;pt.visible&&b.push(M,yt,pt,W,Ie.z,null,D)}}else if((M.isMesh||M.isLine||M.isPoints)&&(!M.frustumCulled||M.intersectsFrustum(Ht))){let yt=$.update(M),pt=M.material;if(k&&(M.boundingSphere!==void 0?(M.boundingSphere===null&&M.computeBoundingSphere(),Ie.copy(M.boundingSphere.center)):(yt.boundingSphere===null&&yt.computeBoundingSphere(),Ie.copy(yt.boundingSphere.center)),Ie.applyMatrix4(M.matrixWorld).applyMatrix4(Wt)),Array.isArray(pt)){let Mt=yt.groups;for(let wt=0,Bt=Mt.length;wt<Bt;wt++){let Gt=Mt[wt],St=pt[Gt.materialIndex];St&&St.visible&&b.push(M,yt,St,W,Ie.z,Gt,D)}}else pt.visible&&b.push(M,yt,pt,W,Ie.z,null,D)}}let mt=M.children;for(let yt=0,pt=mt.length;yt<pt;yt++)yl(mt[yt],D,W,k)}function ph(M,D,W,k){let{opaque:V,transmissive:mt,transparent:yt}=M;w.setupLightsView(W),jt===!0&&Ct.setGlobalState(R.clippingPlanes,W),k&&x.viewport(nt.copy(k)),V.length>0&&io(V,D,W),mt.length>0&&io(mt,D,W),yt.length>0&&io(yt,D,W),x.buffers.depth.setTest(!0),x.buffers.depth.setMask(!0),x.buffers.color.setMask(!0),x.setPolygonOffset(!1)}function mh(M,D,W,k){if((W.isScene===!0?W.overrideMaterial:null)!==null)return;if(w.state.transmissionRenderTarget[k.id]===void 0){let St=ee.has("EXT_color_buffer_half_float")||ee.has("EXT_color_buffer_float");w.state.transmissionRenderTarget[k.id]=new Ke(1,1,{generateMipmaps:!0,type:St?Ln:Qe,minFilter:Ci,samples:Math.max(4,A.samples),stencilBuffer:r,resolveDepthBuffer:!1,resolveStencilBuffer:!1,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1,colorSpace:Xt.workingColorSpace})}let mt=w.state.transmissionRenderTarget[k.id],yt=k.viewport||nt;mt.setSize(yt.z*R.transmissionResolutionScale,yt.w*R.transmissionResolutionScale);let pt=R.getRenderTarget(),Mt=R.getActiveCubeFace(),wt=R.getActiveMipmapLevel();R.setRenderTarget(mt),R.getClearColor(te),qt=R.getClearAlpha(),qt<1&&R.setClearColor(16777215,.5),R.clear(),xe&&Ot.render(W);let Bt=R.toneMapping;R.toneMapping=Rn;let Gt=k.viewport;if(k.viewport!==void 0&&(k.viewport=void 0),w.setupLightsView(k),jt===!0&&Ct.setGlobalState(R.clippingPlanes,k),io(M,W,k),q.updateMultisampleRenderTarget(mt),q.updateRenderTargetMipmap(mt),ee.has("WEBGL_multisampled_render_to_texture")===!1){let St=!1;for(let Kt=0,Ee=D.length;Kt<Ee;Kt++){let he=D[Kt],{object:re,geometry:ze,material:_t,group:Xe}=he;if(_t.side===_n&&re.layers.test(k.layers)){let Zt=_t.side;_t.side=Ze,_t.needsUpdate=!0,gh(re,W,k,ze,_t,Xe),_t.side=Zt,_t.needsUpdate=!0,St=!0}}St===!0&&(q.updateMultisampleRenderTarget(mt),q.updateRenderTargetMipmap(mt))}R.setRenderTarget(pt,Mt,wt),R.setClearColor(te,qt),Gt!==void 0&&(k.viewport=Gt),R.toneMapping=Bt}function io(M,D,W){let k=D.isScene===!0?D.overrideMaterial:null;for(let V=0,mt=M.length;V<mt;V++){let yt=M[V],{object:pt,geometry:Mt,group:wt}=yt,Bt=yt.material;Bt.allowOverride===!0&&k!==null&&(Bt=k),pt.layers.test(W.layers)&&gh(pt,D,W,Mt,Bt,wt)}}function gh(M,D,W,k,V,mt){F!==null&&V.isNodeMaterial&&F.setObject(M,V),M.onBeforeRender(R,D,W,k,V,mt),M.modelViewMatrix.multiplyMatrices(W.matrixWorldInverse,M.matrixWorld),M.normalMatrix.getNormalMatrix(M.modelViewMatrix),V.onBeforeRender(R,D,W,k,M,mt),V.transparent===!0&&V.side===_n&&V.forceSinglePass===!1?(V.side=Ze,V.needsUpdate=!0,R.renderBufferDirect(W,D,k,V,M,mt),V.side=Ti,V.needsUpdate=!0,R.renderBufferDirect(W,D,k,V,M,mt),V.side=_n):R.renderBufferDirect(W,D,k,V,M,mt),M.onAfterRender(R,D,W,k,V,mt)}function so(M,D,W){D.isScene!==!0&&(D=Je);let k=H.get(M),V=w.state.lights,mt=w.state.shadowsArray,yt=V.state.version,pt=at.getParameters(M,V.state,mt,D,W,w.state.lightProbeGridArray),Mt=at.getProgramCacheKey(pt),wt=k.programs;k.environment=M.isMeshStandardMaterial||M.isMeshLambertMaterial||M.isMeshPhongMaterial?D.environment:null,k.fog=D.fog;let Bt=M.isMeshStandardMaterial||M.isMeshLambertMaterial&&!M.envMap||M.isMeshPhongMaterial&&!M.envMap;k.envMap=rt.get(M.envMap||k.environment,Bt),k.envMapRotation=k.environment!==null&&M.envMap===null?D.environmentRotation:M.envMapRotation,wt===void 0&&(M.addEventListener("dispose",Fn),wt=new Map,k.programs=wt);let Gt=wt.get(Mt);if(Gt!==void 0){if(k.currentProgram===Gt&&k.lightsStateVersion===yt)return xh(M,pt),Gt}else pt.uniforms=at.getUniforms(M),F!==null&&M.isNodeMaterial&&F.build(M,W,pt),M.onBeforeCompile(pt,R),Gt=at.acquireProgram(pt,Mt),wt.set(Mt,Gt),k.uniforms=pt.uniforms;let St=k.uniforms;return(!M.isShaderMaterial&&!M.isRawShaderMaterial||M.clipping===!0)&&(St.clippingPlanes=Ct.uniform),xh(M,pt),k.needsLights=jd(M),k.lightsStateVersion=yt,k.needsLights&&(St.ambientLightColor.value=V.state.ambient,St.lightProbe.value=V.state.probe,St.sunLights.value=V.state.sun,St.sunLightShadows.value=V.state.sunShadow,St.directionalLights.value=V.state.directional,St.directionalLightShadows.value=V.state.directionalShadow,St.spotLights.value=V.state.spot,St.spotLightShadows.value=V.state.spotShadow,St.rectAreaLights.value=V.state.rectArea,St.ltc_1.value=V.state.rectAreaLTC1,St.ltc_2.value=V.state.rectAreaLTC2,St.pointLights.value=V.state.point,St.pointLightShadows.value=V.state.pointShadow,St.hemisphereLights.value=V.state.hemi,St.sunShadowMatrix.value=V.state.sunShadowMatrix,St.sunShadowCascade.value=V.state.sunShadowCascade,St.directionalShadowMatrix.value=V.state.directionalShadowMatrix,St.spotLightMatrix.value=V.state.spotLightMatrix,St.spotLightMap.value=V.state.spotLightMap,St.pointShadowMatrix.value=V.state.pointShadowMatrix),k.lightProbeGrid=w.state.lightProbeGridArray.length>0,k.currentProgram=Gt,k.uniformsList=null,Gt}function _h(M){if(M.uniformsList===null){let D=M.currentProgram.getUniforms();M.uniformsList=Ys.seqWithValue(D.seq,M.uniforms)}return M.uniformsList}function xh(M,D){let W=H.get(M);W.outputColorSpace=D.outputColorSpace,W.batching=D.batching,W.batchingColor=D.batchingColor,W.instancing=D.instancing,W.instancingColor=D.instancingColor,W.instancingMorph=D.instancingMorph,W.skinning=D.skinning,W.morphTargets=D.morphTargets,W.morphNormals=D.morphNormals,W.morphColors=D.morphColors,W.morphTargetsCount=D.morphTargetsCount,W.numClippingPlanes=D.numClippingPlanes,W.numIntersection=D.numClipIntersection,W.vertexAlphas=D.vertexAlphas,W.vertexTangents=D.vertexTangents,W.toneMapping=D.toneMapping}function Yd(M,D){if(M.length===0)return null;if(M.length===1)return M[0].texture!==null?M[0]:null;y.setFromMatrixPosition(D.matrixWorld);for(let W=0,k=M.length;W<k;W++){let V=M[W];if(V.texture!==null&&V.boundingBox.containsPoint(y))return V}return null}function qd(M,D,W,k,V){D.isScene!==!0&&(D=Je),q.resetTextureUnits();let mt=D.fog,yt=k.isMeshStandardMaterial||k.isMeshLambertMaterial||k.isMeshPhongMaterial?D.environment:null,pt=et===null?R.outputColorSpace:et.isXRRenderTarget===!0?et.texture.colorSpace:Xt.workingColorSpace,Mt=k.isMeshStandardMaterial||k.isMeshLambertMaterial&&!k.envMap||k.isMeshPhongMaterial&&!k.envMap,wt=rt.get(k.envMap||yt,Mt),Bt=k.vertexColors===!0&&!!W.attributes.color&&W.attributes.color.itemSize===4,Gt=!!W.attributes.tangent&&(!!k.normalMap||k.anisotropy>0),St=!!W.morphAttributes.position,Kt=!!W.morphAttributes.normal,Ee=!!W.morphAttributes.color,he=Rn;k.toneMapped&&(et===null||et.isXRRenderTarget===!0)&&(he=R.toneMapping);let re=W.morphAttributes.position||W.morphAttributes.normal||W.morphAttributes.color,ze=re!==void 0?re.length:0,_t=H.get(k),Xe=w.state.lights;if(jt===!0&&(ae===!0||M!==K)){let ce=M===K&&k.id===Y;Ct.setState(k,M,ce)}let Zt=!1;k.version===_t.__version?(_t.needsLights&&_t.lightsStateVersion!==Xe.state.version||_t.outputColorSpace!==pt||V.isBatchedMesh&&_t.batching===!1||!V.isBatchedMesh&&_t.batching===!0||V.isBatchedMesh&&_t.batchingColor===!0&&V._colorsTexture===null||V.isBatchedMesh&&_t.batchingColor===!1&&V._colorsTexture!==null||V.isInstancedMesh&&_t.instancing===!1||!V.isInstancedMesh&&_t.instancing===!0||V.isSkinnedMesh&&_t.skinning===!1||!V.isSkinnedMesh&&_t.skinning===!0||V.isInstancedMesh&&_t.instancingColor===!0&&V.instanceColor===null||V.isInstancedMesh&&_t.instancingColor===!1&&V.instanceColor!==null||V.isInstancedMesh&&_t.instancingMorph===!0&&V.morphTexture===null||V.isInstancedMesh&&_t.instancingMorph===!1&&V.morphTexture!==null||_t.envMap!==wt||k.fog===!0&&_t.fog!==mt||_t.numClippingPlanes!==void 0&&(_t.numClippingPlanes!==Ct.numPlanes||_t.numIntersection!==Ct.numIntersection)||_t.vertexAlphas!==Bt||_t.vertexTangents!==Gt||_t.morphTargets!==St||_t.morphNormals!==Kt||_t.morphColors!==Ee||_t.toneMapping!==he||_t.morphTargetsCount!==ze||!!_t.lightProbeGrid!=w.state.lightProbeGridArray.length>0)&&(Zt=!0):(Zt=!0,_t.__version=k.version);let mn=_t.currentProgram;Zt===!0&&(mn=so(k,D,V),F&&k.isNodeMaterial&&F.onUpdateProgram(k,mn,_t));let On=!1,ci=!1,hs=!1,ie=mn.getUniforms(),Se=_t.uniforms;if(x.useProgram(mn.program)&&(On=!0,ci=!0,hs=!0),k.id!==Y&&(Y=k.id,ci=!0),_t.needsLights){let ce=Yd(w.state.lightProbeGridArray,V);_t.lightProbeGrid!==ce&&(_t.lightProbeGrid=ce,ci=!0)}if(On||K!==M){x.buffers.depth.getReversed()&&M.reversedDepth!==!0&&(M._reversedDepth=!0,M.updateProjectionMatrix()),ie.setValue(U,"projectionMatrix",M.projectionMatrix),ie.setValue(U,"viewMatrix",M.matrixWorldInverse);let ui=ie.map.cameraPosition;ui!==void 0&&ui.setValue(U,fe.setFromMatrixPosition(M.matrixWorld)),A.logarithmicDepthBuffer&&ie.setValue(U,"logDepthBufFC",2/(Math.log(M.far+1)/Math.LN2)),(k.isMeshPhongMaterial||k.isMeshToonMaterial||k.isMeshLambertMaterial||k.isMeshBasicMaterial||k.isMeshStandardMaterial||k.isShaderMaterial)&&ie.setValue(U,"isOrthographic",M.isOrthographicCamera===!0),K!==M&&(K=M,ci=!0,hs=!0)}if(_t.needsLights&&(Xe.state.sunShadowMap.length>0&&ie.setValue(U,"sunShadowMap",Xe.state.sunShadowMap,q),Xe.state.directionalShadowMap.length>0&&ie.setValue(U,"directionalShadowMap",Xe.state.directionalShadowMap,q),Xe.state.spotShadowMap.length>0&&ie.setValue(U,"spotShadowMap",Xe.state.spotShadowMap,q),Xe.state.pointShadowMap.length>0&&ie.setValue(U,"pointShadowMap",Xe.state.pointShadowMap,q)),V.isSkinnedMesh){ie.setOptional(U,V,"bindMatrix"),ie.setOptional(U,V,"bindMatrixInverse");let ce=V.skeleton;ce&&(ce.boneTexture===null&&ce.computeBoneTexture(),ie.setValue(U,"boneTexture",ce.boneTexture,q))}V.isBatchedMesh&&(ie.setOptional(U,V,"batchingTexture"),ie.setValue(U,"batchingTexture",V._matricesTexture,q),ie.setOptional(U,V,"batchingIdTexture"),ie.setValue(U,"batchingIdTexture",V._indirectTexture,q),ie.setOptional(U,V,"batchingColorTexture"),V._colorsTexture!==null&&ie.setValue(U,"batchingColorTexture",V._colorsTexture,q));let hi=W.morphAttributes;if((hi.position!==void 0||hi.normal!==void 0||hi.color!==void 0)&&N.update(V,W,mn),(ci||_t.receiveShadow!==V.receiveShadow)&&(_t.receiveShadow=V.receiveShadow,ie.setValue(U,"receiveShadow",V.receiveShadow)),(k.isMeshStandardMaterial||k.isMeshLambertMaterial||k.isMeshPhongMaterial)&&k.envMap===null&&D.environment!==null&&(Se.envMapIntensity.value=D.environmentIntensity),Se.dfgLUT!==void 0&&(Se.dfgLUT.value=F_()),ci){if(ie.setValue(U,"toneMappingExposure",R.toneMappingExposure),_t.needsLights&&Zd(Se,hs),mt&&k.fog===!0&&At.refreshFogUniforms(Se,mt),At.refreshMaterialUniforms(Se,k,Q,Z,w.state.transmissionRenderTarget[M.id]),_t.needsLights&&_t.lightProbeGrid){let ce=_t.lightProbeGrid;Se.probesSH.value=ce.texture,Se.probesMin.value.copy(ce.boundingBox.min),Se.probesMax.value.copy(ce.boundingBox.max),Se.probesResolution.value.copy(ce.resolution)}Ys.upload(U,_h(_t),Se,q)}if(k.isShaderMaterial&&k.uniformsNeedUpdate===!0&&(Ys.upload(U,_h(_t),Se,q),k.uniformsNeedUpdate=!1),k.isSpriteMaterial&&ie.setValue(U,"center",V.center),ie.setValue(U,"modelViewMatrix",V.modelViewMatrix),ie.setValue(U,"normalMatrix",V.normalMatrix),ie.setValue(U,"modelMatrix",V.matrixWorld),k.uniformsGroups!==void 0){let ce=k.uniformsGroups;for(let ui=0,us=ce.length;ui<us;ui++){let vh=ce[ui];it.update(vh,mn),it.bind(vh,mn)}}return mn}function Zd(M,D){M.ambientLightColor.needsUpdate=D,M.lightProbe.needsUpdate=D,M.sunLights.needsUpdate=D,M.sunLightShadows.needsUpdate=D,M.directionalLights.needsUpdate=D,M.directionalLightShadows.needsUpdate=D,M.pointLights.needsUpdate=D,M.pointLightShadows.needsUpdate=D,M.spotLights.needsUpdate=D,M.spotLightShadows.needsUpdate=D,M.rectAreaLights.needsUpdate=D,M.hemisphereLights.needsUpdate=D}function jd(M){return M.isMeshLambertMaterial||M.isMeshToonMaterial||M.isMeshPhongMaterial||M.isMeshStandardMaterial||M.isShadowMaterial||M.isShaderMaterial&&M.lights===!0}this.getActiveCubeFace=function(){return G},this.getActiveMipmapLevel=function(){return X},this.getRenderTarget=function(){return et},this.setRenderTargetTextures=function(M,D,W){let k=H.get(M);k.__autoAllocateDepthBuffer=M.resolveDepthBuffer===!1,k.__autoAllocateDepthBuffer===!1&&(k.__useRenderToTexture=!1),H.get(M.texture).__webglTexture=D,H.get(M.depthTexture).__webglTexture=k.__autoAllocateDepthBuffer?void 0:W,k.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(M,D){let W=H.get(M);W.__webglFramebuffer=D,W.__useDefaultFramebuffer=D===void 0},this.setRenderTarget=function(M,D=0,W=0){et=M,G=D,X=W;let k=null,V=!1,mt=!1;if(M){let pt=H.get(M);if(pt.__useDefaultFramebuffer!==void 0){x.bindFramebuffer(U.FRAMEBUFFER,pt.__webglFramebuffer),nt.copy(M.viewport),Et.copy(M.scissor),Tt=M.scissorTest,x.viewport(nt),x.scissor(Et),x.setScissorTest(Tt),Y=-1;return}else if(pt.__webglFramebuffer===void 0)q.setupRenderTarget(M);else if(pt.__hasExternalTextures)q.rebindTextures(M,H.get(M.texture).__webglTexture,H.get(M.depthTexture).__webglTexture);else if(M.depthBuffer){let Bt=M.depthTexture;if(pt.__boundDepthTexture!==Bt){if(Bt!==null&&H.has(Bt)&&(M.width!==Bt.image.width||M.height!==Bt.image.height))throw new Error("THREE.WebGLRenderer: Attached DepthTexture is initialized to the incorrect size.");q.setupDepthRenderbuffer(M)}}let Mt=M.texture;(Mt.isData3DTexture||Mt.isDataArrayTexture||Mt.isCompressedArrayTexture)&&(mt=!0);let wt=H.get(M).__webglFramebuffer;M.isWebGLCubeRenderTarget?(Array.isArray(wt[D])?k=wt[D][W]:k=wt[D],V=!0):M.samples>0&&q.useMultisampledRTT(M)===!1?k=H.get(M).__webglMultisampledFramebuffer:Array.isArray(wt)?k=wt[W]:k=wt,nt.copy(M.viewport),Et.copy(M.scissor),Tt=M.scissorTest}else nt.copy(xt).multiplyScalar(Q).floor(),Et.copy(kt).multiplyScalar(Q).floor(),Tt=Ae;if(W!==0&&(k=z),x.bindFramebuffer(U.FRAMEBUFFER,k)&&x.drawBuffers(M,k),x.viewport(nt),x.scissor(Et),x.setScissorTest(Tt),V){let pt=H.get(M.texture);U.framebufferTexture2D(U.FRAMEBUFFER,U.COLOR_ATTACHMENT0,U.TEXTURE_CUBE_MAP_POSITIVE_X+D,pt.__webglTexture,W)}else if(mt){let pt=D;for(let Mt=0;Mt<M.textures.length;Mt++){let wt=H.get(M.textures[Mt]);U.framebufferTextureLayer(U.FRAMEBUFFER,U.COLOR_ATTACHMENT0+Mt,wt.__webglTexture,W,pt)}}else if(M!==null&&W!==0){let pt=H.get(M.texture);U.framebufferTexture2D(U.FRAMEBUFFER,U.COLOR_ATTACHMENT0,U.TEXTURE_2D,pt.__webglTexture,W)}Y=-1};function yh(M){let D=H.get(M);return(D.__readFormat!==M.format||D.__readType!==M.type)&&(D.__readFormat=M.format,D.__readType=M.type,D.__formatReadable=A.textureFormatReadable(M.format),D.__typeReadable=A.textureTypeReadable(M.type)),D}this.readRenderTargetPixels=function(M,D,W,k,V,mt,yt,pt=0){if(!(M&&M.isWebGLRenderTarget)){Dt("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let Mt=H.get(M).__webglFramebuffer;if(M.isWebGLCubeRenderTarget&&yt!==void 0&&(Mt=Mt[yt]),Mt){x.bindFramebuffer(U.FRAMEBUFFER,Mt);try{let wt=M.textures[pt],Bt=wt.format,Gt=wt.type;M.textures.length>1&&U.readBuffer(U.COLOR_ATTACHMENT0+pt);let St=yh(wt);if(St.__formatReadable===!1){Dt("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(St.__typeReadable===!1){Dt("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}D>=0&&D<=M.width-k&&W>=0&&W<=M.height-V&&U.readPixels(D,W,k,V,ht.convert(Bt),ht.convert(Gt),mt)}finally{let wt=et!==null?H.get(et).__webglFramebuffer:null;x.bindFramebuffer(U.FRAMEBUFFER,wt)}}},this.readRenderTargetPixelsAsync=async function(M,D,W,k,V,mt,yt,pt=0){if(!(M&&M.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let Mt=H.get(M).__webglFramebuffer;if(M.isWebGLCubeRenderTarget&&yt!==void 0&&(Mt=Mt[yt]),Mt)if(D>=0&&D<=M.width-k&&W>=0&&W<=M.height-V){x.bindFramebuffer(U.FRAMEBUFFER,Mt);let wt=M.textures[pt],Bt=wt.format,Gt=wt.type;M.textures.length>1&&U.readBuffer(U.COLOR_ATTACHMENT0+pt);let St=yh(wt);if(St.__formatReadable===!1)throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(St.__typeReadable===!1)throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");let Kt=U.createBuffer();U.bindBuffer(U.PIXEL_PACK_BUFFER,Kt),U.bufferData(U.PIXEL_PACK_BUFFER,mt.byteLength,U.STREAM_READ),U.readPixels(D,W,k,V,ht.convert(Bt),ht.convert(Gt),0),U.bindBuffer(U.PIXEL_PACK_BUFFER,null);let Ee=et!==null?H.get(et).__webglFramebuffer:null;x.bindFramebuffer(U.FRAMEBUFFER,Ee);let he=U.fenceSync(U.SYNC_GPU_COMMANDS_COMPLETE,0);return U.flush(),await Pu(U,he,4),U.bindBuffer(U.PIXEL_PACK_BUFFER,Kt),U.getBufferSubData(U.PIXEL_PACK_BUFFER,0,mt),U.bindBuffer(U.PIXEL_PACK_BUFFER,null),U.deleteBuffer(Kt),U.deleteSync(he),mt}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(M,D=null,W=0){let k=Math.pow(2,-W),V=Math.floor(M.image.width*k),mt=Math.floor(M.image.height*k),yt=D!==null?D.x:0,pt=D!==null?D.y:0;q.setTexture2D(M,0),U.copyTexSubImage2D(U.TEXTURE_2D,W,0,0,yt,pt,V,mt),x.unbindTexture()},this.copyTextureToTexture=function(M,D,W=null,k=null,V=0,mt=0){let yt,pt,Mt,wt,Bt,Gt,St,Kt,Ee,he=M.isCompressedTexture?M.mipmaps[mt]:M.image;if(W!==null)yt=W.max.x-W.min.x,pt=W.max.y-W.min.y,Mt=W.isBox3?W.max.z-W.min.z:1,wt=W.min.x,Bt=W.min.y,Gt=W.isBox3?W.min.z:0;else{let Se=Math.pow(2,-V);yt=Math.floor(he.width*Se),pt=Math.floor(he.height*Se),M.isDataArrayTexture?Mt=he.depth:M.isData3DTexture?Mt=Math.floor(he.depth*Se):Mt=1,wt=0,Bt=0,Gt=0}k!==null?(St=k.x,Kt=k.y,Ee=k.z):(St=0,Kt=0,Ee=0);let re=ht.convert(D.format),ze=ht.convert(D.type),_t;D.isData3DTexture?(q.setTexture3D(D,0),_t=U.TEXTURE_3D):D.isDataArrayTexture||D.isCompressedArrayTexture?(q.setTexture2DArray(D,0),_t=U.TEXTURE_2D_ARRAY):(q.setTexture2D(D,0),_t=U.TEXTURE_2D),x.activeTexture(U.TEXTURE0),x.pixelStorei(U.UNPACK_FLIP_Y_WEBGL,D.flipY),x.pixelStorei(U.UNPACK_PREMULTIPLY_ALPHA_WEBGL,D.premultiplyAlpha),x.pixelStorei(U.UNPACK_ALIGNMENT,D.unpackAlignment);let Xe=x.getParameter(U.UNPACK_ROW_LENGTH),Zt=x.getParameter(U.UNPACK_IMAGE_HEIGHT),mn=x.getParameter(U.UNPACK_SKIP_PIXELS),On=x.getParameter(U.UNPACK_SKIP_ROWS),ci=x.getParameter(U.UNPACK_SKIP_IMAGES);x.pixelStorei(U.UNPACK_ROW_LENGTH,he.width),x.pixelStorei(U.UNPACK_IMAGE_HEIGHT,he.height),x.pixelStorei(U.UNPACK_SKIP_PIXELS,wt),x.pixelStorei(U.UNPACK_SKIP_ROWS,Bt),x.pixelStorei(U.UNPACK_SKIP_IMAGES,Gt);let hs=M.isDataArrayTexture||M.isData3DTexture,ie=D.isDataArrayTexture||D.isData3DTexture;if(M.isDepthTexture){let Se=H.get(M),hi=H.get(D),ce=H.get(Se.__renderTarget),ui=H.get(hi.__renderTarget);x.bindFramebuffer(U.READ_FRAMEBUFFER,ce.__webglFramebuffer),x.bindFramebuffer(U.DRAW_FRAMEBUFFER,ui.__webglFramebuffer);for(let us=0;us<Mt;us++)hs&&(U.framebufferTextureLayer(U.READ_FRAMEBUFFER,U.COLOR_ATTACHMENT0,H.get(M).__webglTexture,V,Gt+us),U.framebufferTextureLayer(U.DRAW_FRAMEBUFFER,U.COLOR_ATTACHMENT0,H.get(D).__webglTexture,mt,Ee+us)),U.blitFramebuffer(wt,Bt,yt,pt,St,Kt,yt,pt,U.DEPTH_BUFFER_BIT,U.NEAREST);x.bindFramebuffer(U.READ_FRAMEBUFFER,null),x.bindFramebuffer(U.DRAW_FRAMEBUFFER,null)}else if(V!==0||M.isRenderTargetTexture||H.has(M)){let Se=H.get(M),hi=H.get(D);x.bindFramebuffer(U.READ_FRAMEBUFFER,I),x.bindFramebuffer(U.DRAW_FRAMEBUFFER,O);for(let ce=0;ce<Mt;ce++)hs?U.framebufferTextureLayer(U.READ_FRAMEBUFFER,U.COLOR_ATTACHMENT0,Se.__webglTexture,V,Gt+ce):U.framebufferTexture2D(U.READ_FRAMEBUFFER,U.COLOR_ATTACHMENT0,U.TEXTURE_2D,Se.__webglTexture,V),ie?U.framebufferTextureLayer(U.DRAW_FRAMEBUFFER,U.COLOR_ATTACHMENT0,hi.__webglTexture,mt,Ee+ce):U.framebufferTexture2D(U.DRAW_FRAMEBUFFER,U.COLOR_ATTACHMENT0,U.TEXTURE_2D,hi.__webglTexture,mt),V!==0?U.blitFramebuffer(wt,Bt,yt,pt,St,Kt,yt,pt,U.COLOR_BUFFER_BIT,U.NEAREST):ie?U.copyTexSubImage3D(_t,mt,St,Kt,Ee+ce,wt,Bt,yt,pt):U.copyTexSubImage2D(_t,mt,St,Kt,wt,Bt,yt,pt);x.bindFramebuffer(U.READ_FRAMEBUFFER,null),x.bindFramebuffer(U.DRAW_FRAMEBUFFER,null)}else ie?M.isDataTexture||M.isData3DTexture?U.texSubImage3D(_t,mt,St,Kt,Ee,yt,pt,Mt,re,ze,he.data):D.isCompressedArrayTexture?U.compressedTexSubImage3D(_t,mt,St,Kt,Ee,yt,pt,Mt,re,he.data):U.texSubImage3D(_t,mt,St,Kt,Ee,yt,pt,Mt,re,ze,he):M.isDataTexture?U.texSubImage2D(U.TEXTURE_2D,mt,St,Kt,yt,pt,re,ze,he.data):M.isCompressedTexture?U.compressedTexSubImage2D(U.TEXTURE_2D,mt,St,Kt,he.width,he.height,re,he.data):U.texSubImage2D(U.TEXTURE_2D,mt,St,Kt,yt,pt,re,ze,he);x.pixelStorei(U.UNPACK_ROW_LENGTH,Xe),x.pixelStorei(U.UNPACK_IMAGE_HEIGHT,Zt),x.pixelStorei(U.UNPACK_SKIP_PIXELS,mn),x.pixelStorei(U.UNPACK_SKIP_ROWS,On),x.pixelStorei(U.UNPACK_SKIP_IMAGES,ci),mt===0&&D.generateMipmaps&&U.generateMipmap(_t),x.unbindTexture()},this.initRenderTarget=function(M){H.get(M).__webglFramebuffer===void 0&&q.setupRenderTarget(M)},this.initTexture=function(M){M.isCubeTexture?q.setTextureCube(M,0):M.isData3DTexture?q.setTexture3D(M,0):M.isDataArrayTexture||M.isCompressedArrayTexture?q.setTexture2DArray(M,0):q.setTexture2D(M,0),x.unbindTexture()},this.resetState=function(){G=0,X=0,et=null,x.reset(),gt.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return wn}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(t){this._outputColorSpace=t;let e=this.getContext();e.drawingBufferColorSpace=Xt._getDrawingBufferColorSpace(t),e.unpackColorSpace=Xt._getUnpackColorSpace()}};var hd={type:"change"},Hc={type:"start"},dd={type:"end"},sl=new xi,ud=new ln,B_=Math.cos(70*Mc.DEG2RAD),Pe=new P,tn=2*Math.PI,ne={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},Vc=1e-6,rl=class extends Xi{constructor(t,e=null){super(t,e),this.state=ne.NONE,this.target=new P,this.cursor=new P,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.keyRotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:Cn.ROTATE,MIDDLE:Cn.DOLLY,RIGHT:Cn.PAN},this.touches={ONE:Ei.ROTATE,TWO:Ei.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._cursorStyle="auto",this._domElementKeyEvents=null,this._lastPosition=new P,this._lastQuaternion=new pe,this._lastTargetPosition=new P,this._quat=new pe().setFromUnitVectors(t.up,new P(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new Bs,this._sphericalDelta=new Bs,this._scale=1,this._panOffset=new P,this._rotateStart=new Pt,this._rotateEnd=new Pt,this._rotateDelta=new Pt,this._panStart=new Pt,this._panEnd=new Pt,this._panDelta=new Pt,this._dollyStart=new Pt,this._dollyEnd=new Pt,this._dollyDelta=new Pt,this._dollyDirection=new P,this._mouse=new Pt,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=k_.bind(this),this._onPointerDown=z_.bind(this),this._onPointerUp=V_.bind(this),this._onContextMenu=Z_.bind(this),this._onMouseWheel=W_.bind(this),this._onKeyDown=X_.bind(this),this._onTouchStart=Y_.bind(this),this._onTouchMove=q_.bind(this),this._onMouseDown=H_.bind(this),this._onMouseMove=G_.bind(this),this._interceptControlDown=j_.bind(this),this._interceptControlUp=J_.bind(this),this.domElement!==null&&this.connect(this.domElement),this.update()}set cursorStyle(t){this._cursorStyle=t,t==="grab"?this.domElement.style.cursor="grab":this.domElement.style.cursor="auto"}get cursorStyle(){return this._cursorStyle}connect(t){super.connect(t),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerUp),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.getRootNode().addEventListener("keydown",this._interceptControlDown,{passive:!0,capture:!0}),this.domElement.style.touchAction="none"}disconnect(){this.state=ne.NONE,this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerUp),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.stopListenToKeyEvents();let t=this.domElement.getRootNode();t.removeEventListener("keydown",this._interceptControlDown,{capture:!0}),t.removeEventListener("keyup",this._interceptControlUp,{capture:!0}),this._controlActive=!1,this._pointers.length=0,this._pointerPositions={},this.domElement.style.touchAction="",this.domElement.style.cursor="auto"}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents(t){t.addEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=t}stopListenToKeyEvents(){this._domElementKeyEvents!==null&&(this._domElementKeyEvents.removeEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=null)}saveState(){this.target0.copy(this.target),this.position0.copy(this.object.position),this.zoom0=this.object.zoom}reset(){this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.zoom=this.zoom0,this.object.updateProjectionMatrix(),this.dispatchEvent(hd),this.update(),this.state=ne.NONE}pan(t,e){this._pan(t,e),this.update()}dollyIn(t){this._dollyIn(t),this.update()}dollyOut(t){this._dollyOut(t),this.update()}rotateLeft(t){this._rotateLeft(t),this.update()}rotateUp(t){this._rotateUp(t),this.update()}update(t=null){let e=this.object.position;Pe.copy(e).sub(this.target),Pe.applyQuaternion(this._quat),this._spherical.setFromVector3(Pe),this.autoRotate&&this.state===ne.NONE&&this._rotateLeft(this._getAutoRotationAngle(t)),this.enableDamping?(this._spherical.theta+=this._sphericalDelta.theta*this.dampingFactor,this._spherical.phi+=this._sphericalDelta.phi*this.dampingFactor):(this._spherical.theta+=this._sphericalDelta.theta,this._spherical.phi+=this._sphericalDelta.phi);let n=this.minAzimuthAngle,s=this.maxAzimuthAngle;isFinite(n)&&isFinite(s)&&(n<-Math.PI?n+=tn:n>Math.PI&&(n-=tn),s<-Math.PI?s+=tn:s>Math.PI&&(s-=tn),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(Pe.setFromSpherical(this._spherical),Pe.applyQuaternion(this._quatInverse),e.copy(this.target).add(Pe),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=Pe.length();o=this._clampDistance(a*this._scale);let c=a-o;this.object.position.addScaledVector(this._dollyDirection,c),this.object.updateMatrixWorld(),r=!!c}else if(this.object.isOrthographicCamera){let a=new P(this._mouse.x,this._mouse.y,0);a.unproject(this.object);let c=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),r=c!==this.object.zoom;let l=new P(this._mouse.x,this._mouse.y,0);l.unproject(this.object),this.object.position.sub(l).add(a),this.object.updateMatrixWorld(),o=Pe.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):(sl.origin.copy(this.object.position),sl.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(sl.direction))<B_?this.object.lookAt(this.target):(ud.setFromNormalAndCoplanarPoint(this.object.up,this.target),sl.intersectPlane(ud,this.target))))}else if(this.object.isOrthographicCamera){let o=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),o!==this.object.zoom&&(this.object.updateProjectionMatrix(),r=!0)}return this._scale=1,this._performCursorZoom=!1,r||this._lastPosition.distanceToSquared(this.object.position)>Vc||8*(1-this._lastQuaternion.dot(this.object.quaternion))>Vc||this._lastTargetPosition.distanceToSquared(this.target)>Vc?(this.dispatchEvent(hd),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(t){return t!==null?tn/60*this.autoRotateSpeed*t:tn/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){Pe.setFromMatrixColumn(e,0),Pe.multiplyScalar(-t),this._panOffset.add(Pe)}_panUp(t,e){this.screenSpacePanning===!0?Pe.setFromMatrixColumn(e,1):(Pe.setFromMatrixColumn(e,0),Pe.crossVectors(this.object.up,Pe)),Pe.multiplyScalar(t),this._panOffset.add(Pe)}_pan(t,e){let n=this.domElement;if(this.object.isPerspectiveCamera){let s=this.object.position;Pe.copy(s).sub(this.target);let r=Pe.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(tn*this._rotateDelta.x/e.clientHeight),this._rotateUp(tn*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(tn*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(-tn*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(tn*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(-tn*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(tn*this._rotateDelta.x/e.clientHeight),this._rotateUp(tn*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<this._pointers.length;e++)if(this._pointers[e]==t.pointerId){this._pointers.splice(e,1);return}}_isTrackingPointer(t){for(let e=0;e<this._pointers.length;e++)if(this._pointers[e]==t.pointerId)return!0;return!1}_trackPointer(t){let e=this._pointerPositions[t.pointerId];e===void 0&&(e=new Pt,this._pointerPositions[t.pointerId]=e),e.set(t.pageX,t.pageY)}_getSecondPointerPosition(t){let e=t.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[e]}_customWheelEvent(t){let e=t.deltaMode,n={clientX:t.clientX,clientY:t.clientY,deltaY:t.deltaY};switch(e){case 1:n.deltaY*=16;break;case 2:n.deltaY*=100;break}return t.ctrlKey&&!this._controlActive&&(n.deltaY*=10),n}};function z_(i){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(i.pointerId),this.domElement.ownerDocument.addEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(i)&&(this._addPointer(i),i.pointerType==="touch"?this._onTouchStart(i):this._onMouseDown(i),this._cursorStyle==="grab"&&(this.domElement.style.cursor="grabbing")))}function k_(i){this.enabled!==!1&&(i.pointerType==="touch"?this._onTouchMove(i):this._onMouseMove(i))}function V_(i){switch(this._removePointer(i),this._pointers.length){case 0:this.domElement.releasePointerCapture(i.pointerId),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(dd),this.state=ne.NONE,this._cursorStyle==="grab"&&(this.domElement.style.cursor="grab");break;case 1:let t=this._pointers[0],e=this._pointerPositions[t];this._onTouchStart({pointerId:t,pageX:e.x,pageY:e.y});break}}function H_(i){let t;switch(i.button){case 0:t=this.mouseButtons.LEFT;break;case 1:t=this.mouseButtons.MIDDLE;break;case 2:t=this.mouseButtons.RIGHT;break;default:t=-1}switch(t){case Cn.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(i),this.state=ne.DOLLY;break;case Cn.ROTATE:if(i.ctrlKey||i.metaKey||i.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(i),this.state=ne.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(i),this.state=ne.ROTATE}break;case Cn.PAN:if(i.ctrlKey||i.metaKey||i.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(i),this.state=ne.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(i),this.state=ne.PAN}break;default:this.state=ne.NONE}this.state!==ne.NONE&&this.dispatchEvent(Hc)}function G_(i){switch(this.state){case ne.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(i);break;case ne.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(i);break;case ne.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(i);break}}function W_(i){this.enabled===!1||this.enableZoom===!1||this.state!==ne.NONE||(i.preventDefault(),this.dispatchEvent(Hc),this._handleMouseWheel(this._customWheelEvent(i)),this.dispatchEvent(dd))}function X_(i){this.enabled!==!1&&this._handleKeyDown(i)}function Y_(i){switch(this._trackPointer(i),this._pointers.length){case 1:switch(this.touches.ONE){case Ei.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(i),this.state=ne.TOUCH_ROTATE;break;case Ei.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(i),this.state=ne.TOUCH_PAN;break;default:this.state=ne.NONE}break;case 2:switch(this.touches.TWO){case Ei.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(i),this.state=ne.TOUCH_DOLLY_PAN;break;case Ei.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(i),this.state=ne.TOUCH_DOLLY_ROTATE;break;default:this.state=ne.NONE}break;default:this.state=ne.NONE}this.state!==ne.NONE&&this.dispatchEvent(Hc)}function q_(i){switch(this._trackPointer(i),this.state){case ne.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(i),this.update();break;case ne.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(i),this.update();break;case ne.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(i),this.update();break;case ne.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(i),this.update();break;default:this.state=ne.NONE}}function Z_(i){this.enabled!==!1&&i.preventDefault()}function j_(i){i.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function J_(i){i.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}var Ji=new Wi,Me=new P,Ii=new P,_e=new pe,fd={X:new P(1,0,0),Y:new P(0,1,0),Z:new P(0,0,1)},Gc={type:"change"},pd={type:"mouseDown",mode:null},md={type:"mouseUp",mode:null},gd={type:"objectChange"},hl=class extends Xi{constructor(t,e=null){super(void 0,e);let n=new Xc(this);this._root=n;let s=new Yc;this._gizmo=s,n.add(s);let r=new qc;this._plane=r,n.add(r);let o=this;function a(T,y){let b=y;Object.defineProperty(o,T,{get:function(){return b!==void 0?b:y},set:function(w){b!==w&&(b=w,r[T]=w,s[T]=w,o.dispatchEvent({type:T+"-changed",value:w}),o.dispatchEvent(Gc))}}),o[T]=y,r[T]=y,s[T]=y}a("camera",t),a("object",void 0),a("enabled",!0),a("axis",null),a("mode","translate"),a("translationSnap",null),a("rotationSnap",null),a("scaleSnap",null),a("space","world"),a("size",1),this.viewport=null,a("dragging",!1),a("showX",!0),a("showY",!0),a("showZ",!0),a("showXY",!0),a("showYZ",!0),a("showXZ",!0),a("showXYZE",!0),a("showE",!0),a("minX",-1/0),a("maxX",1/0),a("minY",-1/0),a("maxY",1/0),a("minZ",-1/0),a("maxZ",1/0);let c=new P,l=new P,u=new pe,f=new pe,h=new P,p=new pe,g=new P,v=new P,m=new P,d=0,S=new P;a("worldPosition",c),a("worldPositionStart",l),a("worldQuaternion",u),a("worldQuaternionStart",f),a("cameraPosition",h),a("cameraQuaternion",p),a("pointStart",g),a("pointEnd",v),a("rotationAxis",m),a("rotationAngle",d),a("eye",S),this._offset=new P,this._startNorm=new P,this._endNorm=new P,this._cameraScale=new P,this._parentPosition=new P,this._parentQuaternion=new pe,this._parentQuaternionInv=new pe,this._parentScale=new P,this._worldScaleStart=new P,this._worldQuaternionInv=new pe,this._worldScale=new P,this._positionStart=new P,this._quaternionStart=new pe,this._scaleStart=new P,this._getPointer=$_.bind(this),this._onPointerDown=Q_.bind(this),this._onPointerHover=K_.bind(this),this._onPointerMove=tx.bind(this),this._onPointerUp=ex.bind(this),e!==null&&this.connect(e)}connect(t){super.connect(t),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointermove",this._onPointerHover),this.domElement.addEventListener("pointerup",this._onPointerUp),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointermove",this._onPointerHover),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.domElement.style.touchAction=""}getHelper(){return this._root}pointerHover(t){if(this.object===void 0||this.dragging===!0)return;t!==null&&Ji.setFromCamera(t,this.camera);let e=Wc(this._gizmo.picker[this.mode],Ji);e?this.axis=e.object.name:this.axis=null}pointerDown(t){if(!(this.object===void 0||this.dragging===!0||t!=null&&t.button!==0)&&this.axis!==null){t!==null&&Ji.setFromCamera(t,this.camera);let e=Wc(this._plane,Ji,!0);e&&(this.object.updateMatrixWorld(),this.object.parent.updateMatrixWorld(),this._positionStart.copy(this.object.position),this._quaternionStart.copy(this.object.quaternion),this._scaleStart.copy(this.object.scale),this.object.matrixWorld.decompose(this.worldPositionStart,this.worldQuaternionStart,this._worldScaleStart),this.pointStart.copy(e.point).sub(this.worldPositionStart)),this.dragging=!0,pd.mode=this.mode,this.dispatchEvent(pd)}}pointerMove(t){let e=this.axis,n=this.mode,s=this.object,r=this.space;if(n==="scale"?r="local":(e==="E"||e==="XYZE"||e==="XYZ")&&(r="world"),s===void 0||e===null||this.dragging===!1||t!==null&&t.button!==-1)return;t!==null&&Ji.setFromCamera(t,this.camera);let o=Wc(this._plane,Ji,!0);if(o){if(this.pointEnd.copy(o.point).sub(this.worldPositionStart),n==="translate")this._offset.copy(this.pointEnd).sub(this.pointStart),r==="local"&&e!=="XYZ"&&this._offset.applyQuaternion(this._worldQuaternionInv),e.indexOf("X")===-1&&(this._offset.x=0),e.indexOf("Y")===-1&&(this._offset.y=0),e.indexOf("Z")===-1&&(this._offset.z=0),r==="local"&&e!=="XYZ"?this._offset.applyQuaternion(this._quaternionStart).divide(this._parentScale):this._offset.applyQuaternion(this._parentQuaternionInv).divide(this._parentScale),s.position.copy(this._offset).add(this._positionStart),this.translationSnap&&(r==="local"&&(s.position.applyQuaternion(_e.copy(this._quaternionStart).invert()),e.search("X")!==-1&&(s.position.x=Math.round(s.position.x/this.translationSnap)*this.translationSnap),e.search("Y")!==-1&&(s.position.y=Math.round(s.position.y/this.translationSnap)*this.translationSnap),e.search("Z")!==-1&&(s.position.z=Math.round(s.position.z/this.translationSnap)*this.translationSnap),s.position.applyQuaternion(this._quaternionStart)),r==="world"&&(s.getWorldPosition(Me),e.search("X")!==-1&&(Me.x=Math.round(Me.x/this.translationSnap)*this.translationSnap),e.search("Y")!==-1&&(Me.y=Math.round(Me.y/this.translationSnap)*this.translationSnap),e.search("Z")!==-1&&(Me.z=Math.round(Me.z/this.translationSnap)*this.translationSnap),s.position.copy(s.parent.worldToLocal(Me)))),s.position.x=Math.max(this.minX,Math.min(this.maxX,s.position.x)),s.position.y=Math.max(this.minY,Math.min(this.maxY,s.position.y)),s.position.z=Math.max(this.minZ,Math.min(this.maxZ,s.position.z));else if(n==="scale"){if(e.search("XYZ")!==-1){let a=this.pointEnd.length()/this.pointStart.length();this.pointEnd.dot(this.pointStart)<0&&(a*=-1),Ii.set(a,a,a)}else Me.copy(this.pointStart),Ii.copy(this.pointEnd),Me.applyQuaternion(this._worldQuaternionInv),Ii.applyQuaternion(this._worldQuaternionInv),Ii.divide(Me),e.search("X")===-1&&(Ii.x=1),e.search("Y")===-1&&(Ii.y=1),e.search("Z")===-1&&(Ii.z=1);s.scale.copy(this._scaleStart).multiply(Ii),this.scaleSnap&&(e.search("X")!==-1&&(s.scale.x=Math.round(s.scale.x/this.scaleSnap)*this.scaleSnap||this.scaleSnap),e.search("Y")!==-1&&(s.scale.y=Math.round(s.scale.y/this.scaleSnap)*this.scaleSnap||this.scaleSnap),e.search("Z")!==-1&&(s.scale.z=Math.round(s.scale.z/this.scaleSnap)*this.scaleSnap||this.scaleSnap))}else if(n==="rotate"){this._offset.copy(this.pointEnd).sub(this.pointStart);let a=20/this.worldPosition.distanceTo(Me.setFromMatrixPosition(this.camera.matrixWorld)),c=!1;e==="XYZE"?(this.rotationAxis.copy(this._offset).cross(this.eye).normalize(),this.rotationAngle=this._offset.dot(Me.copy(this.rotationAxis).cross(this.eye))*a):(e==="X"||e==="Y"||e==="Z")&&(this.rotationAxis.copy(fd[e]),Me.copy(fd[e]),r==="local"&&Me.applyQuaternion(this.worldQuaternion),Me.cross(this.eye),Me.length()===0?c=!0:this.rotationAngle=this._offset.dot(Me.normalize())*a),(e==="E"||c)&&(this.rotationAxis.copy(this.eye),this.rotationAngle=this.pointEnd.angleTo(this.pointStart),this._startNorm.copy(this.pointStart).normalize(),this._endNorm.copy(this.pointEnd).normalize(),this.rotationAngle*=this._endNorm.cross(this._startNorm).dot(this.eye)<0?1:-1),this.rotationSnap&&(this.rotationAngle=Math.round(this.rotationAngle/this.rotationSnap)*this.rotationSnap),r==="local"&&e!=="E"&&e!=="XYZE"?(s.quaternion.copy(this._quaternionStart),s.quaternion.multiply(_e.setFromAxisAngle(this.rotationAxis,this.rotationAngle)).normalize()):(this.rotationAxis.applyQuaternion(this._parentQuaternionInv),s.quaternion.copy(_e.setFromAxisAngle(this.rotationAxis,this.rotationAngle)),s.quaternion.multiply(this._quaternionStart).normalize())}this.dispatchEvent(Gc),this.dispatchEvent(gd)}}pointerUp(t){t!==null&&t.button!==0||(this.dragging&&this.axis!==null&&(md.mode=this.mode,this.dispatchEvent(md)),this.dragging=!1,this.axis=null)}dispose(){this.disconnect(),this._root.dispose()}attach(t){return this.object=t,this._root.visible=!0,this}detach(){return this.object=void 0,this.axis=null,this._root.visible=!1,this}reset(){this.enabled&&this.dragging&&(this.object.position.copy(this._positionStart),this.object.quaternion.copy(this._quaternionStart),this.object.scale.copy(this._scaleStart),this.dispatchEvent(Gc),this.dispatchEvent(gd),this.pointStart.copy(this.pointEnd))}getRaycaster(){return Ji}getMode(){return this.mode}setMode(t){this.mode=t}setTranslationSnap(t){this.translationSnap=t}setRotationSnap(t){this.rotationSnap=t}setScaleSnap(t){this.scaleSnap=t}setSize(t){this.size=t}setSpace(t){this.space=t}setColors(t,e,n,s){let r=this._gizmo.materialLib;r.xAxis.color.set(t),r.yAxis.color.set(e),r.zAxis.color.set(n),r.active.color.set(s),r.xAxisTransparent.color.set(t),r.yAxisTransparent.color.set(e),r.zAxisTransparent.color.set(n),r.activeTransparent.color.set(s),r.xAxis._color&&r.xAxis._color.set(t),r.yAxis._color&&r.yAxis._color.set(e),r.zAxis._color&&r.zAxis._color.set(n),r.active._color&&r.active._color.set(s),r.xAxisTransparent._color&&r.xAxisTransparent._color.set(t),r.yAxisTransparent._color&&r.yAxisTransparent._color.set(e),r.zAxisTransparent._color&&r.zAxisTransparent._color.set(n),r.activeTransparent._color&&r.activeTransparent._color.set(s)}};function $_(i){if(this.domElement.ownerDocument.pointerLockElement)return{x:0,y:0,button:i.button};{let t=this.domElement.getBoundingClientRect(),e=this.viewport,n,s,r,o;return e!==null?(n=e.x,s=t.height-e.y-e.w,r=e.z,o=e.w):(n=0,s=0,r=t.width,o=t.height),{x:(i.clientX-t.left-n)/r*2-1,y:-(i.clientY-t.top-s)/o*2+1,button:i.button}}}function K_(i){if(this.enabled)switch(i.pointerType){case"mouse":case"pen":this.pointerHover(this._getPointer(i));break}}function Q_(i){this.enabled&&(document.pointerLockElement||this.domElement.setPointerCapture(i.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.pointerHover(this._getPointer(i)),this.pointerDown(this._getPointer(i)))}function tx(i){this.enabled&&this.pointerMove(this._getPointer(i))}function ex(i){this.enabled&&(this.domElement.releasePointerCapture(i.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.pointerUp(this._getPointer(i)))}function Wc(i,t,e){let n=t.intersectObject(i,!0);for(let s=0;s<n.length;s++)if(n[s].object.visible||e)return n[s];return!1}var ol=new Tn,oe=new P(0,1,0),_d=new P(0,0,0),xd=new se,al=new pe,cl=new pe,Xn=new P,ul=new se,Wr=new P(1,0,0),$i=new P(0,1,0),Xr=new P(0,0,1),ll=new P,Hr=new P,Gr=new P,Xc=class extends ye{constructor(t){super(),this.isTransformControlsRoot=!0,this.controls=t,this.visible=!1}updateMatrixWorld(t){let e=this.controls;e.object!==void 0&&(e.object.updateMatrixWorld(),e.object.parent===null?console.error("TransformControls: The attached 3D object must be a part of the scene graph."):e.object.parent.matrixWorld.decompose(e._parentPosition,e._parentQuaternion,e._parentScale),e.object.matrixWorld.decompose(e.worldPosition,e.worldQuaternion,e._worldScale),e._parentQuaternionInv.copy(e._parentQuaternion).invert(),e._worldQuaternionInv.copy(e.worldQuaternion).invert()),e.camera.updateMatrixWorld(),e.camera.matrixWorld.decompose(e.cameraPosition,e.cameraQuaternion,e._cameraScale),e.camera.isOrthographicCamera?e.camera.getWorldDirection(e.eye).negate():e.eye.copy(e.cameraPosition).sub(e.worldPosition).normalize(),this.parent&&(ul.copy(this.parent.matrixWorld).invert(),ul.decompose(this.position,this.quaternion,this.scale)),super.updateMatrixWorld(t)}dispose(){this.traverse(function(t){t.geometry&&t.geometry.dispose(),t.material&&t.material.dispose()})}},Yc=class extends ye{constructor(){super(),this.isTransformControlsGizmo=!0,this.type="TransformControlsGizmo";let t=new Vn({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),e=new yi({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),n=t.clone();n.opacity=.15;let s=e.clone();s.opacity=.5;let r=t.clone();r.color.setHex(16711680);let o=t.clone();o.color.setHex(65280);let a=t.clone();a.color.setHex(255);let c=t.clone();c.color.setHex(16711680),c.opacity=.5;let l=t.clone();l.color.setHex(65280),l.opacity=.5;let u=t.clone();u.color.setHex(255),u.opacity=.5;let f=t.clone();f.opacity=.25;let h=t.clone();h.color.setHex(16776960),h.opacity=.25;let p=t.clone();p.color.setHex(16776960);let g=t.clone();g.color.setHex(7895160),this.materialLib={xAxis:r,yAxis:o,zAxis:a,active:p,xAxisTransparent:c,yAxisTransparent:l,zAxisTransparent:u,activeTransparent:h};let v=new Ne(0,.04,.1,12);v.translate(0,.05,0);let m=new ge(.08,.08,.08);m.translate(0,.04,0);let d=new ve;d.setAttribute("position",new Yt([0,0,0,1,0,0],3));let S=new Ne(.0075,.0075,.5,3);S.translate(0,.25,0);function T(O,G){let X=new ii(O,.0075,3,64,G*Math.PI*2);return X.rotateY(Math.PI/2),X.rotateX(Math.PI/2),X}function y(){let O=new ve;return O.setAttribute("position",new Yt([0,0,0,1,1,1],3)),O}let b={X:[[new ut(v,r),[.5,0,0],[0,0,-Math.PI/2]],[new ut(v,r),[-.5,0,0],[0,0,Math.PI/2]],[new ut(S,r),[0,0,0],[0,0,-Math.PI/2]]],Y:[[new ut(v,o),[0,.5,0]],[new ut(v,o),[0,-.5,0],[Math.PI,0,0]],[new ut(S,o)]],Z:[[new ut(v,a),[0,0,.5],[Math.PI/2,0,0]],[new ut(v,a),[0,0,-.5],[-Math.PI/2,0,0]],[new ut(S,a),null,[Math.PI/2,0,0]]],XYZ:[[new ut(new Mi(.1,0),f),[0,0,0]]],XY:[[new ut(new ge(.15,.15,.01),u),[.15,.15,0]]],YZ:[[new ut(new ge(.15,.15,.01),c),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new ut(new ge(.15,.15,.01),l),[.15,0,.15],[-Math.PI/2,0,0]]]},w={X:[[new ut(new Ne(.2,0,.6,4),n),[.3,0,0],[0,0,-Math.PI/2]],[new ut(new Ne(.2,0,.6,4),n),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new ut(new Ne(.2,0,.6,4),n),[0,.3,0]],[new ut(new Ne(.2,0,.6,4),n),[0,-.3,0],[0,0,Math.PI]]],Z:[[new ut(new Ne(.2,0,.6,4),n),[0,0,.3],[Math.PI/2,0,0]],[new ut(new Ne(.2,0,.6,4),n),[0,0,-.3],[-Math.PI/2,0,0]]],XYZ:[[new ut(new Mi(.2,0),n)]],XY:[[new ut(new ge(.2,.2,.01),n),[.15,.15,0]]],YZ:[[new ut(new ge(.2,.2,.01),n),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new ut(new ge(.2,.2,.01),n),[.15,0,.15],[-Math.PI/2,0,0]]]},C={START:[[new ut(new Mi(.01,2),s),null,null,null,"helper"]],END:[[new ut(new Mi(.01,2),s),null,null,null,"helper"]],DELTA:[[new hn(y(),s),null,null,null,"helper"]],X:[[new hn(d,s),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new hn(d,s),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new hn(d,s),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]},_={XYZE:[[new ut(T(.5,1),g),null,[0,Math.PI/2,0]]],X:[[new ut(T(.5,.5),r)]],Y:[[new ut(T(.5,.5),o),null,[0,0,-Math.PI/2]]],Z:[[new ut(T(.5,.5),a),null,[0,Math.PI/2,0]]],E:[[new ut(T(.75,1),h),null,[0,Math.PI/2,0]]]},E={AXIS:[[new hn(d,s),[-1e3,0,0],null,[1e6,1,1],"helper"]]},R={XYZE:[[new ut(new vr(.25,10,8),n)]],X:[[new ut(new ii(.5,.1,4,24),n),[0,0,0],[0,-Math.PI/2,-Math.PI/2]]],Y:[[new ut(new ii(.5,.1,4,24),n),[0,0,0],[Math.PI/2,0,0]]],Z:[[new ut(new ii(.5,.1,4,24),n),[0,0,0],[0,0,-Math.PI/2]]],E:[[new ut(new ii(.75,.1,2,24),n)]]},L={X:[[new ut(m,r),[.5,0,0],[0,0,-Math.PI/2]],[new ut(S,r),[0,0,0],[0,0,-Math.PI/2]],[new ut(m,r),[-.5,0,0],[0,0,Math.PI/2]]],Y:[[new ut(m,o),[0,.5,0]],[new ut(S,o)],[new ut(m,o),[0,-.5,0],[0,0,Math.PI]]],Z:[[new ut(m,a),[0,0,.5],[Math.PI/2,0,0]],[new ut(S,a),[0,0,0],[Math.PI/2,0,0]],[new ut(m,a),[0,0,-.5],[-Math.PI/2,0,0]]],XY:[[new ut(new ge(.15,.15,.01),u),[.15,.15,0]]],YZ:[[new ut(new ge(.15,.15,.01),c),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new ut(new ge(.15,.15,.01),l),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new ut(new ge(.1,.1,.1),f)]]},F={X:[[new ut(new Ne(.2,0,.6,4),n),[.3,0,0],[0,0,-Math.PI/2]],[new ut(new Ne(.2,0,.6,4),n),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new ut(new Ne(.2,0,.6,4),n),[0,.3,0]],[new ut(new Ne(.2,0,.6,4),n),[0,-.3,0],[0,0,Math.PI]]],Z:[[new ut(new Ne(.2,0,.6,4),n),[0,0,.3],[Math.PI/2,0,0]],[new ut(new Ne(.2,0,.6,4),n),[0,0,-.3],[-Math.PI/2,0,0]]],XY:[[new ut(new ge(.2,.2,.01),n),[.15,.15,0]]],YZ:[[new ut(new ge(.2,.2,.01),n),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new ut(new ge(.2,.2,.01),n),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new ut(new ge(.2,.2,.2),n),[0,0,0]]]},z={X:[[new hn(d,s),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new hn(d,s),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new hn(d,s),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]};function I(O){let G=new ye;for(let X in O)for(let et=O[X].length;et--;){let Y=O[X][et][0].clone(),K=O[X][et][1],nt=O[X][et][2],Et=O[X][et][3],Tt=O[X][et][4];Y.name=X,Y.tag=Tt,K&&Y.position.set(K[0],K[1],K[2]),nt&&Y.rotation.set(nt[0],nt[1],nt[2]),Et&&Y.scale.set(Et[0],Et[1],Et[2]),Y.updateMatrix();let te=Y.geometry.clone();te.applyMatrix4(Y.matrix),Y.geometry=te,Y.renderOrder=1/0,Y.position.set(0,0,0),Y.rotation.set(0,0,0),Y.scale.set(1,1,1),G.add(Y)}return G}this.gizmo={},this.picker={},this.helper={},this.add(this.gizmo.translate=I(b)),this.add(this.gizmo.rotate=I(_)),this.add(this.gizmo.scale=I(L)),this.add(this.picker.translate=I(w)),this.add(this.picker.rotate=I(R)),this.add(this.picker.scale=I(F)),this.add(this.helper.translate=I(C)),this.add(this.helper.rotate=I(E)),this.add(this.helper.scale=I(z)),this.picker.translate.visible=!1,this.picker.rotate.visible=!1,this.picker.scale.visible=!1}updateMatrixWorld(t){let n=(this.mode==="scale"?"local":this.space)==="local"?this.worldQuaternion:cl;this.gizmo.translate.visible=this.mode==="translate",this.gizmo.rotate.visible=this.mode==="rotate",this.gizmo.scale.visible=this.mode==="scale",this.helper.translate.visible=this.mode==="translate",this.helper.rotate.visible=this.mode==="rotate",this.helper.scale.visible=this.mode==="scale";let s=[];s=s.concat(this.picker[this.mode].children),s=s.concat(this.gizmo[this.mode].children),s=s.concat(this.helper[this.mode].children);for(let r=0;r<s.length;r++){let o=s[r];o.visible=!0,o.rotation.set(0,0,0),o.position.copy(this.worldPosition);let a;if(this.camera.isOrthographicCamera?a=(this.camera.top-this.camera.bottom)/this.camera.zoom:a=this.worldPosition.distanceTo(this.cameraPosition)*Math.min(1.9*Math.tan(Math.PI*this.camera.fov/360)/this.camera.zoom,7),o.scale.set(1,1,1).multiplyScalar(a*this.size/4),o.tag==="helper"){o.visible=!1,o.name==="AXIS"?(o.visible=!!this.axis,this.axis==="X"&&(_e.setFromEuler(ol.set(0,0,0)),o.quaternion.copy(n).multiply(_e),Math.abs(oe.copy(Wr).applyQuaternion(n).dot(this.eye))>.9&&(o.visible=!1)),this.axis==="Y"&&(_e.setFromEuler(ol.set(0,0,Math.PI/2)),o.quaternion.copy(n).multiply(_e),Math.abs(oe.copy($i).applyQuaternion(n).dot(this.eye))>.9&&(o.visible=!1)),this.axis==="Z"&&(_e.setFromEuler(ol.set(0,Math.PI/2,0)),o.quaternion.copy(n).multiply(_e),Math.abs(oe.copy(Xr).applyQuaternion(n).dot(this.eye))>.9&&(o.visible=!1)),this.axis==="XYZE"&&(_e.setFromEuler(ol.set(0,Math.PI/2,0)),oe.copy(this.rotationAxis),o.quaternion.setFromRotationMatrix(xd.lookAt(_d,oe,$i)),o.quaternion.multiply(_e),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),Me.set(1e-10,1e-10,1e-10).add(this.worldPositionStart).sub(this.worldPosition).multiplyScalar(-1),Me.applyQuaternion(this.worldQuaternionStart.clone().invert()),o.scale.copy(Me),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(oe.copy(Wr).applyQuaternion(n).dot(this.eye))>.99&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="Y"&&Math.abs(oe.copy($i).applyQuaternion(n).dot(this.eye))>.99&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="Z"&&Math.abs(oe.copy(Xr).applyQuaternion(n).dot(this.eye))>.99&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="XY"&&Math.abs(oe.copy(Xr).applyQuaternion(n).dot(this.eye))<.2&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="YZ"&&Math.abs(oe.copy(Wr).applyQuaternion(n).dot(this.eye))<.2&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1),o.name==="XZ"&&Math.abs(oe.copy($i).applyQuaternion(n).dot(this.eye))<.2&&(o.scale.set(1e-10,1e-10,1e-10),o.visible=!1)):this.mode==="rotate"&&(al.copy(n),oe.copy(this.eye).applyQuaternion(_e.copy(n).invert()),o.name.search("E")!==-1&&o.quaternion.setFromRotationMatrix(xd.lookAt(this.eye,_d,$i)),o.name==="X"&&(_e.setFromAxisAngle(Wr,Math.atan2(-oe.y,oe.z)),_e.multiplyQuaternions(al,_e),o.quaternion.copy(_e)),o.name==="Y"&&(_e.setFromAxisAngle($i,Math.atan2(oe.x,oe.z)),_e.multiplyQuaternions(al,_e),o.quaternion.copy(_e)),o.name==="Z"&&(_e.setFromAxisAngle(Xr,Math.atan2(oe.y,oe.x)),_e.multiplyQuaternions(al,_e),o.quaternion.copy(_e))),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.visible=o.visible&&(o.name.indexOf("XY")===-1||this.showXY),o.visible=o.visible&&(o.name.indexOf("YZ")===-1||this.showYZ),o.visible=o.visible&&(o.name.indexOf("XZ")===-1||this.showXZ),o.visible=o.visible&&(o.name!=="E"||this.showE),o.visible=o.visible&&(o.name!=="XYZE"||this.showXYZE),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(c){return o.name===c})&&(o.material.color.copy(this.materialLib.active.color),o.material.opacity=1))}super.updateMatrixWorld(t)}},qc=class extends ut{constructor(){super(new ni(1e5,1e5,2,2),new Vn({visible:!1,wireframe:!0,side:_n,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"),ll.copy(Wr).applyQuaternion(e==="local"?this.worldQuaternion:cl),Hr.copy($i).applyQuaternion(e==="local"?this.worldQuaternion:cl),Gr.copy(Xr).applyQuaternion(e==="local"?this.worldQuaternion:cl),oe.copy(Hr),this.mode){case"translate":case"scale":switch(this.axis){case"X":oe.copy(this.eye).cross(ll),Xn.copy(ll).cross(oe);break;case"Y":oe.copy(this.eye).cross(Hr),Xn.copy(Hr).cross(oe);break;case"Z":oe.copy(this.eye).cross(Gr),Xn.copy(Gr).cross(oe);break;case"XY":Xn.copy(Gr);break;case"YZ":Xn.copy(ll);break;case"XZ":oe.copy(Gr),Xn.copy(Hr);break;case"XYZ":case"E":Xn.set(0,0,0);break}break;default:Xn.set(0,0,0)}Xn.length()===0?this.quaternion.copy(this.cameraQuaternion):(ul.lookAt(Me.set(0,0,0),Xn,oe),this.quaternion.setFromRotationMatrix(ul)),super.updateMatrixWorld(t)}};var nx="tidelands/2",qn=i=>structuredClone(i),Dn=i=>String(i??"").replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t]),Zc=/^[a-z][a-z0-9_-]{0,63}$/,ri=(i,t,e)=>Number.isFinite(i)&&i>=t&&i<=e,Yr=(i,t,e,n)=>Array.isArray(i)&&i.length===t&&i.every(s=>Number.isInteger(s)&&ri(s,e,n)),Ki=(i,t)=>typeof i=="string"&&i.length<=t;function Li(i){return i.rotation%2?[i.size[2],i.size[1],i.size[0]]:[...i.size]}function yd(i,t,e,n){let[s,,r]=i.size,[o,a]=[[t,n],[r-1-n,t],[s-1-t,r-1-n],[n,s-1-t]][i.rotation];return[o+i.origin[0],e+i.origin[1],a+i.origin[2]]}function ix(i,t,e,n){t-=i.origin[0],e-=i.origin[1],n-=i.origin[2];let[s,,r]=i.size,[o,a]=[[t,n],[n,r-1-t],[s-1-t,r-1-n],[s-1-n,t]][i.rotation];return[o,e,a]}function Nn(i){let t=qn(i);if(!t||t.spec!==nx||!Zc.test(t.id))throw new Error("Open a Tidelands world project.");if(!Ki(t.title,120)||!t.title.trim()||!Ki(t.brief,12e3))throw new Error("Give the world a title and brief.");if(!Yr(t.size,3,4,128)||t.size.reduce((l,u)=>l*u,1)>1048576)throw new Error("Use a world up to 128 cells per side and one million cells.");if(!ri(t.unit,.01,10))throw new Error("Set the real size of one voxel in meters.");if(!Array.isArray(t.materials)||!t.materials.length||t.materials.length>255)throw new Error("Use 1\u2013255 materials.");let e=new Set([0]);for(let l of t.materials){if(!Number.isInteger(l.id)||!ri(l.id,1,255)||e.has(l.id)||!Ki(l.name,80)||!/^#[0-9a-f]{6}$/i.test(l.color))throw new Error("Materials need unique numeric IDs, names and hex colors.");if(e.add(l.id),l.solid??=!0,l.opacity??=1,l.emission??=0,typeof l.solid!="boolean"||!ri(l.opacity,.05,1)||!ri(l.emission,0,1))throw new Error("Invalid material solidity, opacity or emission.")}if(!Array.isArray(t.objects)||!t.objects.length||t.objects.length>128)throw new Error("Use 1\u2013128 named objects.");let n=0,s=0,r=0,o=new Set;for(let l of t.objects){if(!Zc.test(l.id)||o.has(l.id)||!Ki(l.name,120))throw new Error("Give every object a unique ID and a name.");if(o.add(l.id),!Yr(l.size,3,1,128)||!Yr(l.origin,3,0,127))throw new Error("Object dimensions and origins must be whole voxel coordinates.");if(l.rotation??=0,l.hidden??=!1,l.locked??=!1,l.edits??=[],!Number.isInteger(l.rotation)||!ri(l.rotation,0,3)||typeof l.hidden!="boolean"||typeof l.locked!="boolean")throw new Error("Invalid object orientation or visibility.");if(Li(l).some((u,f)=>l.origin[f]+u>t.size[f]))throw new Error(`${l.name} extends outside the world. Move it inward or enlarge the world.`);if(n+=l.size.reduce((u,f)=>u*f,1),!Array.isArray(l.boxes)||!Array.isArray(l.edits))throw new Error("Object geometry needs boxes and cell edits.");for(let u of l.boxes){if(!Yr(u,7,0,255)||u.slice(3,6).some(f=>!f)||u.slice(0,3).some((f,h)=>f+u[h+3]>l.size[h])||!e.has(u[6]))throw new Error(`Invalid voxel box in ${l.name}.`);s+=u[3]*u[4]*u[5],r++}for(let u of l.edits){if(!Yr(u,4,0,255)||u.slice(0,3).some((f,h)=>f>=l.size[h])||!e.has(u[3]))throw new Error(`Invalid cell edit in ${l.name}.`);r++}}if(n>8388608||s>16777216||r>1e5)throw new Error("This project exceeds the editing budget. Split it into related worlds or assets.");let a=l=>Array.isArray(l)&&l.length===3&&l.every((u,f)=>ri(u,0,t.size[f]));if(!t.spawn||!a(t.spawn.position)||!ri(t.spawn.yaw,-Math.PI*2,Math.PI*2))throw new Error("Place the visitor start inside the world.");if(t.stops??=[],!Array.isArray(t.stops)||t.stops.length>30)throw new Error("Use at most 30 tour stops.");let c=new Set;for(let l of t.stops){if(!Zc.test(l.id)||c.has(l.id)||!Ki(l.name,120)||!Ki(l.description,2e3)||!a(l.position))throw new Error("Invalid tour stop.");c.add(l.id)}if(t.notes??="",!Ki(t.notes,12e3))throw new Error("Keep project notes under 12,000 characters.");if(t.light??=.32,!ri(t.light,0,1))throw new Error("Choose a light setting from 0 to 1.");if(JSON.stringify(t).length>12e6)throw new Error("Keep the editable project under 12 MB.");return t}function jc(i){let[t,e,n]=i.size,s=new Uint8Array(t*e*n),r=(o,a,c)=>(a*n+c)*t+o;for(let[o,a,c,l,u,f,h]of i.boxes)for(let p=a;p<a+u;p++)for(let g=c;g<c+f;g++)s.fill(h,r(o,p,g),r(o+l,p,g));for(let[o,a,c,l]of i.edits)s[r(o,a,c)]=l;return s}function Qi(i){let[t,e,n]=i.size,s=new Uint8Array(t*e*n),r=new Uint16Array(s.length),o=new Map(i.materials.map(l=>[l.id,l])),a=0,c=new Map;for(let l=0;l<i.objects.length;l++){let u=i.objects[l];if(u.hidden)continue;let f=jc(u),[h,p,g]=u.size;for(let v=0;v<p;v++)for(let m=0;m<g;m++)for(let d=0;d<h;d++){let S=f[(v*g+m)*h+d];if(!S)continue;let[T,y,b]=yd(u,d,v,m),w=(y*n+b)*t+T;s[w]=S,r[w]=l+1}}for(let l of s)l&&(a++,c.set(l,(c.get(l)||0)+1));return{size:i.size,unit:i.unit,cells:s,owners:r,materials:o,count:a,counts:c}}function vd(i,t,e,n){let[s,r,o]=i.size;return t<0||e<0||n<0||t>=s||e>=r||n>=o?0:i.cells[(e*o+n)*s+t]}function Jc(i,t,e,n){return i.materials.get(vd(i,t,e,n))?.solid??!1}var sx=[{n:[1,0,0],v:[[1,0,0],[1,1,0],[1,1,1],[1,0,1]]},{n:[-1,0,0],v:[[0,0,1],[0,1,1],[0,1,0],[0,0,0]]},{n:[0,1,0],v:[[0,1,1],[1,1,1],[1,1,0],[0,1,0]]},{n:[0,-1,0],v:[[0,0,0],[1,0,0],[1,0,1],[0,0,1]]},{n:[0,0,1],v:[[1,0,1],[1,1,1],[0,1,1],[0,0,1]]},{n:[0,0,-1],v:[[0,0,0],[0,1,0],[1,1,0],[1,0,0]]}];function Zs(i,t=Qi(i)){let e=new Map,[n,s,r]=t.size,o=0;for(let a=0;a<s;a++)for(let c=0;c<r;c++)for(let l=0;l<n;l++){let u=(a*r+c)*n+l,f=t.cells[u];if(!f)continue;let h=t.owners[u]-1,p=h+":"+f;for(let g of sx){let v=vd(t,l+g.n[0],a+g.n[1],c+g.n[2]);if(v&&(v===f||t.materials.get(v).opacity===1))continue;if(++o>35e4)throw new Error("This scene has too many exposed voxel faces. Simplify scattered geometry or split it into assets.");e.has(p)||e.set(p,{object:h,material:f,positions:[],normals:[],indices:[]});let m=e.get(p),d=m.positions.length/3;for(let S of g.v)m.positions.push(l+S[0],a+S[1],c+S[2]),m.normals.push(...g.n);m.indices.push(d,d+1,d+2,d,d+2,d+3)}}return[...e.values()]}function Md(i,t,e,n,s=0,{existingOnly:r=!1}={}){let o=i.objects.find(f=>f.id===t);if(!o||o.locked)throw new Error("Choose an unlocked object to sculpt.");if(o.rotation){let f=jc(o),[h,p,g]=o.size,v=Li(o),m=new Uint8Array(v.reduce((d,S)=>d*S,1));for(let d=0;d<p;d++)for(let S=0;S<g;S++)for(let T=0;T<h;T++){let[y,b,w]=yd(o,T,d,S).map((C,_)=>C-o.origin[_]);m[(b*v[2]+w)*v[0]+y]=f[(d*g+S)*h+T]}o.size=v,o.rotation=0,o.boxes=$c(m,v),o.edits=[]}if(n!==0&&!r){let f=e.map((p,g)=>Math.max(-o.origin[g],Math.min(0,p-o.origin[g]-s))),h=e.map((p,g)=>Math.min(i.size[g]-o.origin[g],Math.max(o.size[g],p-o.origin[g]+s+1)));for(let p of o.boxes)for(let g=0;g<3;g++)p[g]-=f[g];for(let p of o.edits)for(let g=0;g<3;g++)p[g]-=f[g];o.size=h.map((p,g)=>p-f[g]),o.origin=o.origin.map((p,g)=>p+f[g])}let a=ix(o,...e),c=new Map(o.edits.map(f=>[f.slice(0,3).join(","),f])),l=r?jc(o):null,u=0;for(let f=-s;f<=s;f++)for(let h=-s;h<=s;h++)for(let p=-s;p<=s;p++){let g=[a[0]+p,a[1]+f,a[2]+h];g.some((v,m)=>v<0||v>=o.size[m])||l&&!l[(g[1]*o.size[2]+g[2])*o.size[0]+g[0]]||(c.set(g.join(","),[...g,n]),u++)}return o.edits=[...c.values()],u}function $c(i,t){let[e,n,s]=t,r=[];for(let o=0;o<n;o++)for(let a=0;a<s;a++)for(let c=0;c<e;){let l=i[(o*s+a)*e+c],u=c++;for(;c<e&&i[(o*s+a)*e+c]===l;)c++;l&&r.push([u,o,a,c-u,1,1,l])}return r}function Yn(i,t){let[e,n,s]=t,r=.26/i.unit,o=1.7/i.unit;if(e-r<0||s-r<0||e+r>i.size[0]||s+r>i.size[2]||n<0||n+o>i.size[1])return!1;for(let a=Math.floor(e-r);a<=Math.floor(e+r-1e-4);a++)for(let c=Math.floor(n+1e-4);c<=Math.floor(n+o-1e-4);c++)for(let l=Math.floor(s-r);l<=Math.floor(s+r-1e-4);l++)if(Jc(i,a,c,l))return!1;return!0}function Sd(i,t,e,n=1/60){let s=qn(t),r=Math.sin(s.yaw)*(e.forward||0)-Math.cos(s.yaw)*(e.right||0),o=Math.cos(s.yaw)*(e.forward||0)+Math.sin(s.yaw)*(e.right||0),a=(e.sprint?5:3)/i.unit,c=Math.max(1,Math.hypot(r,o));r=r/c*a*n,o=o/c*a*n;for(let[u,f]of[[0,r],[2,o]]){let h=[...s.position];if(h[u]+=f,Yn(i,h))s.position=h;else if(s.grounded){for(let p=1;p<=Math.ceil(.45/i.unit)&&(h[1]=Math.floor(s.position[1])+p,!(h[1]-s.position[1]>.45/i.unit+.001));p++)if(Yn(i,h)){s.position=h;break}}}e.jump&&s.grounded&&(s.velocity=4/i.unit),s.velocity=(s.velocity||0)-9.8/i.unit*n;let l=[...s.position];if(l[1]+=s.velocity*n,Yn(i,l))s.position=l,s.grounded=!1;else{let u=0,f=1,h=l[1]-s.position[1];for(let p=0;p<12;p++){let g=(u+f)/2,v=[...s.position];v[1]+=h*g,Yn(i,v)?u=g:f=g}s.position[1]+=h*u,s.velocity<0&&(s.grounded=!0),s.velocity=0}return s}function dl(i,t=Qi(i)){let e=[],n=1.7/i.unit,s=.45/i.unit,r=1/i.unit,[o,a,c]=i.size,l=new Map;for(let m=0;m<c;m++)for(let d=0;d<o;d++){let S=[];for(let T=1;T+n<=a;T++)Jc(t,d,T-1,m)&&!Jc(t,d,T,m)&&Yn(t,[d+.5,T,m+.5])&&S.push(T);S.length&&l.set(d+","+m,S)}let u=i.spawn.position.map(Math.floor),f=l.get(u[0]+","+u[2])??[],h=f.find(m=>Math.abs(m-i.spawn.position[1])<.2);(h===void 0||!Yn(t,i.spawn.position))&&e.push("The visitor start has no clear standing space.");let p=new Set,g=[];h!==void 0&&(u[1]=h,g.push(u),p.add(u.join(",")));for(let m=0;m<g.length;m++){let[d,S,T]=g[m];for(let[y,b]of[[1,0],[-1,0],[0,1],[0,-1]])for(let w of l.get(d+y+","+(T+b))??[]){if(w-S>s+.001||S-w>r+.001)continue;let C=[d+y,w,T+b],_=C.join(",");p.has(_)||(p.add(_),g.push(C))}}let v=i.stops.map(m=>{let[d,S,T]=m.position,y=[...l.get(Math.floor(d)+","+Math.floor(T))??[]].some(b=>Math.abs(S-b)<.2&&p.has([Math.floor(d),b,Math.floor(T)].join(",")));return y||e.push(`${m.name} is not connected to the visitor start by the checked walking routes.`),{id:m.id,reachable:y}});return{spawnClear:h!==void 0&&Yn(t,i.spawn.position),reachableStandingCells:p.size,stops:v,issues:e,method:"Cardinal standing-cell search with visitor clearance, 0.45 m steps and 1 m descents; actual browser walking still required."}}var Kc=new TextEncoder,rx=new TextDecoder,qr=i=>{let t=new Uint8Array(i.reduce((n,s)=>n+s.length,0)),e=0;for(let n of i)t.set(n,e),e+=n.length;return t},bd=(i,t=0)=>{let e=new Uint8Array(Math.ceil(i.length/4)*4);return e.fill(t),e.set(i),e},ox=i=>i<=.04045?i/12.92:((i+.055)/1.055)**2.4;function wd(i,t){let e=qn(i),n=e.objects.find(r=>r.id===t);if(!n)throw new Error("Choose an object to export.");let s=[...n.origin];return n.origin=[0,0,0],n.hidden=!1,e.objects=[n],e.size=n.rotation%2?[n.size[2],n.size[1],n.size[0]]:[...n.size],e.title=n.name,e.id=n.id,e.stops=[],e.spawn={position:[0,0,0],yaw:0},{project:e,origin:s}}function Zr(i,{objectId:t}={}){let e=Nn(i);t&&(e=wd(e,t).project);let n=[],s=[],r=[],o=[],a=[],c=e.materials.map(S=>{let T=[1,3,5].map(y=>ox(parseInt(S.color.slice(y,y+2),16)/255));return{name:S.name,pbrMetallicRoughness:{baseColorFactor:[...T,S.opacity],metallicFactor:0,roughnessFactor:.9},...S.opacity<1?{alphaMode:"BLEND",doubleSided:!0}:{},...S.emission?{emissiveFactor:T.map(y=>y*S.emission)}:{},extras:{voxelMaterialId:S.id,solid:S.solid}}}),l=0;function u(S,T,y,b,w,C){let _=bd(new Uint8Array(S.buffer));return s.push({buffer:0,byteOffset:l,byteLength:S.byteLength,target:b}),n.push(_),l+=_.length,r.push({bufferView:s.length-1,componentType:y,count:S.length/(T==="VEC3"?3:1),type:T,...w?{min:w,max:C}:{}}),r.length-1}let f=new Map;for(let S of Zs(e)){let T=e.objects[S.object],y=new Float32Array(S.positions.map((_,E)=>(_-T.origin[E%3])*e.unit)),b=[1/0,1/0,1/0],w=[-1/0,-1/0,-1/0];for(let _=0;_<y.length;_++)b[_%3]=Math.min(b[_%3],y[_]),w[_%3]=Math.max(w[_%3],y[_]);let C={attributes:{POSITION:u(y,"VEC3",5126,34962,b,w),NORMAL:u(new Float32Array(S.normals),"VEC3",5126,34962)},indices:u(new Uint32Array(S.indices),"SCALAR",5125,34963),material:e.materials.findIndex(_=>_.id===S.material)};f.has(S.object)||f.set(S.object,[]),f.get(S.object).push(C)}if(!f.size)throw new Error("There is no visible geometry to export.");for(let[S,T]of f){let y=e.objects[S];a.push({name:y.name,primitives:T}),o.push({name:y.name,mesh:a.length-1,translation:y.origin.map(b=>b*e.unit),extras:{objectId:y.id,locked:y.locked}})}let h=qr(n),p=bd(Kc.encode(JSON.stringify({asset:{version:"2.0",generator:"Tidelands / Voxel Worlds"},scene:0,scenes:[{name:e.title,nodes:o.map((S,T)=>T)}],nodes:o,meshes:a,materials:c,buffers:[{byteLength:h.length}],bufferViews:s,accessors:r,extras:{brief:e.brief,voxelSizeMeters:e.unit}})),32),g=new Uint8Array(20),v=new DataView(g.buffer),m=new Uint8Array(8),d=new DataView(m.buffer);return v.setUint32(0,1179937895,!0),v.setUint32(4,2,!0),v.setUint32(8,28+p.length+h.length,!0),v.setUint32(12,p.length,!0),v.setUint32(16,1313821514,!0),d.setUint32(0,h.length,!0),d.setUint32(4,5130562,!0),qr([g,p,m,h])}function fl(i,t,e=new Uint8Array){let n=new Uint8Array(12),s=new DataView(n.buffer);return n.set(Kc.encode(i)),s.setUint32(4,t.length,!0),s.setUint32(8,e.length,!0),qr([n,t,e])}function jr(i,{objectId:t}={}){let e=Nn(i);t&&(e=wd(e,t).project);let n=Qi(e),[s,r,o]=n.size,a=new Uint8Array(12),c=new DataView(a.buffer),l=new Uint8Array(4+n.count*4),u=new DataView(l.buffer),f=new Uint8Array(1024);c.setUint32(0,s,!0),c.setUint32(4,o,!0),c.setUint32(8,r,!0),u.setUint32(0,n.count,!0);let h=4;for(let g=0;g<r;g++)for(let v=0;v<o;v++)for(let m=0;m<s;m++){let d=n.cells[(g*o+v)*s+m];d&&(l.set([m,o-1-v,g,d],h),h+=4)}for(let g of e.materials)f.set([...[1,3,5].map(v=>parseInt(g.color.slice(v,v+2),16)),Math.round(g.opacity*255)],(g.id-1)*4);let p=new Uint8Array(8);return p.set(Kc.encode("VOX ")),new DataView(p.buffer).setUint32(4,150,!0),qr([p,fl("MAIN",new Uint8Array,qr([fl("SIZE",a),fl("XYZI",l),fl("RGBA",f)]))])}function Ed(i){let t=new Uint8Array(i);if(t.length<20||t.length>24e6)throw new Error("Choose a .vox file smaller than 24 MB.");let e=new DataView(t.buffer,t.byteOffset,t.byteLength),n=(b,w=4)=>rx.decode(t.slice(b,b+w));if(n(0)!=="VOX "||![150,200].includes(e.getUint32(4,!0))||n(8)!=="MAIN")throw new Error("Not a supported MagicaVoxel file.");let s,r,o,a=0,c=20+e.getUint32(12,!0),l=c+e.getUint32(16,!0),u=new Map,f=new Set;if(l!==t.length)throw new Error("Truncated or trailing VOX data.");for(;c<l;){if(c+12>l)throw new Error("Truncated VOX chunk.");let b=n(c),w=e.getUint32(c+4,!0),C=e.getUint32(c+8,!0),_=c+12,E=_+w+C;if(E>l)throw new Error("Truncated VOX chunk.");if(b==="SIZE"){if(w!==12)throw new Error("Invalid VOX size.");s=[0,4,8].map(R=>e.getUint32(_+R,!0)),a++}if(b==="XYZI"){if(w<4||e.getUint32(_,!0)*4+4!==w||r)throw new Error("Use one flattened voxel model.");r=t.slice(_+4,_+w)}if(b==="RGBA"){if(w!==1024)throw new Error("Invalid VOX palette.");o=t.slice(_,_+w)}if(["nTRN","nGRP","nSHP","LAYR"].includes(b)){let R=_,L=()=>{if(R+4>_+w)throw new Error("Truncated scene transforms.");let G=e.getInt32(R,!0);return R+=4,G},F=()=>{let G=L();if(G<0||G>1e4||R+G>_+w)throw new Error("Invalid VOX scene string.");let X=n(R,G);return R+=G,X},z=()=>{let G=L();if(G<0||G>64)throw new Error("Invalid VOX scene attributes.");let X=Object.create(null);for(let et=0;et<G;et++)X[F()]=F();return X},I=L(),O=z();if(I<0||u.size>128)throw new Error("Invalid VOX scene node.");if(b==="LAYR")O._hidden==="1"&&f.add(I),L();else{if(u.has(I))throw new Error("Duplicate VOX scene node.");let G={id:b,attrs:O};if(b==="nTRN"){if(G.child=L(),L()!==-1)throw new Error("Invalid VOX transform.");if(G.layer=L(),L()!==1)throw new Error("Import a static VOX asset; animated transforms are not supported.");G.frame=z()}if(b==="nGRP"){if(L()!==1)throw new Error("Import one model instance at a time.");G.child=L()}if(b==="nSHP"){if(L()!==1||L()!==0)throw new Error("Import one static voxel model.");z()}u.set(I,G)}if(R!==_+w)throw new Error("Unexpected VOX scene data.")}c=E}if(a!==1||!s||!r)throw new Error("Import a single flattened voxel model. Multiple models are not supported.");if(!o)throw new Error("Export the model with its RGBA palette before importing. Default-palette files are not supported.");if(s.some(b=>b<1||b>128)||s.reduce((b,w)=>b*w,1)>1048576)throw new Error("Use a model up to 128 cells per axis and one million cells.");let h=[];if(u.size){let b=new Set([...u.values()].map(E=>E.child).filter(E=>E!==void 0)),w=[...u.keys()].filter(E=>!b.has(E));if(w.length!==1)throw new Error("Invalid or cyclic VOX scene.");let C=w[0],_=new Set;for(;C!==void 0;){if(_.has(C)||!u.has(C))throw new Error("Invalid or cyclic VOX scene.");_.add(C);let E=u.get(C);if(E.attrs._hidden==="1"||f.has(E.layer))throw new Error("The imported asset is hidden in its scene.");if(E.id==="nTRN"){let R=Number(E.frame._r??4),L=R&3,F=R>>2&3,z=3-L-F;if(!Number.isInteger(R)||R<0||R>127||L>2||F>2||L===F||z<0||z>2)throw new Error("Invalid VOX rotation.");let I=String(E.frame._t??"0 0 0").trim().split(/\s+/).map(Number);if(I.length!==3||I.some(O=>!Number.isInteger(O)||Math.abs(O)>1e6))throw new Error("Invalid VOX translation.");h.push({axes:[L,F,z],signs:[4,5,6].map(O=>R&1<<O?-1:1),translation:I})}C=E.child}if(_.size!==u.size||![...u.values()].some(E=>E.id==="nSHP"))throw new Error("Import one connected VOX model.")}let p=b=>{let w=[...b];for(let C of[...h].reverse())w=C.axes.map((_,E)=>w[_]*C.signs[E]+C.translation[E]);return w},g=[];for(let b of[0,s[0]-1])for(let w of[0,s[1]-1])for(let C of[0,s[2]-1])g.push(p([b,w,C]));let v=[0,1,2].map(b=>Math.min(...g.map(w=>w[b]))),m=[0,1,2].map(b=>Math.max(...g.map(w=>w[b]))-v[b]+1),d=[m[0],m[2],m[1]],S=new Uint8Array(d.reduce((b,w)=>b*w,1)),T=new Set;for(let b=0;b<r.length;b+=4){let w=[...r.slice(b,b+3)],C=r[b+3];if(w.some((F,z)=>F>=s[z])||!C)throw new Error("VOX cell outside its declared model.");let[_,E,R]=p(w).map((F,z)=>F-v[z]),L=(R*d[2]+d[2]-1-E)*d[0]+_;if(S[L])throw new Error("Duplicate VOX cell.");S[L]=C,T.add(C)}let y=[...T].sort((b,w)=>b-w).map(b=>{let w=o.slice((b-1)*4,b*4);if(w[3]<13)throw new Error("A used VOX material is fully transparent.");return{id:b,name:"Imported "+b,color:"#"+[...w.slice(0,3)].map(C=>C.toString(16).padStart(2,"0")).join(""),opacity:w[3]/255,solid:!0,emission:0}});if(!y.length)throw new Error("That model contains no voxels.");return{size:d,cells:S,materials:y,boxes:$c(S,d),source:{format:"vox",transforms:h,placement:"Oriented model rebased to its own bounds for placement in this world; VOX has no physical scale."}}}function Td(i,t,{name:e="Imported asset",origin:n=[0,0,0]}={}){let s=qn(i),r=new Map;for(let c of t.materials){let l=s.materials.find(u=>u.color.toLowerCase()===c.color.toLowerCase()&&Math.abs(u.opacity-c.opacity)<.001&&u.solid===c.solid);if(!l){let u=new Set(s.materials.map(h=>h.id)),f=Array.from({length:255},(h,p)=>p+1).find(h=>!u.has(h));if(!f)throw new Error("The combined palette exceeds 255 colors.");l={...c,id:f},s.materials.push(l)}r.set(c.id,l.id)}let o="imported",a=2;for(;s.objects.some(c=>c.id===o);)o="imported-"+a++;return s.objects.push({id:o,name:e,size:t.size,origin:n,rotation:0,hidden:!1,locked:!1,boxes:t.boxes.map(c=>[...c.slice(0,6),r.get(c[6])]),edits:[],source:t.source}),{project:Nn(s),id:o}}function Ad(i){let t=new TextEncoder,e=[],n=[],s=0;for(let[c,l]of i){let u=t.encode(c),f=typeof l=="string"?t.encode(l):new Uint8Array(l),h=4294967295;for(let d of f){h^=d;for(let S=0;S<8;S++)h=h>>>1^3988292384&-(h&1)}h=(h^4294967295)>>>0;let p=new Uint8Array(30+u.length),g=new DataView(p.buffer);g.setUint32(0,67324752,!0),g.setUint16(4,20,!0),g.setUint16(6,2048,!0),g.setUint16(12,33,!0),g.setUint32(14,h,!0),g.setUint32(18,f.length,!0),g.setUint32(22,f.length,!0),g.setUint16(26,u.length,!0),p.set(u,30);let v=new Uint8Array(46+u.length),m=new DataView(v.buffer);m.setUint32(0,33639248,!0),m.setUint16(4,20,!0),m.setUint16(6,20,!0),m.setUint16(8,2048,!0),m.setUint16(14,33,!0),m.setUint32(16,h,!0),m.setUint32(20,f.length,!0),m.setUint32(24,f.length,!0),m.setUint16(28,u.length,!0),m.setUint32(42,s,!0),v.set(u,46),e.push(p,f),n.push(v),s+=p.length+f.length}let r=n.reduce((c,l)=>c+l.length,0),o=new Uint8Array(22),a=new DataView(o.buffer);return a.setUint32(0,101010256,!0),a.setUint16(8,i.length,!0),a.setUint16(10,i.length,!0),a.setUint32(12,r,!0),a.setUint32(16,s,!0),new Blob([...e,...n,o],{type:"application/zip"})}var ax="<!doctype html>"+document.documentElement.outerHTML,st=i=>document.getElementById(i),Nd=JSON.parse(st("world-data").textContent),Ui=Nd.mode==="walk",tt=Nn(Nd.project),Ks=tt.revision,nn=tt.objects.find(i=>!i.locked&&!i.hidden)?.id??tt.objects[0].id,Di=tt.materials[0].id,ai,js=[],en="select",sn=!1,fn,Js=0,li=!1,ss=!1,Kr=!1,$s=null,eh=0,ml=0,Zn=[],rs=[],Oe=new Set,nh="tidelands:"+tt.id,Qr=st("viewport"),rn=i=>{st("status").textContent=i};function Cd(i){cs(),rn(i.message);let t=document.querySelector("dialog[open]");if(t){let e=t.querySelector("[data-error]");e||(e=document.createElement("p"),e.dataset.error="",e.setAttribute("role","alert"),e.style.color="#a24b2f",t.append(e)),e.textContent=i.message}}var de=i=>(...t)=>{try{let e=i(...t);e?.catch&&e.catch(Cd)}catch(e){Cd(e)}},Un=(i,t,e="application/octet-stream")=>{let n=URL.createObjectURL(t instanceof Blob?t:new Blob([t],{type:e})),s=document.createElement("a");s.href=n,s.download=i,s.click(),setTimeout(()=>URL.revokeObjectURL(n),1e4)},ih=()=>new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),Qs=()=>{st("save-state").textContent=li?"Unsaved changes":ss?"Saved in workspace":"Editable offline project",st("save-source").hidden=!ss||Ui,st("save-source").disabled=!li||Kr||!!$s,st("undo").disabled=!Zn.length,st("redo").disabled=!rs.length};function sh(){try{localStorage.setItem(nh,JSON.stringify({revision:Ks,project:tt,at:Date.now()}))}catch{rn("Browser draft storage is full. Save your project to keep these changes.")}}function We(i,t="World updated"){if(Ui)return;let e=qn(tt);i(e);let n=Nn(e),s=Qi(n),r=Zs(n,s);for(Zn.push(JSON.stringify(tt));Zn.length>40||Zn.reduce((o,a)=>o+a.length,0)>16e6;)Zn.shift();rs.length=0,tt=n,ai=s,li=!0,Fd(r),cs(),sh(),rn(t)}function rh(i,t){i.length&&(t.push(JSON.stringify(tt)),tt=Nn(JSON.parse(i.pop())),li=!0,eo(),sh(),rn("Edit history restored"))}var Ge=new pr,pn=new Ue(43,1,.1,2e3),be=new el({antialias:!0,preserveDrawingBuffer:!0});be.setPixelRatio(Math.min(devicePixelRatio,2));be.shadowMap.enabled=!0;be.shadowMap.type=la;be.outputColorSpace=qe;be.toneMapping=Pr;be.toneMappingExposure=1.18;Qr.append(be.domElement);var Ud=new Sr("#f1f1d9","#66716e",2.2),je=new Tr("#ffedd1",3.1);je.castShadow=!0;je.shadow.mapSize.set(2048,2048);je.shadow.normalBias=.05;je.shadow.bias=-1e-4;Ge.add(Ud,je,je.target);var yn=new rl(pn,be.domElement);yn.enableDamping=!0;yn.dampingFactor=.09;yn.maxPolarAngle=Math.PI*.49;yn.minDistance=3;yn.maxDistance=300;var oi=new ye;Ge.add(oi);var os=new hl(pn,be.domElement);os.setTranslationSnap(1);os.setSize(.65);Ge.add(os.getHelper());var as=new Cr(new An,new Nt("#da9a52"));as.material.depthTest=!1;as.renderOrder=5;Ge.add(as);var is=new ut(new ge(1.015,1.015,1.015),new Vn({color:"#fff2c7",wireframe:!0,depthTest:!1}));is.visible=!1;is.renderOrder=6;Ge.add(is);var ts,es,$r=null,oh=!1,pl=[];function Ni(){return tt.objects.find(i=>i.id===nn)}function to(){let i=Ni();if(as.visible=!!(i&&!i.hidden&&!sn),os.detach(),!i||i.hidden)return;let t=Li(i);as.box.set(new P(...i.origin),new P(...i.origin.map((e,n)=>e+t[n]))),oi.position.set(...i.origin),en==="select"&&!i.locked&&!sn&&!Ui&&os.attach(oi)}os.addEventListener("dragging-changed",i=>{if(oh=i.value,yn.enabled=!i.value&&!sn,i.value)$r=[...Ni().origin];else if($r){let t=oi.position.toArray().map(Math.round);$r=null;try{We(e=>{e.objects.find(n=>n.id===nn).origin=t},"Object moved")}catch(e){eo(),rn(e.message)}to()}});os.addEventListener("objectChange",()=>{if(!$r)return;let i=Ni(),t=Li(i);oi.position.fromArray(oi.position.toArray().map((n,s)=>Math.max(0,Math.min(tt.size[s]-t[s],Math.round(n)))));let e=oi.position.toArray().map((n,s)=>n-$r[s]);for(let n of js)n.userData.id===nn&&n.position.set(...e);as.box.set(oi.position.clone(),oi.position.clone().add(new P(...t)))});function Qc(i){i.geometry?.dispose(),Array.isArray(i.material)?i.material.forEach(t=>t.dispose()):i.material?.dispose(),Ge.remove(i)}function ah(i=tt.light){let t=i*2*Math.PI,e=Math.max(.05,Math.sin(t)),n=Math.max(...tt.size);Ge.background=new Nt().lerpColors(new Nt("#182732"),new Nt("#dbe1d2"),e),Ge.fog=new fr(Ge.background,n*2,n*6),je.position.set(tt.size[0]/2+Math.cos(t)*n,Math.max(10,Math.sin(t)*n),tt.size[2]*1.5),je.target.position.set(tt.size[0]/2,0,tt.size[2]/2),je.intensity=.25+e*2.7,Ud.intensity=.55+e*1.5,je.shadow.camera.left=-n,je.shadow.camera.right=n,je.shadow.camera.top=n,je.shadow.camera.bottom=-n,je.shadow.camera.far=n*5,je.shadow.camera.updateProjectionMatrix()}function Fd(i){for(let e of js)Qc(e);js=[];for(let e of pl)Ge.remove(e);pl.length=0;for(let e of i){let n=new ve;n.setAttribute("position",new Yt(e.positions,3)),n.setAttribute("normal",new Yt(e.normals,3)),n.setIndex(e.indices),n.computeBoundingSphere();let s=tt.materials.find(a=>a.id===e.material),r=new Us({color:s.color,roughness:.86,metalness:0,transparent:s.opacity<1,opacity:s.opacity,depthWrite:s.opacity===1,emissive:s.color,emissiveIntensity:s.emission*.55}),o=new ut(n,r);o.castShadow=s.opacity===1,o.receiveShadow=!0,o.userData={id:tt.objects[e.object].id,material:e.material},js.push(o),Ge.add(o)}for(let e of js){let n=tt.materials.find(s=>s.id===e.userData.material);if(n.emission>0&&pl.length<12){e.geometry.computeBoundingBox();let s=new Er(n.color,n.emission*45,18,2);e.geometry.boundingBox.getCenter(s.position),pl.push(s),Ge.add(s)}}ts&&Qc(ts);let t=Math.max(tt.size[0],tt.size[2]);ts=new Ar(t,Math.ceil(t/4),"#879685","#b3bcab"),ts.position.set(tt.size[0]/2,-.03,tt.size[2]/2),ts.material.transparent=!0,ts.material.opacity=.4,Ge.add(ts),es&&Qc(es),es=new ut(new ni(t*12,t*12),new Us({color:"#c4ccbb",roughness:1})),es.rotation.x=-Math.PI/2,es.position.set(tt.size[0]/2,-.07,tt.size[2]/2),es.receiveShadow=!0,Ge.add(es),ah(),to(),st("scene-measures").textContent=`${ai.count.toLocaleString()} voxels \xB7 ${tt.size.map(e=>(e*tt.unit).toFixed(1)).join(" \xD7 ")} m`}function eo(){ai=Qi(tt),Fd(Zs(tt,ai)),cs(),sn&&fn&&!Yn(ai,fn.position)&&(tr(!1),rn("The world changed around the visitor. Review it before walking again."))}function no(i){let t=i??new An(new P(0,0,0),new P(tt.size[0],Math.max(...tt.objects.filter(r=>!r.hidden).map(r=>r.origin[1]+Li(r)[1]),2),tt.size[2])),e=t.getCenter(new P),n=t.getSize(new P),s=Math.max(...n.toArray())*1.35;i||(e.y*=.55),yn.target.copy(e),pn.position.copy(e).add(new P(s*.8,s*.65,s*.95)),pn.lookAt(e),yn.update()}function ls(i){nn=i,to(),cs()}function lh(i){en=i,document.querySelectorAll("[data-tool]").forEach(t=>t.classList.toggle("active",t.dataset.tool===en)),yn.mouseButtons.LEFT=en==="select"?Cn.ROTATE:-1,yn.mouseButtons.RIGHT=Cn.ROTATE,to(),is.visible=!1,st("interaction-hint").textContent=en==="select"?"Drag to orbit \xB7 click to select \xB7 arrows move objects":"Click to sculpt selected object \xB7 right-drag to orbit"}function cs(){st("world-title").textContent=tt.title,document.title=tt.title+" \u2014 Tidelands",st("brief-text").textContent=tt.brief,st("object-count").textContent=tt.objects.length+" objects",st("light").value=tt.light;let i=st("object-search").value.toLowerCase();st("object-list").innerHTML=tt.objects.filter(n=>n.name.toLowerCase().includes(i)).map(n=>`<div class="object-row ${n.id===nn?"selected":""} ${n.hidden?"hidden-object":""}"><button data-object="${n.id}" title="${Dn(n.name)}"><span class="dot"></span>${Dn(n.name)}</button><button class="toggle" data-visible="${n.id}" title="${n.hidden?"Show":"Hide"} ${Dn(n.name)}">${n.hidden?"\u25CB":"\u25CF"}</button><button class="toggle" data-lock="${n.id}" title="${n.locked?"Unlock":"Lock"} ${Dn(n.name)}">${n.locked?"\u25A3":"\u25A1"}</button></div>`).join("");let t=Ni();st("object-editor").innerHTML=t?`<label>Name<input id="object-name" value="${Dn(t.name)}" ${t.locked?"disabled":""}></label><label>Position \xB7 voxels<div class="xyz">${["X","Y","Z"].map((n,s)=>`<label>${n}<input data-position="${s}" type="number" step="1" min="0" value="${t.origin[s]}" ${t.locked?"disabled":""}></label>`).join("")}</div></label><div class="fine">${Li(t).map(n=>(n*tt.unit).toFixed(1)).join(" \xD7 ")} m \xB7 ${t.locked?"locked":"editable"}</div><div class="actions"><button id="rotate-object" ${t.locked?"disabled":""}>Rotate 90\xB0</button><button id="duplicate-object">Duplicate</button><button id="delete-object" ${t.locked||tt.objects.length===1?"disabled":""}>Delete</button></div><div class="actions"><button id="asset-glb">Asset .glb \u2197</button><button id="asset-vox">Asset .vox \u2197</button></div>`:"Choose an object to edit its geometry.",st("palette").innerHTML=tt.materials.map(n=>`<button data-material="${n.id}" title="${Dn(n.name)}" aria-label="${Dn(n.name)}" style="background:${n.color}" class="${n.id===Di?"active":""}"></button>`).join("");let e=tt.materials.find(n=>n.id===Di)??tt.materials[0];Di=e.id,st("material-editor").innerHTML=`<div class="color-row"><input id="material-color" aria-label="Material color" type="color" value="${e.color}"><input id="material-name" aria-label="Material name" value="${Dn(e.name)}"></div><label class="check"><input id="material-solid" type="checkbox" ${e.solid?"checked":""}> Blocks walking</label><label>Opacity<input id="material-opacity" type="range" min=".05" max="1" step=".01" value="${e.opacity}"></label><label>Glow<input id="material-glow" type="range" min="0" max="1" step=".05" value="${e.emission}"></label>`,st("tour-stops").innerHTML=tt.stops.map(n=>`<button data-stop="${n.id}" title="${Dn(n.description)}">${Dn(n.name)} \u2197</button>`).join(""),Qs()}st("object-list").onclick=de(i=>{let t=i.target.closest("button");t&&(t.dataset.object&&ls(t.dataset.object),t.dataset.visible&&We(e=>{let n=e.objects.find(s=>s.id===t.dataset.visible);n.hidden=!n.hidden},"Object visibility changed"),t.dataset.lock&&We(e=>{let n=e.objects.find(s=>s.id===t.dataset.lock);n.locked=!n.locked},"Object lock changed"))});st("object-search").oninput=cs;st("object-editor").onchange=de(i=>{i.target.id==="object-name"&&We(e=>{e.objects.find(n=>n.id===nn).name=i.target.value}),i.target.dataset.position&&We(e=>{e.objects.find(n=>n.id===nn).origin[Number(i.target.dataset.position)]=Number(i.target.value)},"Object moved")});st("object-editor").onclick=de(i=>{let t=i.target.closest("button")?.id,e=Ni();if(e){if(t==="rotate-object"&&We(n=>{n.objects.find(s=>s.id===nn).rotation=(e.rotation+1)%4},"Object rotated"),t==="duplicate-object"){let n=Od(e.id);We(s=>{let r=qn(e);r.id=n,r.name+=" copy",r.locked=!1,r.origin=r.origin.map((o,a)=>a===0?Math.min(tt.size[0]-Li(r)[0],o+2):o),s.objects.push(r)},"Object duplicated"),ls(n)}t==="delete-object"&&(We(n=>{n.objects=n.objects.filter(s=>s.id!==nn)},"Object removed"),ls(tt.objects[0].id)),t==="asset-glb"&&Un(e.id+".glb",Zr(tt,{objectId:e.id}),"model/gltf-binary"),t==="asset-vox"&&Un(e.id+".vox",jr(tt,{objectId:e.id}))}});function Od(i){let t=i,e=2;for(;tt.objects.some(n=>n.id===t);)t=i.slice(0,56)+"-"+e++;return t}st("new-object").onclick=de(()=>{let i=Od("object");We(t=>t.objects.push({id:i,name:"New voxel object",origin:[Math.floor(t.size[0]/2),Math.min(t.size[1]-1,Math.floor(tt.spawn.position[1])),Math.floor(t.size[2]/2)],size:[1,1,1],boxes:[[0,0,0,1,1,1,Di]],edits:[],rotation:0,hidden:!1,locked:!1}),"New object added"),ls(i),lh("add")});st("palette").onclick=i=>{let t=i.target.closest("[data-material]");t&&(Di=Number(t.dataset.material),cs())};st("material-editor").onchange=de(i=>{let e={"material-name":["name",i.target.value],"material-color":["color",i.target.value],"material-solid":["solid",i.target.checked],"material-opacity":["opacity",Number(i.target.value)],"material-glow":["emission",Number(i.target.value)]}[i.target.id];e&&We(n=>{n.materials.find(s=>s.id===Di)[e[0]]=e[1]},"Material updated across the world")});st("new-material").onclick=de(()=>{let i=Array.from({length:255},(t,e)=>e+1).find(t=>!tt.materials.some(e=>e.id===t));if(!i)throw new Error("The palette already has 255 materials.");We(t=>t.materials.push({id:i,name:"New material",color:"#c58b65",solid:!0,opacity:1,emission:0})),Di=i,cs()});document.querySelectorAll("[data-tool]").forEach(i=>i.onclick=()=>lh(i.dataset.tool));st("undo").onclick=()=>rh(Zn,rs);st("redo").onclick=()=>rh(rs,Zn);st("light").oninput=i=>ah(Number(i.target.value));st("light").onchange=de(i=>We(t=>{t.light=Number(i.target.value)},"Light saved"));st("cycle-light").onchange=()=>{ml=tt.light};st("frame-world").onclick=()=>{sn&&tr(!1),no()};st("focus-object").onclick=()=>{Ni()&&no(as.box)};var Rd=new Wi,Pd=new Pt,Jr=null,ns=null;function Bd(i){let t=be.domElement.getBoundingClientRect();return Pd.set((i.clientX-t.left)/t.width*2-1,-((i.clientY-t.top)/t.height)*2+1),Rd.setFromCamera(Pd,pn),Rd.intersectObjects(js,!1)[0]}function zd(i,t){return i.point.clone().addScaledVector(i.face.normal,t?.001:-.001).toArray().map(Math.floor)}be.domElement.addEventListener("pointerdown",i=>{Qr.focus(),Jr={x:i.clientX,y:i.clientY,button:i.button},sn&&!document.pointerLockElement&&(ns={x:i.clientX,y:i.clientY},be.domElement.setPointerCapture(i.pointerId))});be.domElement.addEventListener("pointermove",i=>{if(sn){if(document.pointerLockElement||ns){let e=document.pointerLockElement?i.movementX:i.clientX-ns.x,n=document.pointerLockElement?i.movementY:i.clientY-ns.y;fn.yaw-=e*.003,Js=Math.max(-1.45,Math.min(1.45,Js-n*.003)),ns&&(ns={x:i.clientX,y:i.clientY})}return}if(en==="select"||oh){is.visible=!1;return}let t=Bd(i);is.visible=!!t,t&&is.position.set(...zd(t,en==="add").map(e=>e+.5))});be.domElement.addEventListener("pointerup",de(i=>{if(ns=null,sn||oh||!Jr||Jr.button!==0||Math.hypot(i.clientX-Jr.x,i.clientY-Jr.y)>4)return;let t=Bd(i);if(!t)return;if(en==="select"){ls(t.object.userData.id);return}let e=zd(t,en==="add");if(e.some((n,s)=>n<0||n>=tt.size[s]))throw new Error("The brush is outside the world. Enlarge the project to build here.");if(en!=="add"&&t.object.userData.id!==nn)throw new Error("Select that object before changing its voxels.");We(n=>Md(n,nn,e,en==="erase"?0:Di,Number(st("brush-radius").value),{existingOnly:en==="paint"}),en==="erase"?"Voxels removed":en==="paint"?"Voxels painted":"Voxels added")}));be.domElement.addEventListener("contextmenu",i=>i.preventDefault());function kd(i=tt.spawn.position){if(!Yn(ai,i))throw new Error("This destination has insufficient room for a 1.7 m visitor. Check the walking routes.");fn={position:[...i],yaw:tt.spawn.yaw,velocity:0,grounded:!0},Js=0}function tr(i){i?kd():document.exitPointerLock?.(),sn=i,document.body.classList.toggle("walking",sn),st("interaction-hint").textContent=i?"WASD \xB7 drag to look \xB7 Space to jump":"Drag to orbit \xB7 click to select",st("walk-overlay").hidden=!i,st("crosshair").hidden=!i,st("touch-walk").hidden=!i||!matchMedia("(pointer:coarse)").matches,st("edit-tools").hidden=i||Ui,st("walk-mode").classList.toggle("active",i),st("edit-mode").classList.toggle("active",!i),yn.enabled=!i,Oe.clear(),to(),i||no(),ch()}st("walk-mode").onclick=de(()=>tr(!0));st("edit-mode").onclick=()=>tr(!1);st("enter-walk").onclick=de(async()=>{try{await be.domElement.requestPointerLock()}catch{rn("Drag the view to look around; keyboard and touch walking remain available.")}Qr.focus()});st("tour-stops").onclick=de(i=>{let t=tt.stops.find(e=>e.id===i.target.dataset.stop);t&&(kd(t.position),rn(t.name+" \xB7 "+t.description))});document.addEventListener("pointerlockchange",()=>{st("enter-walk").hidden=!!document.pointerLockElement});window.addEventListener("keydown",de(i=>{if(!i.target.matches("input,textarea,select")){if((i.metaKey||i.ctrlKey)&&i.key.toLowerCase()==="z"){i.preventDefault(),rh(i.shiftKey?rs:Zn,i.shiftKey?Zn:rs);return}if(sn&&["KeyW","KeyA","KeyS","KeyD","Space","ShiftLeft","ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(i.code))i.preventDefault(),Oe.add(i.code);else if(!sn&&!Ui&&i.code.startsWith("Arrow")&&Ni()&&!Ni().locked){i.preventDefault();let t=i.code==="ArrowLeft"||i.code==="ArrowRight"?0:2,e=i.code==="ArrowLeft"||i.code==="ArrowUp"?-1:1;We(n=>{n.objects.find(s=>s.id===nn).origin[t]+=e},"Object nudged")}}}));window.addEventListener("keyup",i=>Oe.delete(i.code));window.addEventListener("blur",()=>Oe.clear());var Id={forward:"KeyW",back:"KeyS",left:"KeyA",right:"KeyD",jump:"Space"};document.querySelectorAll("[data-move]").forEach(i=>{i.onpointerdown=t=>{t.preventDefault(),i.setPointerCapture(t.pointerId),Oe.add(Id[i.dataset.move])},i.onpointerup=i.onpointercancel=()=>Oe.delete(Id[i.dataset.move])});var Ld=performance.now(),th=0;function Vd(i){requestAnimationFrame(Vd);let t=Math.min(.06,(i-Ld)/1e3);if(Ld=i,sn&&fn){for(th+=t;th>=1/120;)fn=Sd(ai,fn,{forward:(Oe.has("KeyW")||Oe.has("ArrowUp")?1:0)-(Oe.has("KeyS")||Oe.has("ArrowDown")?1:0),right:(Oe.has("KeyD")||Oe.has("ArrowRight")?1:0)-(Oe.has("KeyA")||Oe.has("ArrowLeft")?1:0),sprint:Oe.has("ShiftLeft"),jump:Oe.has("Space")},1/120),Oe.delete("Space"),th-=1/120;pn.position.set(fn.position[0],fn.position[1]+1.58/tt.unit,fn.position[2]),pn.lookAt(pn.position.clone().add(new P(Math.sin(fn.yaw)*Math.cos(Js),Math.sin(Js),Math.cos(fn.yaw)*Math.cos(Js))))}else yn.update();st("cycle-light").checked&&(ml=(ml+t/120)%1,ah(ml)),be.render(Ge,pn)}function ch(){let{width:i,height:t}=Qr.getBoundingClientRect();!i||!t||(pn.aspect=i/t,pn.updateProjectionMatrix(),be.setSize(i,t,!1))}new ResizeObserver(ch).observe(Qr);st("edit-project").onclick=()=>{st("project-title").value=tt.title,st("project-brief").value=tt.brief,st("project-notes").value=tt.notes,st("project-unit").value=tt.unit,["x","y","z"].forEach((i,t)=>st("size-"+i).value=tt.size[t]),st("project-dialog").showModal()};st("apply-project").onclick=de(()=>{We(i=>{i.title=st("project-title").value,i.brief=st("project-brief").value,i.notes=st("project-notes").value,i.unit=Number(st("project-unit").value),i.size=["x","y","z"].map(t=>Number(st("size-"+t).value))},"Project settings saved"),st("project-dialog").close()});function gl(i="edit"){let t=JSON.stringify({project:tt,mode:i}).replace(/</g,"\\u003c");return ax.replace(/(<script id="world-data" type="application\/json">)[\s\S]*?(<\/script>)/,(e,n,s)=>n+t+s)}var lx=()=>`# ${tt.title}++${tt.brief}++Open studio.html to edit or walkthrough.html to explore, including offline. Import the .glb into a glTF-capable 3D tool. GLB is Y-up in meters; named objects become meshes. The .vox file is one flattened MagicaVoxel model with a palette, with its Z axis vertical. Keep ${tt.id}.tidelands.json: it preserves source objects, rotations, locks, materials, scale, spawn and destinations. Browser undo history is temporary.++One voxel = ${tt.unit} meters. The visitor is 1.7 m tall and 0.52 m wide. Route checks are finite geometry checks, not a substitute for walking the result. No game rules, networking or physical construction certification are included.++${tt.notes}+`;st("save-project").onclick=()=>Un(tt.id+".tidelands.json",JSON.stringify(tt,null,2),"application/json");st("deliver").onclick=()=>{st("export-summary").textContent=tt.title+" \xB7 "+ai.count.toLocaleString()+" voxels \xB7 "+tt.objects.filter(i=>!i.hidden).length+" visible objects",st("export-dialog").showModal()};st("close-export").onclick=()=>st("export-dialog").close();st("export-glb").onclick=de(()=>Un(tt.id+".glb",Zr(tt),"model/gltf-binary"));st("export-vox").onclick=de(()=>Un(tt.id+".vox",jr(tt)));st("export-walk").onclick=()=>Un(tt.id+"-walkthrough.html",gl("walk"),"text/html");st("export-kit").onclick=de(async()=>{rn("Preparing your editable world kit\u2026"),await new Promise(t=>setTimeout(t,30));let i=[[tt.id+".tidelands.json",JSON.stringify(tt,null,2)],[tt.id+".glb",Zr(tt)],[tt.id+".vox",jr(tt)],["studio.html",gl()],["walkthrough.html",gl("walk")],["README.md",lx()],["walking-check.json",JSON.stringify(dl(tt),null,2)]];Un(tt.id+"-world-kit.zip",Ad(i)),rn("World kit exported: source, GLB, VOX, editable studio and walkthrough")});st("snapshot").onclick=()=>{be.render(Ge,pn),be.domElement.toBlob(i=>{i&&Un(tt.id+"-"+ih()+".png",i)})};st("check-routes").onclick=de(()=>{let i=dl(tt);rn(i.issues.length?i.issues.join(" "):`${i.reachableStandingCells.toLocaleString()} connected standing positions; all ${i.stops.length} destinations reached by the geometry check. Walk the result to verify it.`),Un(tt.id+"-walking-check.json",JSON.stringify(i,null,2),"application/json")});function _l(i,t){let e=Nn(i);Zs(e),tt=e,nn=tt.objects.find(n=>!n.locked)?.id??tt.objects[0].id,Zn.length=0,rs.length=0,li=!0,eo(),sn&&tr(!1),no(),sh(),rn(t)}st("open-project").onclick=de(async()=>{if(st("native-open").hidden=!ss,st("open-dialog").showModal(),ss){let i=await fetch("/api/files"),t=await i.json();st("recent-projects").replaceChildren();for(let e of t.files??[]){let n=document.createElement("button");n.className="wide",n.textContent=e.name,n.title=e.folder,n.onclick=de(()=>Hd(e.path)),st("recent-projects").append(n)}t.files?.length||(st("recent-projects").textContent="No saved worlds in Downloads, Desktop or Documents yet.")}});st("choose-project").onclick=()=>st("project-file").click();st("close-open").onclick=()=>st("open-dialog").close();async function Hd(i){let t=await fetch("/api/open",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({path:i})}),e=await t.json();if(!t.ok)throw new Error(e.error||"Could not open the project.");_l(e.project,"Project opened as a draft. Save to keep it in this workspace."),st("open-dialog").close()}st("open-path").onclick=de(()=>Hd(st("project-path").value));st("project-file").onchange=de(async i=>{let t=i.target.files[0];if(i.target.value="",!!t){if(t.size>12e6)throw new Error("Choose a project smaller than 12 MB.");_l(JSON.parse(await t.text()),"Project opened as a draft. Save to keep it in this workspace."),st("open-dialog").close()}});st("import-vox").onclick=()=>st("vox-file").click();st("vox-file").onchange=de(async i=>{let t=i.target.files[0];if(i.target.value="",!t)return;if(t.size>24e6)throw new Error("Choose a VOX file smaller than 24 MB.");let e=Ed(await t.arrayBuffer()),n=[0,Math.floor(tt.spawn.position[1]),0],s=Td(tt,e,{name:t.name.replace(/\.vox$/i,""),origin:n});We(r=>Object.assign(r,s.project),"Supplied voxel asset imported"),ls(s.id)});function hh(i,t){$s=i,st("source-notice").hidden=!1,st("source-notice").querySelector("span").textContent=t,Qs()}st("draft-keep").onclick=()=>Un(tt.id+"-draft-"+ih()+".tidelands.json",JSON.stringify(tt,null,2),"application/json");st("source-load").onclick=de(()=>{if(!$s)return;Un(tt.id+"-before-restore-"+ih()+".tidelands.json",JSON.stringify(tt,null,2),"application/json");let i=$s;$s=null,_l(i,"Prior draft downloaded; source version restored"),Ks=i.revision,li=!1,st("source-notice").hidden=!0,Qs()});st("save-source").onclick=de(async()=>{if(!(!ss||$s)){Kr=!0,eh++,Qs();try{let i=await fetch("/api/project",{method:"PUT",headers:{"content-type":"application/json","if-match":Ks},body:JSON.stringify(tt)}),t=await i.json();if(i.status===409){hh(t.project,"The source changed while you were editing. Download your draft before choosing the source.");return}if(!i.ok)throw new Error(t.error||"Save failed");tt=Nn(t.project),Ks=tt.revision,li=!1;try{localStorage.removeItem(nh)}catch{}rn("Saved to workspace; the previous source is retained in history.")}finally{Kr=!1,Qs()}}});async function Dd(){if(location.protocol==="file:"||Ui||Kr)return;let i=++eh;try{let t=await fetch("/api/project");if(!t.ok)return;let e=await t.json();if(i!==eh||Kr||!e.project)return;ss=!0;let n=Nn(e.project);n.revision!==Ks&&(li?hh(n,"Your agent changed the source. Keep your draft before switching versions."):(tt=n,Ks=n.revision,eo(),rn("Agent changes loaded from the source project"))),Qs()}catch{}}document.body.classList.toggle("readonly",Ui);eo();no();ch();lh("select");requestAnimationFrame(Vd);if(Ui)de(()=>tr(!0))(),st("save-state").textContent="Offline walkthrough";else{try{let i=JSON.parse(localStorage.getItem(nh)||"null");if(i?.project&&JSON.stringify(i.project)!==JSON.stringify(tt)){let t=tt;_l(i.project,"Recovered your browser draft"),hh(t,"A previous browser draft was recovered. You can keep it or return to the saved source.")}}catch{}Dd(),setInterval(Dd,3e3)}window.tidelands={get project(){return qn(tt)},get world(){return ai},get visitor(){return qn(fn)},get selected(){return nn},screenPoint(i){let t=new P(...i).project(pn),e=be.domElement.getBoundingClientRect();return{x:e.x+(t.x+1)/2*e.width,y:e.y+(1-t.y)/2*e.height}},get connected(){return ss},get dirty(){return li},setSelected:ls,exportGLB:()=>Zr(tt),exportVOX:()=>jr(tt),portable:gl,navigationReport:()=>dl(tt)};})();+/*! Bundled license information:+three/build/three.core.js:+three/build/three.module.js:+ (**+ * @license+ * Copyright 2010-2026 Three.js Authors+ * SPDX-License-Identifier: MIT+ *)+*/</script></body></html>diff --git a/store/agents/voxel-worlds/template/world/project.json b/store/agents/voxel-worlds/template/world/project.jsonnew file mode 100644index 000000000..bbe3513f4--- /dev/null+++ b/store/agents/voxel-worlds/template/world/project.json@@ -0,0 +1,1385 @@+{+ "spec": "tidelands/2",+ "id": "lantern-quay",+ "title": "Lantern Quay",+ "brief": "An intimate harbor village for a cozy exploration game. A broad public quay leads to a lighthouse, working piers and colorful workshops. Keep buildings separate so they can become a reusable environment kit.",+ "size": [+ 80,+ 48,+ 64+ ],+ "unit": 0.3,+ "light": 0.3,+ "materials": [+ {+ "id": 1,+ "name": "Chalk limestone",+ "color": "#d7ccb4",+ "solid": true,+ "opacity": 1,+ "emission": 0+ },+ {+ "id": 2,+ "name": "Meadow",+ "color": "#75917a",+ "solid": true,+ "opacity": 1,+ "emission": 0+ },+ {+ "id": 3,+ "name": "Harbor water",+ "color": "#537f91",+ "solid": false,+ "opacity": 0.72,+ "emission": 0+ },+ {+ "id": 4,+ "name": "Weathered timber",+ "color": "#8f6750",+ "solid": true,+ "opacity": 1,+ "emission": 0+ },+ {+ "id": 5,+ "name": "Terracotta",+ "color": "#ad6453",+ "solid": true,+ "opacity": 1,+ "emission": 0+ },+ {+ "id": 6,+ "name": "Warm plaster",+ "color": "#eee0bd",+ "solid": true,+ "opacity": 1,+ "emission": 0+ },+ {+ "id": 7,+ "name": "Deep teal trim",+ "color": "#315b5c",+ "solid": true,+ "opacity": 1,+ "emission": 0+ },+ {+ "id": 8,+ "name": "Window glow",+ "color": "#ffd894",+ "solid": true,+ "opacity": 1,+ "emission": 0.7+ },+ {+ "id": 9,+ "name": "Paving",+ "color": "#b4ada2",+ "solid": true,+ "opacity": 1,+ "emission": 0+ },+ {+ "id": 10,+ "name": "Leaves",+ "color": "#436f62",+ "solid": true,+ "opacity": 1,+ "emission": 0+ },+ {+ "id": 11,+ "name": "Lighthouse white",+ "color": "#f6edd8",+ "solid": true,+ "opacity": 1,+ "emission": 0+ },+ {+ "id": 12,+ "name": "Ink metal",+ "color": "#374756",+ "solid": true,+ "opacity": 1,+ "emission": 0+ }+ ],+ "objects": [+ {+ "id": "headland",+ "name": "Limestone headland",+ "origin": [+ 0,+ 0,+ 0+ ],+ "size": [+ 56,+ 4,+ 64+ ],+ "boxes": [+ [+ 0,+ 0,+ 0,+ 56,+ 3,+ 64,+ 1+ ],+ [+ 0,+ 3,+ 0,+ 56,+ 1,+ 64,+ 2+ ]+ ],+ "rotation": 0,+ "hidden": false,+ "locked": true,+ "edits": []+ },+ {+ "id": "water",+ "name": "Tidal water",+ "origin": [+ 56,+ 1,+ 0+ ],+ "size": [+ 24,+ 2,+ 64+ ],+ "boxes": [+ [+ 0,+ 0,+ 0,+ 24,+ 2,+ 64,+ 3+ ]+ ],+ "rotation": 0,+ "hidden": false,+ "locked": true,+ "edits": []+ },+ {+ "id": "quay",+ "name": "Public promenade",+ "origin": [+ 26,+ 3,+ 0+ ],+ "size": [+ 30,+ 1,+ 64+ ],+ "boxes": [+ [+ 0,+ 0,+ 0,+ 10,+ 1,+ 64,+ 9+ ],+ [+ 10,+ 0,+ 25,+ 20,+ 1,+ 12,+ 9+ ],+ [+ 26,+ 0,+ 0,+ 4,+ 1,+ 64,+ 9+ ]+ ],+ "rotation": 0,+ "hidden": false,+ "locked": true,+ "edits": []+ },+ {+ "id": "bakery",+ "name": "Copper Roof Bakery",+ "origin": [+ 5,+ 4,+ 7+ ],+ "size": [+ 17,+ 20,+ 15+ ],+ "boxes": [+ [+ 0,+ 0,+ 0,+ 17,+ 1,+ 15,+ 4+ ],+ [+ 0,+ 1,+ 0,+ 17,+ 11,+ 1,+ 6+ ],+ [+ 0,+ 1,+ 14,+ 17,+ 11,+ 1,+ 6+ ],+ [+ 0,+ 1,+ 1,+ 1,+ 11,+ 13,+ 6+ ],+ [+ 16,+ 1,+ 1,+ 1,+ 11,+ 13,+ 6+ ],+ [+ 7,+ 1,+ 0,+ 3,+ 8,+ 1,+ 0+ ],+ [+ 2,+ 4,+ 0,+ 3,+ 4,+ 1,+ 8+ ],+ [+ 12,+ 4,+ 0,+ 3,+ 4,+ 1,+ 8+ ],+ [+ 0,+ 4,+ 5,+ 1,+ 4,+ 3,+ 8+ ],+ [+ 16,+ 4,+ 5,+ 1,+ 4,+ 3,+ 8+ ],+ [+ 7,+ 9,+ 0,+ 3,+ 1,+ 1,+ 7+ ],+ [+ 0,+ 12,+ 0,+ 17,+ 1,+ 15,+ 5+ ],+ [+ 0,+ 13,+ 1,+ 17,+ 1,+ 13,+ 5+ ],+ [+ 0,+ 14,+ 2,+ 17,+ 1,+ 11,+ 5+ ],+ [+ 0,+ 15,+ 3,+ 17,+ 1,+ 9,+ 5+ ],+ [+ 0,+ 16,+ 4,+ 17,+ 1,+ 7,+ 5+ ],+ [+ 0,+ 17,+ 5,+ 17,+ 1,+ 5,+ 5+ ],+ [+ 2,+ 13,+ 6,+ 2,+ 7,+ 2,+ 1+ ]+ ],+ "rotation": 2,+ "hidden": false,+ "locked": false,+ "edits": []+ },+ {+ "id": "workshop",+ "name": "Teal Boat Workshop",+ "origin": [+ 5,+ 4,+ 39+ ],+ "size": [+ 17,+ 20,+ 15+ ],+ "boxes": [+ [+ 0,+ 0,+ 0,+ 17,+ 1,+ 15,+ 4+ ],+ [+ 0,+ 1,+ 0,+ 17,+ 11,+ 1,+ 11+ ],+ [+ 0,+ 1,+ 14,+ 17,+ 11,+ 1,+ 11+ ],+ [+ 0,+ 1,+ 1,+ 1,+ 11,+ 13,+ 11+ ],+ [+ 16,+ 1,+ 1,+ 1,+ 11,+ 13,+ 11+ ],+ [+ 7,+ 1,+ 0,+ 3,+ 8,+ 1,+ 0+ ],+ [+ 2,+ 4,+ 0,+ 3,+ 4,+ 1,+ 8+ ],+ [+ 12,+ 4,+ 0,+ 3,+ 4,+ 1,+ 8+ ],+ [+ 0,+ 4,+ 5,+ 1,+ 4,+ 3,+ 8+ ],+ [+ 16,+ 4,+ 5,+ 1,+ 4,+ 3,+ 8+ ],+ [+ 7,+ 9,+ 0,+ 3,+ 1,+ 1,+ 7+ ],+ [+ 0,+ 12,+ 0,+ 17,+ 1,+ 15,+ 7+ ],+ [+ 0,+ 13,+ 1,+ 17,+ 1,+ 13,+ 7+ ],+ [+ 0,+ 14,+ 2,+ 17,+ 1,+ 11,+ 7+ ],+ [+ 0,+ 15,+ 3,+ 17,+ 1,+ 9,+ 7+ ],+ [+ 0,+ 16,+ 4,+ 17,+ 1,+ 7,+ 7+ ],+ [+ 0,+ 17,+ 5,+ 17,+ 1,+ 5,+ 7+ ],+ [+ 2,+ 13,+ 6,+ 2,+ 7,+ 2,+ 1+ ]+ ],+ "rotation": 0,+ "hidden": false,+ "locked": false,+ "edits": []+ },+ {+ "id": "pier",+ "name": "East timber pier",+ "origin": [+ 55,+ 0,+ 28+ ],+ "size": [+ 23,+ 4,+ 7+ ],+ "boxes": [+ [+ 0,+ 3,+ 0,+ 23,+ 1,+ 7,+ 4+ ],+ [+ 2,+ 0,+ 0,+ 1,+ 3,+ 1,+ 12+ ],+ [+ 2,+ 0,+ 6,+ 1,+ 3,+ 1,+ 12+ ],+ [+ 11,+ 0,+ 0,+ 1,+ 3,+ 1,+ 12+ ],+ [+ 11,+ 0,+ 6,+ 1,+ 3,+ 1,+ 12+ ],+ [+ 20,+ 0,+ 0,+ 1,+ 3,+ 1,+ 12+ ],+ [+ 20,+ 0,+ 6,+ 1,+ 3,+ 1,+ 12+ ]+ ],+ "rotation": 0,+ "hidden": false,+ "locked": false,+ "edits": []+ },+ {+ "id": "lighthouse",+ "name": "Quay lighthouse",+ "origin": [+ 40,+ 4,+ 2+ ],+ "size": [+ 11,+ 38,+ 11+ ],+ "boxes": [+ [+ 0,+ 0,+ 0,+ 11,+ 1,+ 11,+ 1+ ],+ [+ 2,+ 1,+ 2,+ 7,+ 26,+ 7,+ 11+ ],+ [+ 3,+ 1,+ 3,+ 5,+ 24,+ 5,+ 0+ ],+ [+ 4,+ 1,+ 2,+ 3,+ 8,+ 1,+ 0+ ],+ [+ 2,+ 12,+ 2,+ 7,+ 2,+ 7,+ 5+ ],+ [+ 3,+ 12,+ 3,+ 5,+ 2,+ 5,+ 0+ ],+ [+ 1,+ 27,+ 1,+ 9,+ 1,+ 9,+ 7+ ],+ [+ 3,+ 28,+ 3,+ 5,+ 5,+ 5,+ 8+ ],+ [+ 1,+ 33,+ 1,+ 9,+ 2,+ 9,+ 7+ ],+ [+ 3,+ 35,+ 3,+ 5,+ 1,+ 5,+ 7+ ],+ [+ 5,+ 36,+ 5,+ 1,+ 2,+ 1,+ 12+ ]+ ],+ "rotation": 0,+ "hidden": false,+ "locked": false,+ "edits": []+ },+ {+ "id": "lantern-1",+ "name": "Quay lantern 1",+ "origin": [+ 37,+ 4,+ 22+ ],+ "size": [+ 3,+ 11,+ 3+ ],+ "boxes": [+ [+ 1,+ 0,+ 1,+ 1,+ 8,+ 1,+ 12+ ],+ [+ 0,+ 8,+ 0,+ 3,+ 2,+ 3,+ 8+ ],+ [+ 0,+ 10,+ 0,+ 3,+ 1,+ 3,+ 12+ ]+ ],+ "rotation": 0,+ "hidden": false,+ "locked": false,+ "edits": []+ },+ {+ "id": "lantern-2",+ "name": "Quay lantern 2",+ "origin": [+ 49,+ 4,+ 22+ ],+ "size": [+ 3,+ 11,+ 3+ ],+ "boxes": [+ [+ 1,+ 0,+ 1,+ 1,+ 8,+ 1,+ 12+ ],+ [+ 0,+ 8,+ 0,+ 3,+ 2,+ 3,+ 8+ ],+ [+ 0,+ 10,+ 0,+ 3,+ 1,+ 3,+ 12+ ]+ ],+ "rotation": 0,+ "hidden": false,+ "locked": false,+ "edits": []+ },+ {+ "id": "lantern-3",+ "name": "Quay lantern 3",+ "origin": [+ 37,+ 4,+ 40+ ],+ "size": [+ 3,+ 11,+ 3+ ],+ "boxes": [+ [+ 1,+ 0,+ 1,+ 1,+ 8,+ 1,+ 12+ ],+ [+ 0,+ 8,+ 0,+ 3,+ 2,+ 3,+ 8+ ],+ [+ 0,+ 10,+ 0,+ 3,+ 1,+ 3,+ 12+ ]+ ],+ "rotation": 0,+ "hidden": false,+ "locked": false,+ "edits": []+ },+ {+ "id": "lantern-4",+ "name": "Quay lantern 4",+ "origin": [+ 49,+ 4,+ 40+ ],+ "size": [+ 3,+ 11,+ 3+ ],+ "boxes": [+ [+ 1,+ 0,+ 1,+ 1,+ 8,+ 1,+ 12+ ],+ [+ 0,+ 8,+ 0,+ 3,+ 2,+ 3,+ 8+ ],+ [+ 0,+ 10,+ 0,+ 3,+ 1,+ 3,+ 12+ ]+ ],+ "rotation": 0,+ "hidden": false,+ "locked": false,+ "edits": []+ },+ {+ "id": "tree-1",+ "name": "Wind shaped tree 1",+ "origin": [+ 1,+ 4,+ 27+ ],+ "size": [+ 7,+ 15,+ 7+ ],+ "boxes": [+ [+ 3,+ 0,+ 3,+ 1,+ 9,+ 1,+ 4+ ],+ [+ 1,+ 7,+ 1,+ 5,+ 5,+ 5,+ 10+ ],+ [+ 0,+ 9,+ 2,+ 7,+ 4,+ 3,+ 10+ ],+ [+ 2,+ 12,+ 2,+ 3,+ 3,+ 3,+ 2+ ]+ ],+ "rotation": 0,+ "hidden": false,+ "locked": false,+ "edits": []+ },+ {+ "id": "tree-2",+ "name": "Wind shaped tree 2",+ "origin": [+ 18,+ 4,+ 27+ ],+ "size": [+ 7,+ 15,+ 7+ ],+ "boxes": [+ [+ 3,+ 0,+ 3,+ 1,+ 9,+ 1,+ 4+ ],+ [+ 1,+ 7,+ 1,+ 5,+ 5,+ 5,+ 10+ ],+ [+ 0,+ 9,+ 2,+ 7,+ 4,+ 3,+ 10+ ],+ [+ 2,+ 12,+ 2,+ 3,+ 3,+ 3,+ 2+ ]+ ],+ "rotation": 0,+ "hidden": false,+ "locked": false,+ "edits": []+ },+ {+ "id": "tree-3",+ "name": "Wind shaped tree 3",+ "origin": [+ 43,+ 4,+ 52+ ],+ "size": [+ 7,+ 15,+ 7+ ],+ "boxes": [+ [+ 3,+ 0,+ 3,+ 1,+ 9,+ 1,+ 4+ ],+ [+ 1,+ 7,+ 1,+ 5,+ 5,+ 5,+ 10+ ],+ [+ 0,+ 9,+ 2,+ 7,+ 4,+ 3,+ 10+ ],+ [+ 2,+ 12,+ 2,+ 3,+ 3,+ 3,+ 2+ ]+ ],+ "rotation": 0,+ "hidden": false,+ "locked": false,+ "edits": []+ },+ {+ "id": "tree-4",+ "name": "Wind shaped tree 4",+ "origin": [+ 36,+ 4,+ 52+ ],+ "size": [+ 7,+ 15,+ 7+ ],+ "boxes": [+ [+ 3,+ 0,+ 3,+ 1,+ 9,+ 1,+ 4+ ],+ [+ 1,+ 7,+ 1,+ 5,+ 5,+ 5,+ 10+ ],+ [+ 0,+ 9,+ 2,+ 7,+ 4,+ 3,+ 10+ ],+ [+ 2,+ 12,+ 2,+ 3,+ 3,+ 3,+ 2+ ]+ ],+ "rotation": 0,+ "hidden": false,+ "locked": false,+ "edits": []+ },+ {+ "id": "crates",+ "name": "Cargo stack",+ "origin": [+ 42,+ 4,+ 28+ ],+ "size": [+ 6,+ 6,+ 4+ ],+ "boxes": [+ [+ 0,+ 0,+ 0,+ 3,+ 3,+ 3,+ 4+ ],+ [+ 3,+ 0,+ 1,+ 3,+ 3,+ 3,+ 5+ ],+ [+ 1,+ 3,+ 1,+ 3,+ 3,+ 3,+ 6+ ]+ ],+ "rotation": 0,+ "hidden": false,+ "locked": false,+ "edits": []+ },+ {+ "id": "boat",+ "name": "Harbor skiff",+ "origin": [+ 61,+ 1,+ 43+ ],+ "size": [+ 6,+ 4,+ 15+ ],+ "boxes": [+ [+ 1,+ 0,+ 1,+ 4,+ 1,+ 13,+ 7+ ],+ [+ 0,+ 1,+ 2,+ 1,+ 2,+ 11,+ 5+ ],+ [+ 5,+ 1,+ 2,+ 1,+ 2,+ 11,+ 5+ ],+ [+ 1,+ 1,+ 0,+ 4,+ 2,+ 1,+ 5+ ],+ [+ 1,+ 1,+ 14,+ 4,+ 2,+ 1,+ 5+ ],+ [+ 1,+ 1,+ 5,+ 4,+ 1,+ 1,+ 4+ ],+ [+ 1,+ 1,+ 10,+ 4,+ 1,+ 1,+ 4+ ],+ [+ 2,+ 3,+ 7,+ 1,+ 1,+ 1,+ 12+ ]+ ],+ "rotation": 0,+ "hidden": false,+ "locked": false,+ "edits": []+ }+ ],+ "spawn": {+ "position": [+ 31.5,+ 4,+ 46.5+ ],+ "yaw": 3.141592653589793+ },+ "stops": [+ {+ "id": "quay",+ "name": "The public quay",+ "description": "Workshops face a generous walking street.",+ "position": [+ 30.5,+ 4,+ 29.5+ ]+ },+ {+ "id": "pier",+ "name": "East pier",+ "description": "A removable pier module, ready for another scene.",+ "position": [+ 67.5,+ 4,+ 31.5+ ]+ },+ {+ "id": "beacon",+ "name": "Lighthouse court",+ "description": "The beacon keeps its own identity in the 3D export.",+ "position": [+ 47.5,+ 4,+ 15.5+ ]+ }+ ],+ "notes": "One voxel is 30 cm. Visitor height 1.7 m. Buildings and props are independently editable. Synthetic authored example; not a generated user commission."+}diff --git a/store/agents/voxel-worlds/test/ACCEPTANCE.md b/store/agents/voxel-worlds/test/ACCEPTANCE.mdnew file mode 100644index 000000000..7989d7b75--- /dev/null+++ b/store/agents/voxel-worlds/test/ACCEPTANCE.md@@ -0,0 +1,50 @@+# Voxel Worlds rebuild acceptance — 2026-09-20++The new studio authors editable named objects and reusable 3D assets. Its three scenes are+original authored fixtures, not customer commissions or installed-agent prompt trials.++## Completed checks++- Real setup on Intel macOS: pinned package-local tools installed, existing Chrome discovered,+ doctor passed. Node/runtime helper and local viewer command follow normal Harness packaging.+- Sixteen package tests pass: geometry and rotations, object-local sculpting, preserving empty+ cells while painting, physical walking/collision/jump/landing, mesh winding, import bounds,+ static MagicaVoxel scene transforms, real workspace saves and stale revisions, previous-source+ history, cross-origin rejection, hidden/symlink picker boundaries and init/verdict contracts.+- Actual Chrome controls: select and rename an object, position, rotate, direct voxel painting,+ undo/redo, save source, receive an agent revision while a browser draft exists, download both+ versions, reopen source, export selected GLB/VOX, import the VOX, export a complete ZIP, keyboard+ walking, destination controls and offline walkthrough reopening. Mobile walking controls were+ rendered at 390 × 844. No browser exceptions were observed.+- Keyboard input moved the real visitor roughly 3.3 m during the timed browser pass. Pure-model+ checks also verify wall collision and jump/landing clearance. This is a finite walking sample.+- Six real deliveries: before/after harbor, civic courtyard and dungeon. Each GLB had zero errors+ and zero warnings from Khronos glTF Validator. Three.js GLTFLoader independently reopened and+ rendered every GLB, retaining all 17 / 8 / 14 named objects and physical bounds. Three.js+ VOXLoader independently reopened each flattened VOX with matching dimensions and voxel count.+- Revisions moved the skiff, raised the reading canopy and widened the west passage. The approved+ bakery, pavilion and east treasury retained identical source and isolated GLB hashes. Finite+ walking checks reached all declared destinations before and after each revision.+- The actual seven-file browser ZIP passed `unzip -t`. Its source includes the current draft.+ Studio/independent GLB renderings were visually inspected; Store images are direct screenshots+ of these working studios. The original logo/icon remains in the package, header and favicon.++Raw local evidence: `/private/tmp/tidelands-release-browser/`,+`/private/tmp/tidelands-accepted-light/acceptance.json`. CI repeats package and browser checks;+it also rebuilds and independently reads the six deliveries. Evidence paths are local artifacts,+not durable public links.++## Limits and remaining product validation++- There is no proof here of an installed coding engine independently completing arbitrary user+ briefs, real customer usability, or a subjective “wow.” These remain product validation work.+- Browser checks use Chrome on this Mac and CI Chromium. Safari/Firefox, large-world interaction+ performance, touchscreen walking with a real user and other hardware remain unmeasured.+- VOX import supports one static model/instance with palette and orientation. Multi-model scenes,+ animation, absent palettes and hidden assets are rejected. Imported coordinates are rebased for+ placement; advanced MagicaVoxel shaders are not preserved. VOX does not encode physical scale.+- GLB keeps visible meshes/materials, not editor history, collision bodies, local preview lights+ or game logic. Use project JSON for source structure and the offline studio to keep editing.+- A 1.7 m visitor, cardinal route search and finite controls do not establish physical safety,+ accessibility certification or a finished game. Three authored visual directions do not exhaust+ what the source model can express. The old implementation remains in the repository.diff --git a/store/agents/voxel-worlds/test/acceptance.mjs b/store/agents/voxel-worlds/test/acceptance.mjsnew file mode 100644index 000000000..afb563c9e--- /dev/null+++ b/store/agents/voxel-worlds/test/acceptance.mjs@@ -0,0 +1,39 @@+import {mkdtemp,cp,mkdir,writeFile,readFile} from 'node:fs/promises';+import {tmpdir} from 'node:os';+import {join} from 'node:path';+import {fileURLToPath,pathToFileURL} from 'node:url';+import {createHash} from 'node:crypto';+import assert from 'node:assert/strict';+import {harbor,courtyard,dungeon} from './fixtures.mjs';+import {exportWorld} from '../template/tools/export.mjs';+import {exportGLB} from '../template/studio/formats.mjs';+import {compileWorld,navigationReport} from '../template/studio/project.mjs';+import {chromium} from '../toolchain/node_modules/playwright-core/index.mjs';+import {GLTFLoader} from '../toolchain/node_modules/three/examples/jsm/loaders/GLTFLoader.js';+import {VOXLoader} from '../toolchain/node_modules/three/examples/jsm/loaders/VOXLoader.js';+import {Box3,Vector3} from '../toolchain/node_modules/three/build/three.module.js';+import {build} from '../toolchain/node_modules/esbuild/lib/main.js';+import {browserPath} from '../toolchain/browser.mjs';+import validator from '../toolchain/node_modules/gltf-validator/index.js';+const packageRoot=fileURLToPath(new URL('../',import.meta.url)),root=process.env.VOXEL_ACCEPTANCE_ROOT||await mkdtemp(join(tmpdir(),'tidelands-acceptance-'));await mkdir(root,{recursive:true});process.env.VOXEL_DSH_DIR=packageRoot;+const browser=await chromium.launch({executablePath:await browserPath(),headless:true,args:['--enable-unsafe-swiftshader']}),page=await browser.newPage({viewport:{width:1440,height:960}}),report=[];+const arrayBuffer=b=>b.buffer.slice(b.byteOffset,b.byteOffset+b.byteLength),digest=b=>createHash('sha256').update(b).digest('hex');+const cases=[{make:harbor,target:'boat',approved:'bakery',revision:'Move the skiff east; retain the approved bakery.',edit:o=>{o.origin[0]+=2;}},{make:courtyard,target:'canopy',approved:'pavilion',revision:'Raise the reading canopy by 1.2 m, keeping the pavilion unchanged.',edit:o=>{o.size[1]+=3;o.boxes[0][1]+=3;for(const b of o.boxes.slice(1))b[4]+=3;}},{make:dungeon,target:'west-wing',approved:'east-wing',revision:'Widen the west passage entrance while preserving the east treasury.',edit:o=>{o.boxes[4][0]-=1;o.boxes[4][3]+=2;}}];+try{+ for(const item of cases){+ const workspace=join(root,item.make().id);await cp(join(packageRoot,'template'),workspace,{recursive:true});let project=item.make();const approved=JSON.stringify(project.objects.find(o=>o.id===item.approved)),assetHash=digest(exportGLB(project,{objectId:item.approved}));+ for(const phase of ['before','after']){+ if(phase==='after')item.edit(project.objects.find(o=>o.id===item.target));await writeFile(join(workspace,'world/project.json'),JSON.stringify(project,null,2)+'\n');const delivery=join(workspace,phase);await exportWorld(workspace,delivery);assert.deepEqual(navigationReport(project).issues,[]);+ const glb=await readFile(join(delivery,project.id+'.glb')),vox=await readFile(join(delivery,project.id+'.vox')),validation=await validator.validateBytes(new Uint8Array(glb),{});assert.equal(validation.issues.numErrors,0,JSON.stringify(validation.issues.messages));+ const parsed=await new GLTFLoader().parseAsync(arrayBuffer(glb),''),names=parsed.scene.children.map(n=>n.userData.objectId);assert.deepEqual(names.sort(),project.objects.filter(o=>!o.hidden).map(o=>o.id).sort());+ const bounds=new Box3().setFromObject(parsed.scene),size=bounds.getSize(new Vector3()).toArray();assert.ok(size[0]<=project.size[0]*project.unit+.0001);assert.ok(size[1]<=project.size[1]*project.unit+.0001);assert.ok(size[2]<=project.size[2]*project.unit+.0001);+ const supplied=new VOXLoader().parse(arrayBuffer(vox));assert.equal(supplied.chunks.length,1);assert.deepEqual(supplied.chunks[0].size,{x:project.size[0],y:project.size[2],z:project.size[1]});assert.equal(supplied.chunks[0].data.length/4,compileWorld(project).count);+ assert.equal(JSON.stringify(project.objects.find(o=>o.id===item.approved)),approved);assert.equal(digest(exportGLB(project,{objectId:item.approved})),assetHash);+ await page.goto(pathToFileURL(join(delivery,'studio.html')).href);await page.waitForFunction(()=>window.tidelands);await page.waitForTimeout(600);await page.screenshot({path:join(delivery,'studio.png')});+ const script=`import * as T from 'three';import {GLTFLoader} from 'three/addons/loaders/GLTFLoader.js';const bytes=Uint8Array.from(atob(${JSON.stringify(glb.toString('base64'))}),c=>c.charCodeAt(0));const result=await new GLTFLoader().parseAsync(bytes.buffer,'');const scene=new T.Scene();scene.background=new T.Color('#e6e8df');scene.add(result.scene);const box=new T.Box3().setFromObject(result.scene),center=box.getCenter(new T.Vector3()),size=box.getSize(new T.Vector3()),span=Math.max(...size.toArray()),camera=new T.PerspectiveCamera(42,innerWidth/innerHeight,.01,1000);camera.position.copy(center).add(new T.Vector3(span,span*.8,span*1.2));camera.lookAt(center);scene.add(new T.HemisphereLight('#ffffff','#757b73',2));const sun=new T.DirectionalLight('#ffe8ca',3);sun.position.set(span,span*2,span);scene.add(sun);const renderer=new T.WebGLRenderer({antialias:true});renderer.setSize(innerWidth,innerHeight);document.body.append(renderer.domElement);renderer.render(scene,camera);window.imported={objects:result.scene.children.length,bounds:size.toArray()};`;+ const built=await build({stdin:{contents:script,resolveDir:join(packageRoot,'toolchain')},bundle:true,write:false,format:'esm',minify:true,target:'es2022'});const imported=join(delivery,'independent-glb-preview.html');await writeFile(imported,'<!doctype html><meta charset="utf-8"><title>Independent GLB import</title><style>body{margin:0;overflow:hidden}</style><script type="module">'+built.outputFiles[0].text.replace(/<\/script/gi,'<\\/script')+'</script>');await page.goto(pathToFileURL(imported).href);await page.waitForFunction(()=>window.imported);await page.screenshot({path:join(delivery,'independent-glb.png')});+ report.push({id:project.id,phase,brief:project.brief,revision:item.revision,delivery,glbErrors:validation.issues.numErrors,glbWarnings:validation.issues.numWarnings,independentlyImportedObjects:names.length,physicalBoundsMeters:size,voxCells:supplied.chunks[0].data.length/4,approvedAsset:item.approved,approvedAssetSHA256:assetHash,navigation:navigationReport(project)});+ }+ }+ await writeFile(join(root,'acceptance.json'),JSON.stringify(report,null,2));console.log(JSON.stringify({root,cases:report.length,report:join(root,'acceptance.json')}));+}finally{await browser.close();}diff --git a/store/agents/voxel-worlds/test/browser.mjs b/store/agents/voxel-worlds/test/browser.mjsnew file mode 100644index 000000000..8f2f34745--- /dev/null+++ b/store/agents/voxel-worlds/test/browser.mjs@@ -0,0 +1,36 @@+import {mkdtemp,cp,mkdir,writeFile,readFile} from 'node:fs/promises';+import {tmpdir} from 'node:os';+import {join,resolve} from 'node:path';+import {fileURLToPath,pathToFileURL} from 'node:url';+import assert from 'node:assert/strict';+import {chromium} from '../toolchain/node_modules/playwright-core/index.mjs';+import {browserPath} from '../toolchain/browser.mjs';+import {createWorldViewer} from '../viewer/viewer.mjs';+import {buildWorld} from '../template/tools/build.mjs';+import {importVOX} from '../template/studio/formats.mjs';+import validator from '../toolchain/node_modules/gltf-validator/index.js';+const root=process.env.VOXEL_QA_ROOT||await mkdtemp(join(tmpdir(),'tidelands-browser-')),workspace=join(root,'workspace');await mkdir(root,{recursive:true});await cp(fileURLToPath(new URL('../template/',import.meta.url)),workspace,{recursive:true});+process.env.VOXEL_DSH_DIR=fileURLToPath(new URL('../',import.meta.url));await buildWorld(workspace);const server=await createWorldViewer(workspace);await new Promise(r=>server.listen(0,'127.0.0.1',r));+const url='http://127.0.0.1:'+server.address().port,browser=await chromium.launch({executablePath:await browserPath(),headless:true,args:['--enable-unsafe-swiftshader']});const context=await browser.newContext({viewport:{width:1440,height:960},acceptDownloads:true}),page=await context.newPage(),errors=[];page.on('pageerror',e=>errors.push(e.message));+const shot=async name=>{await page.waitForTimeout(500);await page.screenshot({path:join(root,name+'.png')});};+async function downloadClick(selector,name){const promise=page.waitForEvent('download');await page.locator(selector).click();const d=await promise;const path=join(root,name||d.suggestedFilename());await d.saveAs(path);return path;}+try{+ await page.goto(url);await page.waitForFunction(()=>window.tidelands?.connected);await shot('01-studio');assert.deepEqual(errors,[]);+ await page.locator('#edit-project').click();await page.locator('#size-x').fill('4');await page.locator('#apply-project').click();await page.locator('#project-dialog [data-error]').waitFor({state:'visible'});assert.equal(await page.evaluate(()=>window.tidelands.project.size[0]),80);await page.getByRole('button',{name:'Cancel',exact:true}).click();+ await page.locator('[data-object="crates"]').click();await page.locator('#focus-object').click();await page.waitForTimeout(500);await page.locator('[data-tool="paint"]').click();await page.locator('[data-material="8"]').click();const top=await page.evaluate(()=>window.tidelands.screenPoint([44.5,10,30.5]));await page.mouse.click(top.x,top.y);await page.waitForFunction(()=>window.tidelands.project.objects.find(o=>o.id==='crates').edits.length>0);await shot('02-sculpted');await page.locator('#undo').click();assert.equal(await page.evaluate(()=>window.tidelands.project.objects.find(o=>o.id==='crates').edits.length),0);await page.locator('[data-tool="select"]').click();await page.locator('#frame-world').click();+ await page.locator('[data-object="bakery"]').click();await page.locator('#object-name').fill('Approved bakery');await page.locator('#object-name').press('Tab');await page.waitForFunction(()=>window.tidelands.project.objects.find(o=>o.id==='bakery').name==='Approved bakery');+ await page.locator('[data-position="0"]').fill('7');await page.locator('[data-position="0"]').press('Tab');await page.locator('#rotate-object').click();assert.equal(await page.evaluate(()=>window.tidelands.project.objects.find(o=>o.id==='bakery').origin[0]),7);await shot('02-edited');+ await page.locator('#undo').click();assert.equal(await page.evaluate(()=>window.tidelands.project.objects.find(o=>o.id==='bakery').rotation),2);await page.locator('#redo').click();+ await page.locator('#save-source').click();await page.waitForFunction(()=>!window.tidelands.dirty);const saved=JSON.parse(await readFile(join(workspace,'world/project.json'),'utf8'));assert.equal(saved.objects.find(o=>o.id==='bakery').name,'Approved bakery');+ await page.locator('#object-name').fill('Browser draft bakery');await page.locator('#object-name').press('Tab');const external=structuredClone(saved);external.objects.find(o=>o.id==='boat').name='Agent revised skiff';await writeFile(join(workspace,'world/project.json'),JSON.stringify(external));await buildWorld(workspace);await page.locator('#source-notice').waitFor({state:'visible'});const draft=await downloadClick('#draft-keep','conflict-draft.tidelands.json');assert.equal(JSON.parse(await readFile(draft,'utf8')).objects.find(o=>o.id==='bakery').name,'Browser draft bakery');+ await downloadClick('#source-load','before-source-restore.tidelands.json');await page.waitForFunction(()=>window.tidelands.project.objects.find(o=>o.id==='boat').name==='Agent revised skiff');assert.equal(await page.evaluate(()=>window.tidelands.project.objects.find(o=>o.id==='bakery').name),'Approved bakery');+ await page.locator('[data-object="boat"]').click();const glbPath=await downloadClick('#asset-glb','skiff.glb'),voxPath=await downloadClick('#asset-vox','skiff.vox');const validation=await validator.validateBytes(new Uint8Array(await readFile(glbPath)),{});assert.equal(validation.issues.numErrors,0);const supplied=importVOX(await readFile(voxPath));assert.deepEqual(supplied.size,[6,4,15]);+ await page.locator('#vox-file').setInputFiles(voxPath);await page.waitForFunction(()=>window.tidelands.project.objects.some(o=>o.name==='skiff'));await page.locator('#undo').click();+ await page.locator('#deliver').click();const kit=await downloadClick('#export-kit','world-kit.zip'),walk=await downloadClick('#export-walk','walkthrough.html');await page.locator('#close-export').click();+ await page.locator('#walk-mode').click();await page.locator('#viewport').click({position:{x:700,y:700}});const before=await page.evaluate(()=>window.tidelands.visitor.position);await page.keyboard.down('w');await page.waitForTimeout(1100);await page.keyboard.up('w');const after=await page.evaluate(()=>window.tidelands.visitor.position);assert.ok(Math.hypot(before[0]-after[0],before[2]-after[2])>1);await shot('03-walk');+ const beforeRight=await page.evaluate(()=>window.tidelands.visitor.position[0]);await page.keyboard.down('d');await page.waitForTimeout(300);await page.keyboard.up('d');assert.ok(await page.evaluate(()=>window.tidelands.visitor.position[0])>beforeRight,'D strafes to the camera right');+ await page.locator('[data-stop="pier"]').click();await shot('04-pier');await page.locator('#edit-mode').click();+ const offline=await context.newPage();await context.setOffline(true);await offline.goto(pathToFileURL(walk).href);await offline.waitForFunction(()=>window.tidelands?.visitor);assert.equal(await offline.evaluate(()=>window.tidelands.project.objects.find(o=>o.id==='boat').name),'Agent revised skiff');await offline.screenshot({path:join(root,'05-offline-walk.png')});await context.setOffline(false);+ const mobile=await browser.newContext({viewport:{width:390,height:844},isMobile:true,hasTouch:true}),phone=await mobile.newPage();await phone.goto(url);await phone.waitForFunction(()=>window.tidelands);await phone.locator('#walk-mode').click();await phone.locator('[data-move="forward"]').waitFor({state:'visible'});await phone.screenshot({path:join(root,'06-mobile.png')});await mobile.close();+ assert.deepEqual(errors,[]);const report={root,workspace,url,kit,glbErrors:validation.issues.numErrors,walkDistanceCells:Math.hypot(before[0]-after[0],before[2]-after[2]),browserErrors:errors,checks:['direct voxel painting and undo','edit object and position','rotate/undo/redo','save source','agent/browser conflict with both drafts retained','independent selected GLB validation','VOX import','complete kit download','actual keyboard walking','tour stop','offline walkthrough reopen','mobile walking controls']};await writeFile(join(root,'report.json'),JSON.stringify(report,null,2));console.log(JSON.stringify(report));+}finally{await browser.close();server.closeAllConnections();await new Promise(r=>server.close(r));}diff --git a/store/agents/voxel-worlds/test/fixtures.mjs b/store/agents/voxel-worlds/test/fixtures.mjsnew file mode 100644index 000000000..48dd3815f--- /dev/null+++ b/store/agents/voxel-worlds/test/fixtures.mjs@@ -0,0 +1,33 @@+// Authored acceptance briefs, not a style selector or a generator exposed as the product.+import {validateProject} from '../template/studio/project.mjs';+const material=(id,name,color,extra={})=>({id,name,color,solid:true,opacity:1,emission:0,...extra});+const object=(id,name,origin,size,boxes,extra={})=>({id,name,origin,size,boxes,rotation:0,hidden:false,locked:false,edits:[],...extra});+export function harbor(){+ const p={spec:'tidelands/2',id:'lantern-quay',title:'Lantern Quay',brief:'An intimate harbor village for a cozy exploration game. A broad public quay leads to a lighthouse, working piers and colorful workshops. Keep buildings separate so they can become a reusable environment kit.',size:[80,48,64],unit:.3,light:.3,materials:[material(1,'Chalk limestone','#d7ccb4'),material(2,'Meadow','#75917a'),material(3,'Harbor water','#537f91',{solid:false,opacity:.72}),material(4,'Weathered timber','#8f6750'),material(5,'Terracotta','#ad6453'),material(6,'Warm plaster','#eee0bd'),material(7,'Deep teal trim','#315b5c'),material(8,'Window glow','#ffd894',{emission:.7}),material(9,'Paving','#b4ada2'),material(10,'Leaves','#436f62'),material(11,'Lighthouse white','#f6edd8'),material(12,'Ink metal','#374756')],objects:[],spawn:{position:[31.5,4,46.5],yaw:Math.PI},stops:[{id:'quay',name:'The public quay',description:'Workshops face a generous walking street.',position:[30.5,4,29.5]},{id:'pier',name:'East pier',description:'A removable pier module, ready for another scene.',position:[67.5,4,31.5]},{id:'beacon',name:'Lighthouse court',description:'The beacon keeps its own identity in the 3D export.',position:[47.5,4,15.5]}],notes:'One voxel is 30 cm. Visitor height 1.7 m. Buildings and props are independently editable. Synthetic authored example; not a generated user commission.'};+ p.objects.push(object('headland','Limestone headland',[0,0,0],[56,4,64],[[0,0,0,56,3,64,1],[0,3,0,56,1,64,2]],{locked:true}),object('water','Tidal water',[56,1,0],[24,2,64],[[0,0,0,24,2,64,3]],{locked:true}),object('quay','Public promenade',[26,3,0],[30,1,64],[[0,0,0,10,1,64,9],[10,0,25,20,1,12,9],[26,0,0,4,1,64,9]],{locked:true}));+ function house(id,name,origin,wall,roof){const boxes=[[0,0,0,17,1,15,4],[0,1,0,17,11,1,wall],[0,1,14,17,11,1,wall],[0,1,1,1,11,13,wall],[16,1,1,1,11,13,wall],[7,1,0,3,8,1,0],[2,4,0,3,4,1,8],[12,4,0,3,4,1,8],[0,4,5,1,4,3,8],[16,4,5,1,4,3,8],[7,9,0,3,1,1,7]];for(let n=0;n<6;n++)boxes.push([0,12+n,n,17,1,15-n*2,roof]);boxes.push([2,13,6,2,7,2,1]);return object(id,name,origin,[17,20,15],boxes);}+ const bakery=house('bakery','Copper Roof Bakery',[5,4,7],6,5);bakery.rotation=2;p.objects.push(bakery);+ p.objects.push(house('workshop','Teal Boat Workshop',[5,4,39],11,7));+ p.objects.push(object('pier','East timber pier',[55,0,28],[23,4,7],[[0,3,0,23,1,7,4],...[2,11,20].flatMap(x=>[[x,0,0,1,3,1,12],[x,0,6,1,3,1,12]])]));+ const tower=[[0,0,0,11,1,11,1],[2,1,2,7,26,7,11],[3,1,3,5,24,5,0],[4,1,2,3,8,1,0],[2,12,2,7,2,7,5],[3,12,3,5,2,5,0],[1,27,1,9,1,9,7],[3,28,3,5,5,5,8],[1,33,1,9,2,9,7],[3,35,3,5,1,5,7],[5,36,5,1,2,1,12]];+ p.objects.push(object('lighthouse','Quay lighthouse',[40,4,2],[11,38,11],tower));+ for(const [i,x,z]of [[1,37,22],[2,49,22],[3,37,40],[4,49,40]])p.objects.push(object('lantern-'+i,'Quay lantern '+i,[x,4,z],[3,11,3],[[1,0,1,1,8,1,12],[0,8,0,3,2,3,8],[0,10,0,3,1,3,12]]));+ for(const [i,x,z]of [[1,1,27],[2,18,27],[3,43,52],[4,36,52]])p.objects.push(object('tree-'+i,'Wind shaped tree '+i,[x,4,z],[7,15,7],[[3,0,3,1,9,1,4],[1,7,1,5,5,5,10],[0,9,2,7,4,3,10],[2,12,2,3,3,3,2]]));+ p.objects.push(object('crates','Cargo stack',[42,4,28],[6,6,4],[[0,0,0,3,3,3,4],[3,0,1,3,3,3,5],[1,3,1,3,3,3,6]]));+ p.objects.push(object('boat','Harbor skiff',[61,1,43],[6,4,15],[[1,0,1,4,1,13,7],[0,1,2,1,2,11,5],[5,1,2,1,2,11,5],[1,1,0,4,2,1,5],[1,1,14,4,2,1,5],[1,1,5,4,1,1,4],[1,1,10,4,1,1,4],[2,3,7,1,1,1,12]]));+ return validateProject(p);+}+export function courtyard(){+ const p={spec:'tidelands/2',id:'civic-court',title:'Civic Court',brief:'Block out a small civic arts campus with a sheltered exhibition pavilion, accessible level courtyard, water garden and sculpture. Deliver independent building masses for an architect to iterate in a 3D tool.',size:[64,40,64],unit:.4,light:.22,materials:[material(1,'Cast concrete','#cec9bb'),material(2,'Pale stone','#eeeadf'),material(3,'Charcoal steel','#3d4a52'),material(4,'Copper screen','#b87557'),material(5,'Garden','#7e8e70'),material(6,'Pool','#6f9299',{solid:false,opacity:.7}),material(7,'Glazing','#9db8b8',{solid:false,opacity:.35})],objects:[],spawn:{position:[31.5,2,55.5],yaw:Math.PI},stops:[{id:'pavilion',name:'Gallery threshold',description:'A wide level entry, without stairs.',position:[30.5,2,20.5]},{id:'garden',name:'Water garden',description:'The garden and canopy remain separate objects.',position:[13.5,2,52.5]}]};+ p.objects.push(object('site','Campus slab',[0,0,0],[64,2,64],[[0,0,0,64,2,64,1]],{locked:true}),object('pavilion','Exhibition pavilion',[9,1,5],[46,18,20],[[0,0,0,46,1,20,2],[0,1,0,46,14,1,2],[0,1,0,1,14,20,2],[45,1,0,1,14,20,2],[0,15,0,46,3,20,2],[8,1,18,1,14,1,3],[37,1,18,1,14,1,3],[2,1,18,5,10,1,7],[39,1,18,5,10,1,7]]),object('pool','Reflecting garden',[5,2,30],[18,2,20],[[0,0,0,18,1,20,2],[1,1,1,16,1,18,6]]),object('canopy','Copper reading canopy',[41,2,32],[17,14,20],[[0,12,0,17,2,20,4],[1,0,1,1,12,1,3],[15,0,1,1,12,1,3],[1,0,18,1,12,1,3],[15,0,18,1,12,1,3]]),object('sculpture','Folded stone sculpture',[28,2,33],[8,13,8],[[0,0,0,8,2,8,3],[1,2,1,2,11,6,2],[1,10,1,6,3,2,2],[5,5,1,2,8,2,2]]));+ for(let i=0;i<3;i++)p.objects.push(object('bench-'+i,'Courtyard bench '+(i+1),[27+i*5,2,49],[4,3,2],[[0,2,0,4,1,2,4],[0,0,0,1,2,2,3],[3,0,0,1,2,2,3]]));return validateProject(p);+}+export function dungeon(){+ const p={spec:'tidelands/2',id:'amber-vault',title:'The Amber Vault',brief:'A modular tabletop dungeon kit with a safe entry hall, a branching stone room, altar, pillars and a treasure chamber. Give each reusable module its own name and preserve the east wing during revisions.',size:[64,32,48],unit:.3,light:.42,materials:[material(1,'Basalt','#565770'),material(2,'Worn flagstone','#828092'),material(3,'Amber light','#efa65a',{emission:.8}),material(4,'Oxidized copper','#528e86'),material(5,'Dark iron','#2b3548'),material(6,'Gold','#c8a45c')],objects:[],spawn:{position:[30.5,2,38.5],yaw:Math.PI},stops:[{id:'altar',name:'The amber altar',description:'An independent prop for a tabletop or game scene.',position:[30.5,2,14.5]},{id:'treasure',name:'East treasury',description:'This wing is a reusable module.',position:[49.5,2,23.5]}]};+ p.objects.push(object('floor','Vault foundation',[0,0,0],[64,2,48],[[0,0,0,64,2,48,5],[2,1,2,60,1,44,2]],{locked:true}));+ const room=(id,name,x,z,w,d)=>object(id,name,[x,2,z],[w,11,d],[[0,0,0,w,11,1,1],[0,0,d-1,w,11,1,1],[0,0,1,1,11,d-2,1],[w-1,0,1,1,11,d-2,1],[Math.floor(w/2)-2,0,d-1,5,8,1,0],[w-1,0,Math.floor(d/2)-2,1,8,5,0],[0,0,Math.floor(d/2)-2,1,8,5,0]]);+ p.objects.push(room('hall','Central hall',18,5,26,30),room('east-wing','East treasury',44,10,17,22),room('west-wing','West passage',3,10,15,22));+ for(const [i,x,z]of [[1,22,10],[2,38,10],[3,22,27],[4,38,27]])p.objects.push(object('pillar-'+i,'Pillar '+i,[x,2,z],[3,13,3],[[0,0,0,3,2,3,1],[1,2,1,1,9,1,4],[0,11,0,3,2,3,1]]));+ p.objects.push(object('altar','Amber altar',[28,2,8],[7,8,4],[[0,0,0,7,2,4,1],[1,2,1,5,2,2,4],[2,4,1,3,4,2,3]]),object('chest','Treasury coffer',[52,2,15],[5,4,3],[[0,0,0,5,3,3,4],[0,3,0,5,1,3,6],[2,1,0,1,2,1,6]]));+ for(const [i,x,z]of [[1,19,18],[2,42,18],[3,45,13],[4,59,27]])p.objects.push(object('sconce-'+i,'Amber sconce '+i,[x,5,z],[1,4,1],[[0,0,0,1,2,1,5],[0,2,0,1,2,1,3]]));return validateProject(p);+}diff --git a/store/agents/voxel-worlds/test/project.test.mjs b/store/agents/voxel-worlds/test/project.test.mjsnew file mode 100644index 000000000..b5865fad1--- /dev/null+++ b/store/agents/voxel-worlds/test/project.test.mjs@@ -0,0 +1,55 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import {harbor,courtyard,dungeon} from './fixtures.mjs';+import {validateProject,compileWorld,cellAt,meshWorld,localToWorld,worldToLocal,paintCells,objectCells,moveVisitor,fitsVisitor,navigationReport,clone} from '../template/studio/project.mjs';+import {exportGLB,exportVOX,importVOX,addImportedAsset} from '../template/studio/formats.mjs';+import validator from '../toolchain/node_modules/gltf-validator/index.js';+test('three authored briefs have clear starts, reachable destinations and valid standard 3D exports',async()=>{+ for(const p of [harbor(),courtyard(),dungeon()]){+ assert.deepEqual(navigationReport(p).issues,[],p.title);+ const result=await validator.validateBytes(exportGLB(p),{maxIssues:20});assert.equal(result.issues.numErrors,0,JSON.stringify(result.issues.messages));+ const glb=exportGLB(p),v=new DataView(glb.buffer),json=JSON.parse(new TextDecoder().decode(glb.slice(20,20+v.getUint32(12,true))));assert.equal(json.nodes.length,p.objects.filter(o=>!o.hidden).length);+ assert.equal(json.extras.voxelSizeMeters,p.unit);assert.equal(json.nodes.find(n=>n.name===p.objects.at(-1).name).extras.objectId,p.objects.at(-1).id);+ const round=importVOX(exportVOX(p)),world=compileWorld(p);assert.deepEqual(round.size,world.size);assert.deepEqual(round.cells,world.cells);assert.equal(round.materials.find(m=>m.id===1).color,p.materials[0].color);+ }+});+test('asymmetric assets rotate with a reversible coordinate mapping, retain unrelated objects and export alone',async()=>{+ const p=harbor(),id='boat',o=p.objects.find(o=>o.id===id),before=JSON.stringify(p.objects.filter(o=>o.id!==id));+ for(let r=0;r<4;r++){o.rotation=r;for(const point of [[0,0,0],[2,1,8],[5,3,14]])assert.deepEqual(worldToLocal(o,...localToWorld(o,...point)),point);}+ o.rotation=1;const at=localToWorld(o,2,1,8);paintCells(p,id,at,8);assert.equal(cellAt(compileWorld(p),...at),8);assert.equal(o.rotation,0);assert.equal(JSON.stringify(p.objects.filter(o=>o.id!==id)),before);+ const round=importVOX(exportVOX(p,{objectId:id}));assert.deepEqual(round.size,o.size);assert.deepEqual(round.cells,objectCells(o));+ const valid=await validator.validateBytes(exportGLB(p,{objectId:id}),{});assert.equal(valid.issues.numErrors,0);+});+test('source import preserves palette and geometry and rejects truncated data and oversized objects',()=>{+ const p=harbor(),vox=exportVOX(p,{objectId:'boat'}),asset=importVOX(vox),insert=addImportedAsset(p,asset,{origin:[65,4,1],name:'Supplied skiff'});+ assert.equal(insert.project.objects.at(-1).name,'Supplied skiff');assert.equal(insert.project.materials.length,p.materials.length);+ assert.throws(()=>importVOX(vox.slice(0,-1)),/Truncated/);assert.throws(()=>addImportedAsset(p,asset,{origin:[79,0,0]}),/outside/);+ const transformed=new Uint8Array(vox.length+12);transformed.set(vox);transformed.set(new TextEncoder().encode('nTRN'),vox.length);new DataView(transformed.buffer).setUint32(16,transformed.length-20,true);assert.throws(()=>importVOX(transformed),/transforms/);+ const broken=clone(p);broken.objects[0].boxes[0][6]=254;assert.throws(()=>validateProject(broken),/Invalid voxel box/);+});+test('a standard VOX transform graph preserves asymmetric orientation when imported as a movable asset',()=>{+ const p=harbor(),base=exportVOX(p,{objectId:'boat'}),int=n=>{const b=Buffer.alloc(4);b.writeInt32LE(n);return b;},string=s=>Buffer.concat([int(Buffer.byteLength(s)),Buffer.from(s)]),dict=o=>Buffer.concat([int(Object.keys(o).length),...Object.entries(o).flatMap(([k,v])=>[string(k),string(v)])]),chunk=(id,body)=>Buffer.concat([Buffer.from(id),int(body.length),int(0),body]);+ const transform=chunk('nTRN',Buffer.concat([int(0),dict({_name:'Supplied skiff'}),int(1),int(-1),int(-1),int(1),dict({_r:'17',_t:'20 12 4'})]));+ const shape=chunk('nSHP',Buffer.concat([int(1),dict({}),int(1),int(0),dict({})])),bytes=Buffer.concat([base,transform,shape]);bytes.writeUInt32LE(bytes.length-20,16);+ const imported=importVOX(bytes),original=importVOX(base);assert.deepEqual(imported.size,[15,4,6]);+ for(let y=0;y<4;y++)for(let z=0;z<15;z++)for(let x=0;x<6;x++)assert.equal(imported.cells[(y*6+5-x)*15+z],original.cells[(y*15+z)*6+x]);+ assert.equal(imported.source.transforms.length,1);+});+test('sculpting expands an object without shifting existing cells and respects locks',()=>{+ const p=harbor(),o=p.objects.find(o=>o.id==='crates'),world=compileWorld(p),at=[o.origin[0]-1,o.origin[1],o.origin[2]];+ paintCells(p,o.id,at,8);assert.equal(cellAt(compileWorld(p),...at),8);assert.equal(cellAt(compileWorld(p),43,4,28),cellAt(world,43,4,28));+ assert.throws(()=>paintCells(p,'headland',[0,4,0],5),/unlocked/);paintCells(p,o.id,at,0);assert.equal(cellAt(compileWorld(p),...at),0);validateProject(p);+ const before=objectCells(o).filter(Boolean).length;paintCells(p,o.id,[42,4,28],8,2,{existingOnly:true});assert.equal(objectCells(o).filter(Boolean).length,before,'painting cannot fill empty space');+});+test('visitor travels in meters, collides with walls and lands without penetrating the ground',()=>{+ const p=harbor(),world=compileWorld(p);let visitor={position:[31.5,4,46.5],yaw:Math.PI,velocity:0,grounded:true};+ for(let i=0;i<120;i++)visitor=moveVisitor(world,visitor,{forward:1});assert.ok(Math.abs(visitor.position[2]-26.5)<.1);assert.ok(fitsVisitor(world,visitor.position));+ const north={position:[31.5,4,46.5],yaw:Math.PI,velocity:0,grounded:true};assert.ok(moveVisitor(world,north,{right:1}).position[0]>north.position[0],'D moves to camera-right when looking north');assert.ok(moveVisitor(world,{...north,yaw:0},{right:1}).position[0]<north.position[0],'D moves to camera-right when looking south');+ let jumper={position:[31.5,4,46.5],yaw:0,velocity:0,grounded:true},highest=4;+ for(let i=0;i<150;i++){jumper=moveVisitor(world,jumper,{jump:i===0});highest=Math.max(highest,jumper.position[1]);assert.ok(fitsVisitor(world,jumper.position));}+ assert.ok(highest>6);assert.ok(Math.abs(jumper.position[1]-4)<.002);assert.equal(jumper.grounded,true);+ let walker={position:[24.5,4,12.5],yaw:-Math.PI/2,velocity:0,grounded:true};for(let i=0;i<300;i++)walker=moveVisitor(world,walker,{forward:1,sprint:true});assert.ok(walker.position[0]>22);assert.ok(fitsVisitor(world,walker.position));+});+test('mesh face normals match triangle winding and buried surfaces are removed',()=>{+ const p=harbor();for(const g of meshWorld(p)){for(let f=0;f<g.indices.length;f+=6){const [a,b,c]=g.indices.slice(f,f+3).map(i=>g.positions.slice(i*3,i*3+3)),u=b.map((n,i)=>n-a[i]),v=c.map((n,i)=>n-a[i]),cross=[u[1]*v[2]-u[2]*v[1],u[2]*v[0]-u[0]*v[2],u[0]*v[1]-u[1]*v[0]],normal=g.normals.slice(g.indices[f]*3,g.indices[f]*3+3);assert.ok(cross.reduce((n,v,i)=>n+v*normal[i],0)>0);}}+});diff --git a/store/agents/voxel-worlds/test/showcase.mjs b/store/agents/voxel-worlds/test/showcase.mjsnew file mode 100644index 000000000..5d8d85041--- /dev/null+++ b/store/agents/voxel-worlds/test/showcase.mjs@@ -0,0 +1,8 @@+import {chromium} from '../toolchain/node_modules/playwright-core/index.mjs';+import {browserPath} from '../toolchain/browser.mjs';+import {fileURLToPath,pathToFileURL} from 'node:url';+import {join,resolve} from 'node:path';+import {mkdir} from 'node:fs/promises';+const root=resolve(process.argv[2]),out=fileURLToPath(new URL('../../../showcase/voxel-worlds/',import.meta.url));await mkdir(out,{recursive:true});+const browser=await chromium.launch({executablePath:await browserPath(),headless:true,args:['--enable-unsafe-swiftshader']}),page=await browser.newPage({viewport:{width:1440,height:960}});+try{for(const [id,name,phase]of [['lantern-quay','starter','before'],['civic-court','civic-court','before'],['amber-vault','amber-vault','after']]){await page.goto(pathToFileURL(join(root,id,phase,'studio.html')).href);await page.waitForFunction(()=>window.tidelands);await page.waitForTimeout(500);await page.screenshot({path:join(out,name+'.jpg'),type:'jpeg',quality:91});}console.log(out);}finally{await browser.close();}diff --git a/store/agents/voxel-worlds/test/toolchain.test.mjs b/store/agents/voxel-worlds/test/toolchain.test.mjsindex 15b7363be..d6b58dfcb 100644--- a/store/agents/voxel-worlds/test/toolchain.test.mjs+++ b/store/agents/voxel-worlds/test/toolchain.test.mjs@@ -33,11 +33,7 @@ test('every script the manifest names is in the folder and executable', () => {}})-test('setup installs nothing and succeeds quietly', () => {- assert.deepEqual(run(manifest.toolchain.setup), { code: 0, stdout: '', stderr: '' })-})--test('doctor says ok when sh is on PATH', () => {+test('doctor locates the installed world builder and browser', () => {const { code } = run(manifest.toolchain.doctor)assert.equal(code, 0)})@@ -50,8 +46,8 @@ test('init lays out a workspace and seeds a not-ready verdict', () => {assert.equal(readFileSync(join(workspace, '.harness-initialized'), 'utf8'), `initialized by ${manifest.id}\n`)})-test('the manifest names a viewer package and an HTML artifact', () => {- assert.equal(manifest.viewer.use, 'autonomous/web-viewer')+test('the manifest names its workspace bridge and an HTML artifact', () => {+ assert.equal(manifest.viewer.command, 'toolchain/viewer.sh')assert.deepEqual(manifest.viewer.artifactExtensions, ['.html'])})@@ -69,7 +65,7 @@ test('seed-verdict reports artifact presence without inventing verification', ()assert.equal(JSON.parse(readFileSync(join(workspace, '.harness/verdict.json'), 'utf8')).ready, false)})-test('the manifest routes the actual nested artifact through the shared viewer', () => {- assert.equal(manifest.viewer.url, 'http://127.0.0.1:${port}/?file=${artifact}')+test('the manifest routes the actual nested artifact through the source workspace bridge', () => {+ assert.equal(manifest.viewer.url, 'http://127.0.0.1:${port}/')assert.ok(manifest.workspace.marker.endsWith('/index.html'))})diff --git a/store/agents/voxel-worlds/test/viewer.test.mjs b/store/agents/voxel-worlds/test/viewer.test.mjsnew file mode 100644index 000000000..090decdd4--- /dev/null+++ b/store/agents/voxel-worlds/test/viewer.test.mjs@@ -0,0 +1,37 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { once } from 'node:events';+import { get } from 'node:http';+import { mkdtemp,cp,readFile,writeFile,rm,mkdir,readdir,symlink } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { fileURLToPath } from 'node:url';+import { createWorldViewer } from '../viewer/viewer.mjs';+const template=fileURLToPath(new URL('../template',import.meta.url));+async function fixture(fn){const dir=await mkdtemp(join(tmpdir(),'tidelands-viewer-')),ws=join(dir,'workspace'),home=join(dir,'home');await cp(template,ws,{recursive:true});await mkdir(join(home,'Downloads'),{recursive:true});const server=await createWorldViewer(ws,{home});server.listen(0,'127.0.0.1');await once(server,'listening');const base='http://127.0.0.1:'+server.address().port;try{await fn({ws,home,base});}finally{server.closeAllConnections();await new Promise(r=>server.close(r));await rm(dir,{recursive:true,force:true});}}+test('workspace save roundtrips real browser data, rebuilds output and rejects stale revisions',()=>fixture(async({ws,base})=>{+ const before=(await(await fetch(base+'/api/project')).json()).project,edited=structuredClone(before);edited.title='New harbor title';+ const put=p=>fetch(base+'/api/project',{method:'PUT',headers:{origin:base,'content-type':'application/json','if-match':before.revision},body:JSON.stringify(p)});+ const response=await put(edited);assert.equal(response.status,200);const after=(await response.json()).project;assert.notEqual(after.revision,before.revision);+ assert.equal(JSON.parse(await readFile(join(ws,'world/project.json'))).title,'New harbor title');assert.match(await readFile(join(ws,'world/index.html'),'utf8'),/New harbor title/);+ const history=await readdir(join(ws,'.harness/history'));assert.equal(history.length,1);assert.equal(JSON.parse(await readFile(join(ws,'.harness/history',history[0]))).title,'Lantern Quay');+ const stale=await put(before);assert.equal(stale.status,409);assert.equal((await stale.json()).project.title,'New harbor title');+}));+test('invalid project cannot overwrite the workspace and cross-origin writes are refused',()=>fixture(async({ws,base})=>{+ const before=await readFile(join(ws,'world/project.json'),'utf8');+ for(const origin of ['https://foreign.example',undefined]){const r=await fetch(base+'/api/project',{method:'PUT',headers:{'content-type':'application/json',...(origin?{origin}:{})},body:'{}'});assert.equal(r.status,403);}+ const invalid=await fetch(base+'/api/project',{method:'PUT',headers:{origin:base,'content-type':'application/json'},body:'{}'});assert.equal(invalid.status,400);+ assert.equal(await readFile(join(ws,'world/project.json'),'utf8'),before);+ const rejectedHost=await new Promise((resolve,reject)=>{get(base+'/api/project',{headers:{host:'foreign.example'}},response=>{response.resume();resolve(response.statusCode);}).on('error',reject);});+ assert.equal(rejectedHost,403);+ assert.equal((await fetch(base+'/files/.harness/verdict.json')).status,404);+}));+test('native picker opens only an explicitly selected visible home project',()=>fixture(async({ws,home,base})=>{+ const project=(await(await fetch(base+'/api/project')).json()).project,chosen=join(home,'Downloads','A world.tidelands.json');await writeFile(chosen,JSON.stringify(project));+ const files=(await(await fetch(base+'/api/files')).json()).files;assert.equal(files.length,1);assert.equal(files[0].name,'A world.tidelands.json');+ const open=path=>fetch(base+'/api/open',{method:'POST',headers:{origin:base,'content-type':'application/json'},body:JSON.stringify({path})});+ assert.equal((await open('"~/Downloads/A world.tidelands.json"')).status,200);+ const secret=join(home,'.hidden');await mkdir(secret);await writeFile(join(secret,'private.tidelands.json'),JSON.stringify(project));assert.equal((await open(join(secret,'private.tidelands.json'))).status,400);+ await writeFile(join(ws,'outside.tidelands.json'),JSON.stringify(project));await symlink(join(ws,'outside.tidelands.json'),join(home,'Downloads','link.tidelands.json'));assert.equal((await open(join(home,'Downloads','link.tidelands.json'))).status,400);+ assert.equal(JSON.parse(await readFile(join(ws,'world/project.json'))).title,'Lantern Quay','opening a file does not save over the workspace');+}));diff --git a/store/agents/voxel-worlds/toolchain/browser.mjs b/store/agents/voxel-worlds/toolchain/browser.mjsnew file mode 100644index 000000000..95832f547--- /dev/null+++ b/store/agents/voxel-worlds/toolchain/browser.mjs@@ -0,0 +1,18 @@+import { access, writeFile, readFile } from 'node:fs/promises';+import { execFileSync } from 'node:child_process';+import { fileURLToPath } from 'node:url';+import { join } from 'node:path';+const dir = fileURLToPath(new URL('.', import.meta.url));+export async function browserPath({ install = false } = {}) {+ const candidates = [process.env.BROWSER_EXECUTABLE, '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '/usr/bin/google-chrome', '/usr/bin/chromium', '/usr/bin/chromium-browser', process.env.PROGRAMFILES && join(process.env.PROGRAMFILES, 'Google/Chrome/Application/chrome.exe')].filter(Boolean);+ for (const path of candidates) { try { await access(path); return path; } catch {} }+ process.env.PLAYWRIGHT_BROWSERS_PATH = join(dir, 'browsers');+ const { chromium } = await import('./node_modules/playwright-core/index.mjs');+ const path = chromium.executablePath();+ try { await access(path); return path; } catch {}+ if (!install) throw new Error('Browser missing. Run the Voxel Worlds setup script.');+ execFileSync(process.execPath, [join(dir, 'node_modules/playwright-core/cli.js'), 'install', 'chromium'], { stdio: 'inherit', env: process.env });+ await access(path); return path;+}+if (process.argv.includes('--install')) console.log(`ok export browser: ${await browserPath({ install: true })}`);+if (process.argv.includes('--check')) console.log(`ok export browser: ${await browserPath()}`);diff --git a/store/agents/voxel-worlds/toolchain/doctor.sh b/store/agents/voxel-worlds/toolchain/doctor.shindex 76844330b..c68388b7b 100755--- a/store/agents/voxel-worlds/toolchain/doctor.sh+++ b/store/agents/voxel-worlds/toolchain/doctor.sh@@ -1,6 +1,6 @@#!/bin/sh-# Exit 0 when this machine can run the harness. Print one line per check; Harness shows them.-command -v sh >/dev/null 2>&1 && echo "ok sh (world generator)" || { echo "miss sh"; exit 1; }-# A browser pass helps the agent verify; warn, don't fail, without it.-command -v node >/dev/null 2>&1 && echo "ok node (for headless verify)" || echo "note node optional: camera-verify needs a browser"-exit 0+set -eu+here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)+cd "$here"+bash node.sh --input-type=module -e 'if(Number(process.versions.node.split(".")[0])<20)process.exit(1);await import("esbuild");await import("three");console.log("ok Node and offline world build tools")'+bash node.sh browser.mjs --checkdiff --git a/store/agents/voxel-worlds/toolchain/init-workspace.sh b/store/agents/voxel-worlds/toolchain/init-workspace.shindex faeead7de..a26732e11 100755--- a/store/agents/voxel-worlds/toolchain/init-workspace.sh+++ b/store/agents/voxel-worlds/toolchain/init-workspace.sh@@ -7,6 +7,6 @@ if [ ! -f "$ws/world/DESIGN.md" ]; thenprintf '# Design log — Voxel Worlds\n\nRecord date, USER or AI, decision, rationale, and whether it remains in the build.\n' > "$ws/world/DESIGN.md"ficat > "$ws/.harness/verdict.json" <<JSON-{"spec":1,"ready":false,"summary":"Tidelands starter available — describe what you want to create","artifact":"world/index.html","findings":[{"severity":"info","kind":"review_pending","message":"Starter provided; personalized changes need browser verification."}],"phases":[{"id":"build","name":"Build","state":"active"},{"id":"verify","name":"Verify","state":"pending"}],"updatedAt":"$(date -u +%Y-%m-%dT%H:%M:%SZ)"}+{"spec":1,"ready":false,"summary":"Tidelands world studio — describe a place you want to build","artifact":"world/index.html","findings":[{"severity":"info","kind":"review_pending","message":"The harbor is an authored example. Your world needs original geometry, walking and export review."}],"phases":[{"id":"build","name":"Build","state":"active"},{"id":"verify","name":"Verify","state":"pending"}],"updatedAt":"$(date -u +%Y-%m-%dT%H:%M:%SZ)"}JSONprintf 'initialized by %s\n' "${HARNESS_DSH:-autonomous/voxel-worlds}" > "$ws/.harness-initialized"diff --git a/store/agents/voxel-worlds/toolchain/install.sh b/store/agents/voxel-worlds/toolchain/install.shnew file mode 100755index 000000000..5bd03b568--- /dev/null+++ b/store/agents/voxel-worlds/toolchain/install.sh@@ -0,0 +1,9 @@+#!/usr/bin/env bash+set -euo pipefail+here="$(cd "$(dirname "$0")" && pwd)"+. "$here/runtimes.sh"+harness_node 20 || exit 1+cd "$here"+npm ci --ignore-scripts --no-audit --no-fund+node browser.mjs --install+node --input-type=module -e 'await import("esbuild");await import("three");console.log("ok offline world build tools")'diff --git a/store/agents/voxel-worlds/toolchain/node.sh b/store/agents/voxel-worlds/toolchain/node.shnew file mode 100755index 000000000..a527a9f1d--- /dev/null+++ b/store/agents/voxel-worlds/toolchain/node.sh@@ -0,0 +1,6 @@+#!/usr/bin/env bash+set -euo pipefail+here="$(cd "$(dirname "$0")" && pwd)"+. "$here/runtimes.sh"+harness_node 20 || exit 1+exec node "$@"diff --git a/store/agents/voxel-worlds/toolchain/package-lock.json b/store/agents/voxel-worlds/toolchain/package-lock.jsonnew file mode 100644index 000000000..01aa4fc18--- /dev/null+++ b/store/agents/voxel-worlds/toolchain/package-lock.json@@ -0,0 +1,497 @@+{+ "name": "tidelands-world-tools",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "tidelands-world-tools",+ "dependencies": {+ "esbuild": "0.27.2",+ "gltf-validator": "2.0.0-dev.3.10",+ "playwright-core": "1.63.0",+ "three": "0.186.0"+ }+ },+ "node_modules/@esbuild/aix-ppc64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.2.tgz",+ "integrity": "sha512-GZMB+a0mOMZs4MpDbj8RJp4cw+w1WV5NYD6xzgvzUJ5Ek2jerwfO2eADyI6ExDSUED+1X8aMbegahsJi+8mgpw==",+ "cpu": [+ "ppc64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "aix"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.2.tgz",+ "integrity": "sha512-DVNI8jlPa7Ujbr1yjU2PfUSRtAUZPG9I1RwW4F4xFB1Imiu2on0ADiI/c3td+KmDtVKNbi+nffGDQMfcIMkwIA==",+ "cpu": [+ "arm"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.2.tgz",+ "integrity": "sha512-pvz8ZZ7ot/RBphf8fv60ljmaoydPU12VuXHImtAs0XhLLw+EXBi2BLe3OYSBslR4rryHvweW5gmkKFwTiFy6KA==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-x64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.2.tgz",+ "integrity": "sha512-z8Ank4Byh4TJJOh4wpz8g2vDy75zFL0TlZlkUkEwYXuPSgX8yzep596n6mT7905kA9uHZsf/o2OJZubl2l3M7A==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-arm64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.2.tgz",+ "integrity": "sha512-davCD2Zc80nzDVRwXTcQP/28fiJbcOwvdolL0sOiOsbwBa72kegmVU0Wrh1MYrbuCL98Omp5dVhQFWRKR2ZAlg==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-x64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.2.tgz",+ "integrity": "sha512-ZxtijOmlQCBWGwbVmwOF/UCzuGIbUkqB1faQRf5akQmxRJ1ujusWsb3CVfk/9iZKr2L5SMU5wPBi1UWbvL+VQA==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-arm64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.2.tgz",+ "integrity": "sha512-lS/9CN+rgqQ9czogxlMcBMGd+l8Q3Nj1MFQwBZJyoEKI50XGxwuzznYdwcav6lpOGv5BqaZXqvBSiB/kJ5op+g==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-x64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.2.tgz",+ "integrity": "sha512-tAfqtNYb4YgPnJlEFu4c212HYjQWSO/w/h/lQaBK7RbwGIkBOuNKQI9tqWzx7Wtp7bTPaGC6MJvWI608P3wXYA==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.2.tgz",+ "integrity": "sha512-vWfq4GaIMP9AIe4yj1ZUW18RDhx6EPQKjwe7n8BbIecFtCQG4CfHGaHuh7fdfq+y3LIA2vGS/o9ZBGVxIDi9hw==",+ "cpu": [+ "arm"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.2.tgz",+ "integrity": "sha512-hYxN8pr66NsCCiRFkHUAsxylNOcAQaxSSkHMMjcpx0si13t1LHFphxJZUiGwojB1a/Hd5OiPIqDdXONia6bhTw==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ia32": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.2.tgz",+ "integrity": "sha512-MJt5BRRSScPDwG2hLelYhAAKh9imjHK5+NE/tvnRLbIqUWa+0E9N4WNMjmp/kXXPHZGqPLxggwVhz7QP8CTR8w==",+ "cpu": [+ "ia32"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-loong64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.2.tgz",+ "integrity": "sha512-lugyF1atnAT463aO6KPshVCJK5NgRnU4yb3FUumyVz+cGvZbontBgzeGFO1nF+dPueHD367a2ZXe1NtUkAjOtg==",+ "cpu": [+ "loong64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-mips64el": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.2.tgz",+ "integrity": "sha512-nlP2I6ArEBewvJ2gjrrkESEZkB5mIoaTswuqNFRv/WYd+ATtUpe9Y09RnJvgvdag7he0OWgEZWhviS1OTOKixw==",+ "cpu": [+ "mips64el"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ppc64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.2.tgz",+ "integrity": "sha512-C92gnpey7tUQONqg1n6dKVbx3vphKtTHJaNG2Ok9lGwbZil6DrfyecMsp9CrmXGQJmZ7iiVXvvZH6Ml5hL6XdQ==",+ "cpu": [+ "ppc64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-riscv64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.2.tgz",+ "integrity": "sha512-B5BOmojNtUyN8AXlK0QJyvjEZkWwy/FKvakkTDCziX95AowLZKR6aCDhG7LeF7uMCXEJqwa8Bejz5LTPYm8AvA==",+ "cpu": [+ "riscv64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-s390x": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.2.tgz",+ "integrity": "sha512-p4bm9+wsPwup5Z8f4EpfN63qNagQ47Ua2znaqGH6bqLlmJ4bx97Y9JdqxgGZ6Y8xVTixUnEkoKSHcpRlDnNr5w==",+ "cpu": [+ "s390x"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-x64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.2.tgz",+ "integrity": "sha512-uwp2Tip5aPmH+NRUwTcfLb+W32WXjpFejTIOWZFw/v7/KnpCDKG66u4DLcurQpiYTiYwQ9B7KOeMJvLCu/OvbA==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-arm64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.2.tgz",+ "integrity": "sha512-Kj6DiBlwXrPsCRDeRvGAUb/LNrBASrfqAIok+xB0LxK8CHqxZ037viF13ugfsIpePH93mX7xfJp97cyDuTZ3cw==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-x64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.2.tgz",+ "integrity": "sha512-HwGDZ0VLVBY3Y+Nw0JexZy9o/nUAWq9MlV7cahpaXKW6TOzfVno3y3/M8Ga8u8Yr7GldLOov27xiCnqRZf0tCA==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-arm64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.2.tgz",+ "integrity": "sha512-DNIHH2BPQ5551A7oSHD0CKbwIA/Ox7+78/AWkbS5QoRzaqlev2uFayfSxq68EkonB+IKjiuxBFoV8ESJy8bOHA==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-x64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.2.tgz",+ "integrity": "sha512-/it7w9Nb7+0KFIzjalNJVR5bOzA9Vay+yIPLVHfIQYG/j+j9VTH84aNB8ExGKPU4AzfaEvN9/V4HV+F+vo8OEg==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openharmony-arm64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.2.tgz",+ "integrity": "sha512-LRBbCmiU51IXfeXk59csuX/aSaToeG7w48nMwA6049Y4J4+VbWALAuXcs+qcD04rHDuSCSRKdmY63sruDS5qag==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "openharmony"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/sunos-x64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.2.tgz",+ "integrity": "sha512-kMtx1yqJHTmqaqHPAzKCAkDaKsffmXkPHThSfRwZGyuqyIeBvf08KSsYXl+abf5HDAPMJIPnbBfXvP2ZC2TfHg==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "sunos"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-arm64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.2.tgz",+ "integrity": "sha512-Yaf78O/B3Kkh+nKABUF++bvJv5Ijoy9AN1ww904rOXZFLWVc5OLOfL56W+C8F9xn5JQZa3UX6m+IktJnIb1Jjg==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-ia32": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.2.tgz",+ "integrity": "sha512-Iuws0kxo4yusk7sw70Xa2E2imZU5HoixzxfGCdxwBdhiDgt9vX9VUCBhqcwY7/uh//78A1hMkkROMJq9l27oLQ==",+ "cpu": [+ "ia32"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-x64": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.2.tgz",+ "integrity": "sha512-sRdU18mcKf7F+YgheI/zGf5alZatMUTKj/jNS6l744f9u3WFu4v7twcUI9vu4mknF4Y9aDlblIie0IM+5xxaqQ==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/esbuild": {+ "version": "0.27.2",+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.2.tgz",+ "integrity": "sha512-HyNQImnsOC7X9PMNaCIeAm4ISCQXs5a5YasTXVliKv4uuBo1dKrG0A+uQS8M5eXjVMnLg3WgXaKvprHlFJQffw==",+ "hasInstallScript": true,+ "license": "MIT",+ "bin": {+ "esbuild": "bin/esbuild"+ },+ "engines": {+ "node": ">=18"+ },+ "optionalDependencies": {+ "@esbuild/aix-ppc64": "0.27.2",+ "@esbuild/android-arm": "0.27.2",+ "@esbuild/android-arm64": "0.27.2",+ "@esbuild/android-x64": "0.27.2",+ "@esbuild/darwin-arm64": "0.27.2",+ "@esbuild/darwin-x64": "0.27.2",+ "@esbuild/freebsd-arm64": "0.27.2",+ "@esbuild/freebsd-x64": "0.27.2",+ "@esbuild/linux-arm": "0.27.2",+ "@esbuild/linux-arm64": "0.27.2",+ "@esbuild/linux-ia32": "0.27.2",+ "@esbuild/linux-loong64": "0.27.2",+ "@esbuild/linux-mips64el": "0.27.2",+ "@esbuild/linux-ppc64": "0.27.2",+ "@esbuild/linux-riscv64": "0.27.2",+ "@esbuild/linux-s390x": "0.27.2",+ "@esbuild/linux-x64": "0.27.2",+ "@esbuild/netbsd-arm64": "0.27.2",+ "@esbuild/netbsd-x64": "0.27.2",+ "@esbuild/openbsd-arm64": "0.27.2",+ "@esbuild/openbsd-x64": "0.27.2",+ "@esbuild/openharmony-arm64": "0.27.2",+ "@esbuild/sunos-x64": "0.27.2",+ "@esbuild/win32-arm64": "0.27.2",+ "@esbuild/win32-ia32": "0.27.2",+ "@esbuild/win32-x64": "0.27.2"+ }+ },+ "node_modules/gltf-validator": {+ "version": "2.0.0-dev.3.10",+ "resolved": "https://registry.npmjs.org/gltf-validator/-/gltf-validator-2.0.0-dev.3.10.tgz",+ "integrity": "sha512-odJ4k0tRkGXiDGn78yDBg+fBbAIvBnXxh3RwAta0emSxGtyagFE8B4xELB1oYe3S5RD8Ci3uZAsZaascH2LAEQ==",+ "license": "Apache-2.0"+ },+ "node_modules/playwright-core": {+ "version": "1.63.0",+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz",+ "integrity": "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==",+ "license": "Apache-2.0",+ "bin": {+ "playwright-core": "cli.js"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/three": {+ "version": "0.186.0",+ "resolved": "https://registry.npmjs.org/three/-/three-0.186.0.tgz",+ "integrity": "sha512-cr/fIM2ddMSVbYVgkfD4jLJv7Fh/8ZTjvo+7gQeSVGUZHxpx9FDwoL5iC7hUz/LiRA8wMbqfnb90xKfm1/HHkQ==",+ "license": "MIT"+ }+ }+}diff --git a/store/agents/voxel-worlds/toolchain/package.json b/store/agents/voxel-worlds/toolchain/package.jsonnew file mode 100644index 000000000..3b3aae833--- /dev/null+++ b/store/agents/voxel-worlds/toolchain/package.json@@ -0,0 +1,11 @@+{+ "name": "tidelands-world-tools",+ "private": true,+ "type": "module",+ "dependencies": {+ "three": "0.186.0",+ "esbuild": "0.27.2",+ "playwright-core": "1.63.0",+ "gltf-validator": "2.0.0-dev.3.10"+ }+}diff --git a/store/agents/voxel-worlds/toolchain/runtimes.sh b/store/agents/voxel-worlds/toolchain/runtimes.shnew file mode 100644index 000000000..7223c78dc--- /dev/null+++ b/store/agents/voxel-worlds/toolchain/runtimes.sh@@ -0,0 +1,192 @@+# shellcheck shell=bash+# runtimes.sh — the interpreters a store package runs on, found on this machine or fetched, never+# asked of the person who pressed Get.+#+# Sourced (not run) by a package's setup, doctor and viewer scripts. A new Mac has Apple's Python 3.9,+# no Homebrew and, for most people, no Node on PATH; a package that answers "brew install [email protected]"+# has failed its install. So:+#+# harness_node 18 node >= 18 on PATH, with npm: the machine's own, else the Node Harness+# itself runs on (~/.harness/runtime/current-node, laid down with the CLI)+# harness_uv uv on PATH: the machine's own, else a pinned, checksummed release+# fetched into ~/.harness/runtime+# harness_venv DIR 3.12 [MIN [BELOW]]+# DIR is a venv on CPython 3.12, which uv downloads when the machine+# has none. A venv already there on a Python in [MIN, BELOW) is kept.+# harness_pip DIR PKG… install into that venv, through uv+# harness_micromamba micromamba, pinned and checksummed, for native libraries PyPI has+# no wheel for (pycairo on macOS)+# harness_conda_env DIR SPEC… DIR is a conda-forge environment with those packages+#+# Every function prints `miss …` and returns 1 when it cannot deliver, so `harness_node 18 || exit 1`+# reads like the rest of a setup script. Nothing here touches the user's shell profile; what it+# installs lands in ~/.harness/runtime or the package's own directory (uv keeps its download cache+# where it always does, which a venv does not depend on).+#+# ONE copy is written by hand: store/tools/runtimes.sh in the OpenHarness repository. Each package+# carries an identical copy (a package installs alone, so it cannot reach this one);+# `node store/tools/sync-runtimes.mjs` rewrites them and the CLI's store spec fails when one drifts.++HARNESS_RUNTIME="${ADAPTER_RUNTIME_DIR:-${HOME:-}/.harness/runtime}"+# The Pythons uv downloads live with Harness's other runtimes, not in uv's own ~/.local/share/uv:+# a package's venv points at its interpreter, and `uv python uninstall` there must not break it.+UV_PYTHON_INSTALL_DIR="${UV_PYTHON_INSTALL_DIR:-$HARNESS_RUNTIME/python}"+export UV_PYTHON_INSTALL_DIR+HARNESS_UV_VERSION=0.12.15+HARNESS_MICROMAMBA_VERSION=2.9.0-0++_harness_platform() {+ case "$(uname -s)-$(uname -m)" in+ Darwin-arm64) echo darwin-arm64 ;;+ Darwin-x86_64) echo darwin-x64 ;;+ Linux-x86_64) echo linux-x64 ;;+ Linux-aarch64 | Linux-arm64) echo linux-arm64 ;;+ *) return 1 ;;+ esac+}++_harness_sha256() {+ if command -v shasum >/dev/null 2>&1; then shasum -a 256 "$1" | cut -d' ' -f1+ else sha256sum "$1" | cut -d' ' -f1; fi+}++# _harness_fetch URL DEST SHA256 — DEST exists only if what arrived matches the pinned checksum.+_harness_fetch() {+ local part="$2.part.$$"+ if ! curl -fsSL --retry 3 --connect-timeout 20 --max-time 900 -o "$part" "$1"; then+ rm -f "$part"; echo "miss could not download $1 — check this machine's internet connection"; return 1+ fi+ if [ "$(_harness_sha256 "$part")" != "$3" ]; then+ rm -f "$part"; echo "miss $1 did not match its pinned checksum; nothing was installed"; return 1+ fi+ mv -f "$part" "$2"+}++_harness_node_at_least() {+ command -v node >/dev/null 2>&1 || return 1+ node -e '+ const [a, b = 0] = process.argv[1].split(".").map(Number)+ const [x, y] = process.versions.node.split(".").map(Number)+ process.exit(x > a || (x === a && y >= b) ? 0 : 1)+ ' "$1" >/dev/null 2>&1+}++harness_node() {+ local min="${1:-18}" recorded saved="$PATH" own=0+ _harness_node_at_least "$min" && own=1+ # A node without npm beside it (a distro's nodejs package) cannot run a setup's `npm ci`.+ if [ "$own" = 1 ] && command -v npm >/dev/null 2>&1; then return 0; fi+ recorded="$(cat "$HARNESS_RUNTIME/current-node" 2>/dev/null || true)"+ # Already Harness's own (a second call, or a wrapper calling a script that asks again): nothing to add.+ if [ "$own" = 1 ] && [ -n "$recorded" ] && [ "$(command -v node)" = "${recorded%/*}/node" ]; then return 0; fi+ if [ -n "$recorded" ] && [ -x "${recorded%/*}/node" ]; then+ PATH="${recorded%/*}:$PATH"; export PATH; hash -r 2>/dev/null || true+ _harness_node_at_least "$min" && return 0+ PATH="$saved"; export PATH; hash -r 2>/dev/null || true+ [ "$own" = 1 ] && return 0+ echo "miss node >= $min — this machine's newest is $("${recorded%/*}/node" -v), Harness's own; update Harness"+ return 1+ fi+ [ "$own" = 1 ] && return 0+ echo "miss node >= $min, and Harness's own Node is not in $HARNESS_RUNTIME — run \`harness start\` once to lay it down"+ return 1+}++harness_uv() {+ local dir asset sum tmp+ command -v uv >/dev/null 2>&1 && return 0+ for dir in "${HOME:-}/.local/bin" "${HOME:-}/.cargo/bin"; do+ [ -n "${HOME:-}" ] || break+ if [ -x "$dir/uv" ]; then PATH="$dir:$PATH"; export PATH; return 0; fi+ done+ dir="$HARNESS_RUNTIME/uv-$HARNESS_UV_VERSION"+ if [ ! -x "$dir/uv" ]; then+ case "$(_harness_platform)" in+ darwin-arm64) asset=uv-aarch64-apple-darwin sum=dc304b9ed1b24174572290fba60ac3f6fe63c73a671f0439e62a91375841964d ;;+ darwin-x64) asset=uv-x86_64-apple-darwin sum=e9ca61775532368fe518ab03e7a354c7ecab8ccb3c7d941c775fcc4a362b801b ;;+ linux-x64) asset=uv-x86_64-unknown-linux-gnu sum=f97935763c04be3e692460a7aaeaaab8fc3b78fcf8b389da820b38ae7423a638 ;;+ linux-arm64) asset=uv-aarch64-unknown-linux-gnu sum=0e9a3499b0587d449c9ff684c0160da607826e4af1cee220bc87f378702d3e08 ;;+ *) echo "miss uv — there is no uv release for $(uname -s) $(uname -m); install it from https://docs.astral.sh/uv/"; return 1 ;;+ esac+ echo " fetching uv $HARNESS_UV_VERSION into $HARNESS_RUNTIME (it brings Python and the packages)"+ mkdir -p "$HARNESS_RUNTIME" || { echo "miss cannot write $HARNESS_RUNTIME"; return 1; }+ tmp="$(mktemp -d "$HARNESS_RUNTIME/.uv.XXXXXX")" || { echo "miss cannot write $HARNESS_RUNTIME"; return 1; }+ if ! _harness_fetch "https://github.com/astral-sh/uv/releases/download/$HARNESS_UV_VERSION/$asset.tar.gz" "$tmp/uv.tar.gz" "$sum"; then+ rm -rf "$tmp"; return 1+ fi+ tar -xzf "$tmp/uv.tar.gz" -C "$tmp" && chmod +x "$tmp/$asset/uv" "$tmp/$asset/uvx" \+ || { rm -rf "$tmp"; echo "miss the uv archive would not unpack"; return 1; }+ # Two installs at once both get here; whichever renames first wins and the other's copy goes.+ # (mv onto a directory that exists would nest the copy inside it, hence the test.)+ [ -e "$dir" ] || mv "$tmp/$asset" "$dir" 2>/dev/null || true+ rm -rf "$tmp"+ [ -x "$dir/uv" ] || { echo "miss uv did not land in $dir"; return 1; }+ fi+ PATH="$dir:$PATH"; export PATH+}++# harness_venv DIR VERSION [MIN [BELOW]] — MIN defaults to VERSION; BELOW is exclusive and optional.+harness_venv() {+ local dir="${1:?harness_venv needs a directory}" want="${2:?harness_venv needs a Python version}"+ local min="${3:-$2}" below="${4:-}"+ if [ -x "$dir/bin/python" ] && "$dir/bin/python" -c '+import sys+at = lambda s: tuple(int(p) for p in s.split("."))+v = sys.version_info[:2]+sys.exit(0 if v >= at(sys.argv[1]) and (not sys.argv[2] or v < at(sys.argv[2])) else 1)+' "$min" "$below" 2>/dev/null; then+ echo "ok $("$dir/bin/python" --version) in $dir"+ return 0+ fi+ harness_uv || return 1+ echo " python $want in $dir (uv downloads it when this machine has none)"+ rm -rf "$dir"+ # only-managed: the same python-build-standalone interpreter on every machine, so a package tested+ # once is tested everywhere — not whichever Homebrew or pyenv Python happened to be first on PATH.+ uv venv --quiet --seed --python "$want" --python-preference only-managed "$dir" \+ || { echo "miss could not make a Python $want environment in $dir"; return 1; }+ echo "ok $("$dir/bin/python" --version) in $dir"+}++harness_pip() {+ local dir="${1:?harness_pip needs a venv}"+ shift+ harness_uv || return 1+ # uv's own error comes first; the miss line is last, so it is the line the store shows.+ uv pip install --quiet --python "$dir/bin/python" "$@" \+ || { echo "miss could not install $* into $dir"; return 1; }+}++harness_micromamba() {+ local dir asset sum+ dir="$HARNESS_RUNTIME/micromamba-$HARNESS_MICROMAMBA_VERSION"+ if [ ! -x "$dir/micromamba" ]; then+ case "$(_harness_platform)" in+ darwin-arm64) asset=micromamba-osx-arm64 sum=ec2a072f028e1a7cf20f3e2e74d5a8127cf5a5f27636375b5359811565f4e5be ;;+ darwin-x64) asset=micromamba-osx-64 sum=1e71054bb3ac9a076e21f7ec48acfef536f9b3f1408f371a942784bf5ef83d8a ;;+ linux-x64) asset=micromamba-linux-64 sum=366cd9cd8be14df1ab8ed50352a82111082a36686b2d389fdb79a92c3fafb3e3 ;;+ linux-arm64) asset=micromamba-linux-aarch64 sum=9f93b974adcb4d166996af969b6cd371287d1a3e52733704727884d9b74cb7a7 ;;+ *) echo "miss micromamba — there is no release for $(uname -s) $(uname -m)"; return 1 ;;+ esac+ echo " fetching micromamba $HARNESS_MICROMAMBA_VERSION into $HARNESS_RUNTIME (native libraries PyPI has no wheel for)"+ mkdir -p "$dir" || { echo "miss cannot write $dir"; return 1; }+ _harness_fetch "https://github.com/mamba-org/micromamba-releases/releases/download/$HARNESS_MICROMAMBA_VERSION/$asset" "$dir/micromamba.$$" "$sum" || return 1+ chmod +x "$dir/micromamba.$$" && mv -f "$dir/micromamba.$$" "$dir/micromamba" \+ || { rm -f "$dir/micromamba.$$"; echo "miss micromamba would not install into $dir"; return 1; }+ fi+ HARNESS_MICROMAMBA="$dir/micromamba"+ export HARNESS_MICROMAMBA+}++# harness_conda_env DIR SPEC… — conda-forge only, packages cached under ~/.harness/runtime/mamba.+harness_conda_env() {+ local dir="${1:?harness_conda_env needs a directory}"+ shift+ # micromamba takes a relative --prefix as a name under its root prefix and "succeeds" there.+ case "$dir" in /*) ;; *) dir="$PWD/$dir" ;; esac+ harness_micromamba || return 1+ MAMBA_ROOT_PREFIX="$HARNESS_RUNTIME/mamba" "$HARNESS_MICROMAMBA" create --yes --quiet \+ --prefix "$dir" --override-channels --channel conda-forge "$@" >/dev/null \+ && [ -d "$dir/conda-meta" ] \+ || { echo "miss could not make the conda-forge environment in $dir ($*)"; return 1; }+}diff --git a/store/agents/voxel-worlds/toolchain/setup.sh b/store/agents/voxel-worlds/toolchain/setup.shindex 30f606684..7ccd3d7a1 100755--- a/store/agents/voxel-worlds/toolchain/setup.sh+++ b/store/agents/voxel-worlds/toolchain/setup.sh@@ -1,4 +1,4 @@#!/bin/sh-# Nothing to install: the Voxel Worlds harness generates a single self-contained HTML file and-# renders it in the built-in web-viewer. Kept so the shape matches a real harness.-exit 0+set -eu+here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)+exec bash "$here/install.sh"diff --git a/store/agents/voxel-worlds/toolchain/viewer.sh b/store/agents/voxel-worlds/toolchain/viewer.shnew file mode 100755index 000000000..c2afe7493--- /dev/null+++ b/store/agents/voxel-worlds/toolchain/viewer.sh@@ -0,0 +1,4 @@+#!/bin/sh+set -eu+here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)+exec bash "$here/node.sh" "$here/../viewer/viewer.mjs"diff --git a/store/agents/voxel-worlds/viewer/viewer.mjs b/store/agents/voxel-worlds/viewer/viewer.mjsnew file mode 100644index 000000000..a1f122d72--- /dev/null+++ b/store/agents/voxel-worlds/viewer/viewer.mjs@@ -0,0 +1,74 @@+// Local workspace bridge: explicit project saves, optimistic revision checks, recoverable history.+import { createServer } from 'node:http';+import { readFile,writeFile,mkdir,rename,realpath,readdir,stat } from 'node:fs/promises';+import { homedir } from 'node:os';+import { resolve,join,dirname,basename,relative,sep,extname } from 'node:path';+import { fileURLToPath } from 'node:url';+import { createHash,randomUUID } from 'node:crypto';+import { readProject,buildWorld } from '../template/tools/build.mjs';+import { validateProject,meshWorld } from '../template/studio/project.mjs';+const hash=p=>createHash('sha256').update(JSON.stringify(p)).digest('hex');+export async function createWorldViewer(workspace,{home=homedir()}={}){+ const root=await realpath(workspace),homeRoot=await realpath(home);let saving=false;+ async function current(){const project=await readProject(root);delete project.revision;project.revision=hash(project);return project;}+ async function picked(raw){+ let name=String(raw??'').trim();if((name.startsWith('"')&&name.endsWith('"'))||(name.startsWith("'")&&name.endsWith("'")))name=name.slice(1,-1);+ if(name.startsWith('file://'))name=fileURLToPath(name);else name=name.replace(/\\ /g,' ');+ if(name==='~')name=homeRoot;else if(name.startsWith('~/'))name=join(homeRoot,name.slice(2));+ const actual=await realpath(resolve(name)),rel=relative(homeRoot,actual);+ if(rel.startsWith('..')||rel.split(sep).some(s=>s.startsWith('.')||s==='Library')||!actual.startsWith(homeRoot+sep))throw new Error('Choose a project inside your home folder, outside hidden folders and Library.');+ if(!actual.toLowerCase().endsWith('.tidelands.json'))throw new Error('Choose a saved .tidelands.json project.');+ const info=await stat(actual);if(!info.isFile()||info.size>12000000)throw new Error('Choose a project file smaller than 12 MB.');+ return validateProject(JSON.parse(await readFile(actual,'utf8')));+ }+ async function recent(){+ const files=[];+ for(const folder of ['Downloads','Desktop','Documents']){+ const path=join(homeRoot,folder);let list=[];try{list=await readdir(path,{withFileTypes:true});}catch{continue;}+ for(const entry of list.slice(0,3000)){if(!entry.isFile()||entry.name.startsWith('.')||!entry.name.toLowerCase().endsWith('.tidelands.json'))continue;const file=join(path,entry.name),info=await stat(file).catch(()=>null);if(info&&info.size<=12000000)files.push({name:entry.name,path:file,folder:'~/'+folder,mtime:info.mtimeMs});}+ }return files.sort((a,b)=>b.mtime-a.mtime).slice(0,30);+ }+ const server=createServer(async(req,res)=>{+ res.setHeader('cache-control','no-store');res.setHeader('x-content-type-options','nosniff');+ const send=(code,body,type='application/json')=>{res.writeHead(code,{'content-type':type});res.end(type==='application/json'?JSON.stringify(body):body);};+ if(!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(req.headers.host??''))return send(403,{error:'Loopback only.'});+ const origin='http://'+req.headers.host;+ if((req.headers.origin&&req.headers.origin!==origin)||req.headers['sec-fetch-site']==='cross-site')return send(403,{error:'Same-origin requests only.'});+ let path;try{path=decodeURIComponent(new URL(req.url,origin).pathname);}catch{return send(400,{error:'Invalid path.'});}+ const mutation=['PUT','POST'].includes(req.method);+ if(mutation&&(req.headers.origin!==origin||!String(req.headers['content-type']).startsWith('application/json')))return send(403,{error:'Use the local studio to save or open a project.'});+ async function body(){let size=0;const chunks=[];for await(const chunk of req){size+=chunk.length;if(size>12000000)throw new Error('Request exceeds 12 MB.');chunks.push(chunk);}return JSON.parse(Buffer.concat(chunks));}+ try{+ if(path==='/api/project'&&req.method==='GET')return send(200,{project:await current()});+ if(path==='/api/project'&&req.method==='PUT'){+ if(saving)return send(409,{project:await current(),error:'Another save is in progress.'});+ const project=validateProject(await body());meshWorld(project);delete project.revision;saving=true;+ try{+ const before=await current();if(req.headers['if-match']!==before.revision)return send(409,{project:before,error:'The source changed. Keep both versions until you choose.'});+ const history=join(root,'.harness/history');await mkdir(history,{recursive:true});+ await writeFile(join(history,new Date().toISOString().replace(/[:.]/g,'-')+'-'+randomUUID()+'.tidelands.json'),JSON.stringify(before));+ const target=join(root,'world/project.json'),temporary=target+'.'+randomUUID()+'.tmp';+ await writeFile(temporary,JSON.stringify(project,null,2)+'\n');await rename(temporary,target);await buildWorld(root);+ return send(200,{project:await current()});+ }finally{saving=false;}+ }+ if(path==='/api/files'&&req.method==='GET')return send(200,{files:await recent()});+ if(path==='/api/open'&&req.method==='POST')return send(200,{project:await picked((await body()).path)});+ if(req.method!=='GET'&&req.method!=='HEAD')return send(405,{error:'Method not allowed.'});+ if(path==='/'){const html=await readFile(join(root,'world/index.html'));return send(200,req.method==='HEAD'?'':html,'text/html; charset=utf-8');}+ if(!path.startsWith('/files/'))return send(404,{error:'Not found.'});+ const name=path.slice(7);if(name.split(/[\\/]/).some(s=>s.startsWith('.')||s==='node_modules'))return send(404,{error:'Not found.'});+ const file=await realpath(join(root,name));if(!file.startsWith(root+sep)||relative(root,file).split(sep).some(s=>s.startsWith('.')))return send(404,{error:'Not found.'});+ const info=await stat(file);if(!info.isFile()||info.size>48000000)return send(413,{error:'File unavailable or too large.'});+ const mime={'.html':'text/html; charset=utf-8','.svg':'image/svg+xml','.png':'image/png','.pdf':'application/pdf','.json':'application/json','.ttf':'font/ttf'}[extname(file)]??'application/octet-stream';+ return send(200,req.method==='HEAD'?'':await readFile(file),mime==='application/json'?'application/json; charset=utf-8':mime);+ }catch(error){return send(400,{error:error.code==='ENOENT'?'That file is not available.':error.message});}+ });+ return server;+}+if(process.argv[1]&&resolve(process.argv[1])===fileURLToPath(import.meta.url)){+ if(!process.env.HARNESS_WORKSPACE)throw new Error('HARNESS_WORKSPACE is required.');+ const port=Number(process.env.HARNESS_VIEWER_PORT);if(!Number.isInteger(port)||port<1||port>65535)throw new Error('HARNESS_VIEWER_PORT must be valid.');+ const server=await createWorldViewer(process.env.HARNESS_WORKSPACE);server.listen(port,'127.0.0.1',()=>console.log(`[tidelands] http://127.0.0.1:${port}/`));+ for(const signal of ['SIGINT','SIGTERM'])process.once(signal,()=>{server.closeAllConnections();server.close();});+}diff --git a/store/showcase/voxel-worlds/amber-vault.jpg b/store/showcase/voxel-worlds/amber-vault.jpgnew file mode 100644index 000000000..6f83a5e65Binary files /dev/null and b/store/showcase/voxel-worlds/amber-vault.jpg differdiff --git a/store/showcase/voxel-worlds/civic-court.jpg b/store/showcase/voxel-worlds/civic-court.jpgnew file mode 100644index 000000000..e63c4dfe7Binary files /dev/null and b/store/showcase/voxel-worlds/civic-court.jpg differdiff --git a/store/showcase/voxel-worlds/starter.jpg b/store/showcase/voxel-worlds/starter.jpgindex fab5eed52..0cac75f54 100644Binary files a/store/showcase/voxel-worlds/starter.jpg and b/store/showcase/voxel-worlds/starter.jpg differdiff --git a/store/tools/build-experiences.mjs b/store/tools/build-experiences.mjsindex a7187e97c..9a2a618ca 100644--- a/store/tools/build-experiences.mjs+++ b/store/tools/build-experiences.mjs@@ -6,6 +6,7 @@ import { resolve } from "node:path";import { buildArt } from "../agents/generative-art/template/tools/build.mjs";import { buildMusic } from "../agents/music-studio/template/tools/build.mjs";import { buildBrand } from "../agents/creative-direction/template/tools/build.mjs";+import { buildWorld } from "../agents/voxel-worlds/template/tools/build.mjs";const source = new URL("./experiences/", import.meta.url);export const experiences = [{@@ -61,7 +62,7 @@ export async function build({ check = false } = {}) {]);let drift = false;for (const exp of experiences) {- if (["generative-art", "music-studio", "creative-direction"].includes(exp.id)) {+ if (["generative-art", "music-studio", "creative-direction", "voxel-worlds"].includes(exp.id)) {try {const packageRoot = new URL(`../agents/${exp.id}/`, import.meta.url);const icon = await readFile(new URL('brand/icon.svg', packageRoot), 'utf8');@@ -69,7 +70,7 @@ export async function build({ check = false } = {}) {if (check) {if (await readFile(studioIcon, 'utf8') !== icon) throw new Error(`${exp.id}: packaged studio icon is out of date.`);} else await writeFile(studioIcon, icon);- const builder = { 'generative-art': buildArt, 'music-studio': buildMusic, 'creative-direction': buildBrand }[exp.id];+ const builder = { 'generative-art': buildArt, 'music-studio': buildMusic, 'creative-direction': buildBrand, 'voxel-worlds': buildWorld }[exp.id];await builder(fileURLToPath(new URL(`../agents/${exp.id}/template/`, import.meta.url)), { check });} catch (error) {if (!check) throw error;diff --git a/store/tools/experience-tests/browser.mjs b/store/tools/experience-tests/browser.mjsindex fee66c400..4fc716816 100644--- a/store/tools/experience-tests/browser.mjs+++ b/store/tools/experience-tests/browser.mjs@@ -109,6 +109,11 @@ async function shellRegression() {}async function one(exp) {+ if (exp.id === 'voxel-worlds') {+ const result = execFileSync(process.execPath, [join(repo, 'store/agents/voxel-worlds/test/browser.mjs')], { env: { ...process.env, VOXEL_QA_ROOT: join(output, 'tidelands-browser') }, encoding: 'utf8', timeout: 180000 });+ results.push({ id: exp.id, ...JSON.parse(result.trim()) });+ return;+ }if (exp.id === 'creative-direction') {results.push(await brandBrowser({ browser, output }));return;diff --git a/work/FIVE-REBUILDS.md b/work/FIVE-REBUILDS.mdindex 09574d31b..6484466d1 100644--- a/work/FIVE-REBUILDS.md+++ b/work/FIVE-REBUILDS.md@@ -4,10 +4,12 @@ User direction: improve the remaining five one by one. Each must help a person cuseful work. Preserve the old implementations. Publish each finished rebuild through the Storeso the user can test it, then move to the next. Do not claim a subjective “wow” from passing tests.-1. **Creative Direction — rebuilt; publication in progress.** A business brief and supplied+1. **Creative Direction — published (#141).** A business brief and suppliedmaterials become an editable identity, coordinated launch assets, a responsive website and aportable brand guide. See [tested deliverables and remaining evidence](FORME-REBUILD.md).-2. **Voxel Worlds — pending.** Original playable world creation and an independently usable handoff.+2. **Voxel Worlds — rebuilt; publication in progress.** Named object editing, sculpting, source saves,+ physical walking, VOX import and independent GLB/VOX/offline delivery. See+ [the acceptance evidence](../store/agents/voxel-worlds/test/ACCEPTANCE.md).3. **Drone Pilot — pending.** Useful planning/analysis with actual inputs and explicit simulationboundaries. No claim that a simulation authorizes or validates a real flight.4. **Game Master — pending.** Create and revise original playable games, then deliver working builds.